Fix reference-counting issues.

- Loops need to unreference at the very end.
- Declarations can be executed more than once, so we need to initialise
  memory slots with some null value that reference-counting will ignore.
- It doesn't make sense to declare a variable in after-clause of for
  loop and then use it in the body; it will be uninitialised on the
  first round.