fixed group by, and a little refactoring