Rewrite, simplify the grouping, add proper range checking