Improved code

Improved conditional queries.