;; CADLisp Tools - Pipeline Length by Layer
(vl-load-com)

(defun ct-pl:add (key amount items / hit)
  (if (setq hit (assoc key items))
    (subst (cons key (+ amount (cdr hit))) hit items)
    (cons (cons key amount) items)))

(defun ct-pl:length (ent / data end flags result)
  (setq data (and ent (entget ent)))
  (if (and data
           (or (= (cdr (assoc 0 data)) "LWPOLYLINE")
               (and (= (cdr (assoc 0 data)) "POLYLINE")
                    (setq flags (cdr (assoc 70 data)))
                    (= 0 (logand flags 80))))
           (not (vl-catch-all-error-p
                  (setq end (vl-catch-all-apply 'vlax-curve-getEndParam (list ent)))))
           (not (vl-catch-all-error-p
                  (setq result (vl-catch-all-apply 'vlax-curve-getDistAtParam (list ent end))))))
    result))

(defun c:PIPELEN (/ data ent i layer length pair skipped ss totals)
  (prompt "\nSelect pipeline polylines: ")
  (if (setq ss (ssget '((0 . "LWPOLYLINE,POLYLINE"))))
    (progn
      (setq i 0 totals nil skipped 0)
      (repeat (sslength ss)
        (setq ent (ssname ss i) data (and ent (entget ent))
              layer (and data (cdr (assoc 8 data))) length (ct-pl:length ent))
        (if (and layer length)
          (setq totals (ct-pl:add layer length totals))
          (setq skipped (1+ skipped)))
        (setq i (1+ i)))
      (prompt "\n--- Pipeline length by layer ---")
      (foreach pair (vl-sort totals '(lambda (a b) (< (strcase (car a)) (strcase (car b)))))
        (prompt (strcat "\n" (car pair) ": " (rtos (cdr pair) 2 3))))
      (prompt (strcat "\nUnsupported or invalid polylines skipped: " (itoa skipped))))
    (prompt "\nNo pipeline polylines selected."))
  (princ))
