Fix order by issue + some refactoring