Refactor main handler