Major refactoring, fixing and cleaning up