; ---- Eliminate the tiny, unwanted connections with a cutoff in the 
;         (cell_area, worst_bounding_path_score) plane ----

;      if outside cutoff, remove the worst_bounding_path

; ---- Segmentation & Unique Path Labeling ----
(ns Path_Finder.src.tinycell)

(use 'Path_Finder.src.drawing)
(import BinaryLabel_)

(defn remove-tiny-cells [path_img
                         good_path_ids
                         paths
                         scores
                         small_cell_area_cutoff]
  
  (def path_img_b  (make-16bit-img "Paths" "blue orange icb" (.getWidth path_img) (.getHeight path_img)))
  (def path_proc_b (.convertToByte (.getProcessor path_img) true))
  (.threshold path_proc_b 0)
  (.invert path_proc_b)
  (.setProcessor path_img_b path_proc_b)

  ; (exec [ImagePlus Name white-particles? 4-connected?])
  (let [result (.exec (BinaryLabel_.) path_img_b "Labelled" true true)]
    (def result_img (aget result 1)))

  ; convert default 32-bit imgs. 16-bit is still big enough to uniquely label paths
  (def result_proc (.. result_img getProcessor (convertToShort false)))
  (.setProcessor result_img result_proc)
  (.show result_img)

  ; add paths to img mapped by unique-id
  (let [paths   (map #(paths %)  good_path_ids)
        big_ids (map #(+ 1000 %) good_path_ids)]
    (redraw-paths (map list paths big_ids) result_proc))
  (.close path_img_b)

  (ij.IJ/log "Creating Mapping…")

  ; ---- Create Cell → [Paths] mapping ----
  (def mapping (atom {}))
  (doseq [i (range 1 (dec (.getWidth path_img))) 
          j (range 1 (dec (.getHeight path_img)))
          :let [mykey (.get result_proc i j)]
          :when (< 1 mykey 1000)] ; ignore background labelled 1
    (let [
        ; values of 4-connected neibs
        nvals (map #(.get result_proc (+ i %1) (+ j %2)) [1 -1 0 0] [0 0 1 -1])
        ; keep the ones that are path-ids
        gdns  (filter #(> % 1000) nvals)
        ; get set of values mapped-to by key
        ;   if it's new, then return the empty set
        ;   then add all the new path values to the set
        s (into (@mapping mykey #{}) gdns)]
      ; update mapping with the new set!
      (swap! mapping #(assoc % mykey s))))

  (ij.IJ/log "Done with Mapping")

  ; Now use `mapping` to eliminate the small cells
  (def histo (.getHistogram result_proc))
  (def cell_ids (range 1 (inc (count @mapping))))
  (def cell_area (map #(aget histo %) cell_ids))
  (def small_cells (filter #(> small_cell_area_cutoff (first %)) (map list cell_area cell_ids)))
  (def path_sets (map #(@mapping (second %)) small_cells))
  (let [f1 (fn [elem] (- elem 1000)) ; convert back to normal path_id
        f2 (fn [elem] [elem (scores elem)])
        f3 (fn [set]  (map (comp f2 f1) set))
        f4 (fn [lst]  (sort-by second lst))]
    (def paths_to_remove (map (comp last f4 f3) path_sets)))
  (.close result_img)
  
  ; this gives a list of [path_id score] to remove
  (set (map first paths_to_remove)))
  