Fixed/simplified sorting issue. Added a test