Adding sorting. A little refactoring.