Simplified query and implmented logic to adhere to constraints passed in
as arguments.