Major refactoring and documentation; probably breaks lots of things