Refactored (improved) the code, added copious comments