Code cleanup and refactor