Revamped the WHERE and HAVING clauses so they share the same code. Bug fixes, optimisations, and readability.