Refactoring, Type-safety, Minor performance improvements

Replacement for #509