Started refactoring mega-function