Reorganized event handler code