fix scoping issues

### Purpose

Scope variables locally so that they don't bleed into the variables scope and create possible race conditions.

I've tried to stick to the same coding style where possible.