This cleans up the code even more, unifying the different cases into one simple approach. Added a unit test to verify the result.