added optional log, moved the queries to the right place