Major refactoring; also, preliminary work for #7