Refactor plugin

* Use better and more consitent variable names
* Extract local functions to simplify logic
* Make non-public functions local
* Add rake task for running tests
@christoomey I've tried to simplify this logic, but unfortunately there are four branches that reflect four situations.