refactor huge function