Refactored the fix for issue #14

The former solution did not cover all use cases and needed some
additional code to make it all work as expected.