Completely reworked version. 
Removed many globals.