added sorting and fixed some bugs.