fixed the algorithm, and added comments