Simple code fix needed

Hi, I’m trying to write a basic code for pushing a button and letting an LED turn on, while increasing the intensity of the light when the button is pressed for a longer time. However i keep getting error messages near the end of my code and i can’t figure out how to fix it. Could someone please help me out? Thanks

Code:

const int LED = 9;
const int button = 7;
int val = 0;
int old_val = 0;
unsigned long startTime = 0;
int state = 0;
int brightness = 512; //check

void setup ()
{
  pinMode (LED, OUTPUT);
  pinMode (button, INPUT);
}

void loop ()
{
  val = digitalRead(button);

  if ((val == HIGH) && (old_val == LOW))
  { state = 1 - state;
    startTime = millis();
    delay(10);
  }

  if ((val == HIGH) && (old_val == HIGH))
  { if ((state == 1) && (millis() - startTime > 500))
    { brightness++;
      delay(10);
    }
    if (brightness > 1022) {
      brightness = 0;
    }
  }
}
old_val = val;
if (state == 1) {
  analogWrite(LED, brightness);
}
else {
  analogWrite(LED, 0)
}
}

Error messages:

Arduino: 1.8.5 (Mac OS X), Board: "Arduino/Genuino Uno"

The sketch name had to be modified. Sketch names can only consist
of ASCII characters and numbers and be less than 64 characters long.

Build options changed, rebuilding all
LED_button_5:35: error: 'old_val' does not name a type
old_val = val;
^
LED_button_5:36: error: expected unqualified-id before 'if'
if (state == 1) {
^
LED_button_5:39: error: expected unqualified-id before 'else'
else {
^
LED_button_5:42: error: expected declaration before '}' token
}
^
exit status 1
'old_val' does not name a type

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

LED_button_5.ino (674 Bytes)

If possible you should always post code directly in the forum thread as text using code tags (</> button on the toolbar). This will make it easy for anyone to look at it, which will increase the likelihood of you getting help. If the sketch is longer than the forum will allow then it’s ok to add it as an attachment but in this case the sketch is plenty short enough to just post directly.

When you encounter an error you’ll see a button on the right side of the orange bar “Copy error messages”. Click that button. Paste the error in a message here USING CODE TAGS (</> button on the toolbar).

If you read the "How to use this forum - please read" post at the top of the forum and post your code as directed in there and then you also post details of the "error messages near the end of my code" that you are getting as mentioned in there...then very likely someone can help.

Steve

Could someone please help me out?

If you used Tools + Auto Format (or half a brain cell while typing the code), you'd see where loop() ends, and that there is code following the end of loop(). That is NOT allowed.