Fixed conditional queries

And added logging-functionality