add sorting and other bug fixes