cleans up the code and shortens it by about 30 lines