simplified logic, fixed a bug