Updated Code

Handwritten code, debugged using JSFiddle