Fix for #544

ALso included some refactorings that were driven by changes to fix #544. Depends on #546 fix, merge that first.