Massive refactor. Logic is mostly the same, but a lot of duplicated code was eliminated.
Code clean up and doc blocks