Bug fixes

Various bug fixes (and one new helper function squeezed in)