Key refactoring of core classes

This contains fixes for #7, #8 and #9, as well as lots of other housekeeping.