Fixed sorting and added option to reverse the output sorting