attempt to fix sorting, code cleanup