Refactor / decompose main file handler code