       (cond (>= i (count table))
             (compressed-table table equiv)
             
-            (or (>= j (count gens)) (not= i (pfind equiv i)))
+            (or (>= j (count gens)) (not= i (equiv i)))
             (recur table equiv (inc i) 0)
             
             ((table i) (get gens j))

(defn- scan-relations [rels subgens table equiv n]
  (let [[table equiv]
        (reduce (fn [[t p] w] (scan t p w n)) [table equiv] rels)]
    (reduce (fn [[t p] w] (scan t p w (pfind equiv 0))) [table equiv] subgens)))

(defn- compressed-table [table equiv]
  (let [reps (into #{} (filter #(= % (pfind equiv %)) (keys table)))
        rep-to-idx (into {} (map vector reps (range)))
        canon (comp rep-to-idx (partial pfind equiv))]
    (into {} (for [[i row] table :when (reps i)]
               [(canon i) (into {} (map (fn [[j v]] [j (canon v)]) row))]))))

(defn coset-table [nr-gens relators subgroup-gens]
  (let [with-inverses (fn [ws] (vec (into #{} (concat ws (map inverse ws)))))

         equiv equiv]
    (if-let [[i j] (first q)]
      (let [q (pop q)
            a (equiv i)
            b (equiv j)]
        (if (= a b)
          (recur q table equiv)
          (let [equiv (conj equiv [a b])
                [table q] (merge-rows table equiv q a b)]
            (recur q table equiv))))
      [table equiv])))
