General code refactor and clean up