extracted helper methods, tweaked style, made suggestions in comments