Throughout, I've added 'declare' to variable declarations.  Think of it just like Perl's 'local'.