seanbo, jarich, dvergin - thanks for all your help.
I think my main problem was trying to sort text using the spaceship operator - very silly indeed and guaranteed to screw up... I've fixed the sort routine so that it sorts asciibetically and then numerically which seems to have solved everything.