Major code cleanup. Removed a bunch of global variables. Re-organized code to be more modular and reusable.