Much needed clean up and refactoring