Redoing changes for #164 from dev branch (#167)

This should be possible to merge now.