Added lots of doc blocks, refactored everything