Fixed: performance issues

Things can still be improved but it's much better now.
I also found and fix a bug in sort algorithm.