Vastly clean up handler code, much more sensible and readable now.