Sorting filenames refactored

There were two sorting methods with almost the same code, abstracted them into a common method.