;; CADLisp Tools - Change Text Case
(defun ct-tc:editable-p (data / row flags)
  (and data
       (setq row (tblsearch "LAYER" (cdr (assoc 8 data))))
       (setq flags (cdr (assoc 70 row)))
       (= 0 (logand flags 20))))

(defun ct-tc:text-value (data / pair value)
  (setq value "")
  (foreach pair data
    (if (member (car pair) '(1 3)) (setq value (strcat value (cdr pair)))))
  value)

(defun ct-tc:control-code-p (value / character found index)
  (setq index 1 found nil)
  (while (and (not found) (<= index (strlen value)))
    (setq character (substr value index 1)
          found (member character '("\\" "{" "}"))
          index (1+ index)))
  (if found T nil))

(defun ct-tc:formatted-mtext-p (data value)
  (and (= (cdr (assoc 0 data)) "MTEXT") (ct-tc:control-code-p value)))

(defun ct-tc:text-pairs (value / pairs)
  (setq pairs nil)
  (while (> (strlen value) 250)
    (setq pairs (cons (cons 3 (substr value 1 250)) pairs)
          value (substr value 251)))
  (reverse (cons (cons 1 value) pairs)))

(defun ct-tc:set-value (data value / inserted item new out pair)
  (setq inserted nil new (ct-tc:text-pairs value) out nil)
  (foreach pair data
    (if (member (car pair) '(1 3))
      (if (not inserted)
        (progn
          (foreach item new (setq out (cons item out)))
          (setq inserted T)))
      (setq out (cons pair out))))
  (reverse out))

(defun c:TEXTCASE (/ *error* changed data ent i lower mode old skipped ss undo-started)
  (defun *error* (message)
    (if undo-started (command-s "_.UNDO" "_End"))
    (if (and message (not (wcmatch (strcase message) "*CANCEL*,*QUIT*,*EXIT*")))
      (prompt (strcat "\nTEXTCASE error: " message)))
    (princ))
  (initget "Upper Lower")
  (setq mode (getkword "\nCase [Upper/Lower] <Upper>: ") lower (= mode "Lower"))
  (prompt "\nSelect TEXT or unformatted MTEXT: ")
  (if (setq ss (ssget '((0 . "TEXT,MTEXT"))))
    (progn
      (setq changed 0 skipped 0)
      (if (= 0 (logand 8 (getvar "UNDOCTL")))
        (progn (command "_.UNDO" "_Begin") (setq undo-started T)))
      (repeat (setq i (sslength ss))
        (setq ent (ssname ss (setq i (1- i))) data (and ent (entget ent))
              old (and data (ct-tc:text-value data)))
        (if (and (ct-tc:editable-p data) old (not (ct-tc:formatted-mtext-p data old))
                 (entmod (ct-tc:set-value data (strcase old lower))))
          (progn (entupd ent) (setq changed (1+ changed)))
          (setq skipped (1+ skipped))))
      (if undo-started (progn (command "_.UNDO" "_End") (setq undo-started nil)))
      (prompt (strcat "\nUpdated " (itoa changed) " object(s); skipped " (itoa skipped)
                      " locked, referenced, invalid, or formatted MTEXT object(s).")))
    (prompt "\nNo text selected."))
  (princ))
