reworked sorting and output