Optimized queries and removed some from foreach loops
Added more sorting alternatives, cleaned up some code.