More work to make #34 work for all cases; some refactoring