Proposed fix for #1280

This PR proposes a fix for #1280, and #1676.

It is not ready to be merged, as I need a few more tests. 

Input for tests are very welcome.
Yes that looks right. Would probably have caught that with a unit test. Any suggestions on where to put them. That is really what is holding me back from going forward with this PR. This is just the result of one night of hacking around, and needs to be covered in tests before it can be considered for merging.