Some performance improvements. Fix sorting issue.