fully refactored code. Allows for better checks and query filters