New fix for issue 966

This pull request supercedes #1036. I have implemented the suggested changes from that pull request, and it works with all of the current tests. I have not yet written any new tests, but I would like to get some feedback about the code if possible. Thanks!