Whole bunch of refactoring and comments