Infinite loop bug

The bug is described and triggerd in the unit test included in this pull request.