Cleaned up code, changed to use less SQL queries