Major clean up and refactor of code