Cleaned up code and implemented DB sorting