cleaned up the code, now almost down to 100 lines