Code cleanup and small sorting bugfix