Code cleanup debugged

Tested and fixed code in Chrome.