Fixed bugs and implemented sorting routine.