Initial refactoring and formatting. Divide the code in meaningful groups.