Fix for #40, #29 and #31

This PR adresses the issues #40, #31 and #29. For #40 I added a regression test.