cleaned up a large portion of code, reoredered some functions for clarity. Functionallity should remain unchanged