Formatting

Fixed some of the formatting and comments.
Variable scope

All global variables replaced with local variables. state variable was
removed.