;; CADLisp Tools - BOM from Block Attributes
(vl-load-com)

(defun ct-bb:bump (key items / hit)
  (if (setq hit (assoc key items))
    (subst (cons key (1+ (cdr hit))) hit items)
    (cons (cons key 1) items)))

(defun ct-bb:invoke-list (obj method / result)
  (setq result (vl-catch-all-apply 'vlax-invoke (list obj method)))
  (if (vl-catch-all-error-p result) nil result))

(defun ct-bb:attributes (obj)
  (append (ct-bb:invoke-list obj 'GetAttributes)
          (ct-bb:invoke-list obj 'GetConstantAttributes)))

(defun ct-bb:property (object getter / result)
  (setq result (vl-catch-all-apply getter (list object)))
  (if (vl-catch-all-error-p result) nil result))

(defun c:BLOCKBOM (/ att attrs counts ent i obj pair skipped ss tag tag-name value)
  (setq tag (strcase (getstring T "\nAttribute tag to group by: ")))
  (if (= tag "")
    (prompt "\nAttribute tag cannot be blank.")
    (progn
      (prompt "\nSelect attributed blocks: ")
      (if (setq ss (ssget '((0 . "INSERT"))))
        (progn
          (setq i 0 counts nil skipped 0)
          (repeat (sslength ss)
            (setq ent (ssname ss i)
                  obj (and ent (vl-catch-all-apply 'vlax-ename->vla-object (list ent)))
                  value nil)
            (if (and obj (not (vl-catch-all-error-p obj)))
              (progn
                (setq attrs (ct-bb:attributes obj))
                (foreach att attrs
                  (setq tag-name (ct-bb:property att 'vla-get-TagString))
                  (if (and tag-name (= (strcase tag-name) tag))
                    (setq value (ct-bb:property att 'vla-get-TextString))))))
            (if value
              (setq counts (ct-bb:bump value counts))
              (setq skipped (1+ skipped)))
            (setq i (1+ i)))
          (prompt "\n--- Attribute BOM ---")
          (foreach pair (vl-sort counts '(lambda (a b) (< (strcase (car a)) (strcase (car b)))))
            (prompt (strcat "\n" (if (= (car pair) "") "<blank>" (car pair))
                            ": " (itoa (cdr pair)))))
          (prompt (strcat "\nBlocks missing a readable matching tag: " (itoa skipped))))
        (prompt "\nNo attributed blocks selected."))))
  (princ))
