added comments and cleaned up logic a bit