refactor 400 line method to be more manageable