Clean up code, fix bug where a second query isn't processed right