Bugfix in sorting function