Re-wrote some of the code for better quality