Fixed a couple of silly logic errors and simplified the SQL statement processing loop.