Fixed error in query. Sorry, my fault =)
Fixed some errors in logic