Refactoring and cleanup

Fixes #124