large rewrite to use prepared statements multiple times; multiple bug fixes