added comments, re-organized logic.