debugged next_event algorithm