fixed bugs in querying output db and constructing csv