Query script - very bad code