checking well formed brackets and modifying query