Copied from MrDoor for refactoring

Lots of bad var patterns, global issues, inefficient for loops, etc. Need fixing.