Fixes and adds a test for #321, although there are still some cases that will fail.