Fixed a bug introduced in 61cd792793679535198a4d95bfbfb329643fcf38

Also added some tests to handle similar issues in future