various code improvements

* break out some complicated logic into seperate methods
* reduce logic redundancy
* improve readability of long lines
* clean up some whitespace