Query code cleaned up