turned spaghetti code into working, jslint acceptable code