Tidy up code - update logic and make code pass jslint