Cleanup and refactoring of the code