Cleaned up the code to make it smarter