Error checking.
Removed some globals, added some arguments...