Tidy up of SQL queries and minor bug fixes