Cleaned up the code, added commenting