fixed sorting in makeOrderedLeafList, added test cases to cover bug scenario, reduced complexity in encode