Major clean up and refactoring of code