Refactored for increased testability. Added tests around functionality.