fixed tie breaking, changed order of grouping and sorting