Cleaning up code, adding debug mode. Added comments as necessary.