Enormous refactoring. Fixes #9. Fixes #7. #4