Major refactoring

Fixes #4 and fixes #5