A general solution to issue #332

Also added some tests.