refactored large methods into helper methods, plus some style improvements