Clean up and make the code logic cleaner