Major refactoring and documenting pass