finished version with queries