Cleaned up the code and reduced the database queries