Final changes - cleaned up the code and added comments