;;; SELTOOLS v1.5 - Myo Myint Maung / dailypainkiller.com
;;; AutoCAD Windows / Visual LISP. APPLOAD, then SELTOOLS.
;;; BlocksInsideRectangle: pick a closed 4-vertex LWPOLYLINE rectangle.
;;; Supports rotated rectangles. Checks main block geometry and nested blocks;
;;; excludes ATTDEF and attached ATTRIB. Ordinary TEXT/MTEXT remains geometry.
;;; Rectangle selection: current layout, no drawing changes.
;;; MoveMid: nearest WCS XY points on two finite edges, then their midpoint.
;;; Lines, polylines, circles and arcs; nested/locked reference edges supported.
;;; Numerical curve minimisation; preserve block Z,
;;; rotation and scale. Ignore attributes; nested geometry included.
;;; All user input and geometry checks finish before the Undo group starts.
;;; Uses conservative per-entity bounds: never deliberately includes crossing
;;; geometry, but curved/irregular geometry near an edge may be omitted.
;;; Boundary touching allowed within 1e-7 drawing units. Tests 2D footprint
;;; projected onto the rectangle plane; no depth/height restriction.
;;; Xrefs, MINSERT arrays, cycles and unreadable geometry skipped.
;;; Dynamic hidden geometry may enlarge bounds; test such blocks separately.
;;; Static checks only; test on a drawing copy in AutoCAD.
(vl-load-com)

(defun ST:Value (data code fallback / pair)
  (if (setq pair (assoc code data)) (cdr pair) fallback))
(defun ST:Dot (a b) (apply '+ (mapcar '* a b)))
(defun ST:Sub (a b) (mapcar '- a b))
(defun ST:Unit (a / size)
  (setq size (sqrt (ST:Dot a a)))
  (if (> size 1e-12) (mapcar '(lambda (x) (/ x size)) a)))

(defun ST:Rectangle (ent / data normal elevation points pair p edges a b c d)
  (setq data (entget ent))
  (if (and (= "LWPOLYLINE" (cdr (assoc 0 data)))
           (= 1 (logand 1 (ST:Value data 70 0)))
           (= 4 (ST:Value data 90 0))
           (= 0.0 (ST:Value data 39 0.0)))
    (progn
      (setq normal (ST:Value data 210 '(0.0 0.0 1.0))
            elevation (ST:Value data 38 0.0) points nil)
      (foreach pair data
        (if (= 10 (car pair))
          (setq points (cons (trans (list (cadr pair) (caddr pair) elevation) normal 0) points))))
      (setq points (reverse points))
      (if (not (vl-some '(lambda (x) (and (= 42 (car x)) (/= 0.0 (cdr x)))) data))
        (progn
          (setq p (car points)
                a (ST:Sub (nth 1 points) p)
                b (ST:Sub (nth 2 points) (nth 1 points))
                c (ST:Sub (nth 3 points) (nth 2 points))
                d (ST:Sub p (nth 3 points)))
          (if (and (ST:Unit a) (ST:Unit b)
                   (< (abs (ST:Dot (ST:Unit a) (ST:Unit b))) 1e-8)
                   (equal a (mapcar '- c) 1e-7)
                   (equal b (mapcar '- d) 1e-7))
            (list p (ST:Unit a) (ST:Unit b)
              (sqrt (ST:Dot a a)) (sqrt (ST:Dot b b)))))))))

(defun ST:Transform (p data / name base normal insertion angle x y z scaled)
  (setq name (cdr (assoc 2 data))
        base (ST:Value (tblsearch "BLOCK" name) 10 '(0.0 0.0 0.0))
        normal (ST:Value data 210 '(0.0 0.0 1.0))
        insertion (trans (ST:Value data 10 '(0.0 0.0 0.0)) normal 0)
        angle (ST:Value data 50 0.0)
        scaled (mapcar '* (ST:Sub p base)
          (list (ST:Value data 41 1.0) (ST:Value data 42 1.0) (ST:Value data 43 1.0)))
        x (car scaled) y (cadr scaled) z (caddr scaled))
  (mapcar '+ insertion
    (trans (list (- (* x (cos angle)) (* y (sin angle)))
                 (+ (* x (sin angle)) (* y (cos angle))) z) normal 0 T)))

(defun ST:Within (point chain / transform q x y)
  ;; Chain ordered innermost to outermost; no dependence on the current UCS.
  (foreach transform chain (setq point (ST:Transform point transform)))
  (setq q (ST:Sub point (car rectangle))
        x (ST:Dot q (cadr rectangle)) y (ST:Dot q (caddr rectangle)))
  (and (>= x (- tolerance)) (<= x (+ (nth 3 rectangle) tolerance))
       (>= y (- tolerance)) (<= y (+ (nth 4 rectangle) tolerance))))

(defun ST:Bounds (ent / entry low high x y z corners)
  (if (setq entry (assoc ent boundsCache))
    (cdr entry)
    (progn
      (vla-GetBoundingBox (vlax-ename->vla-object ent) 'low 'high)
      (setq low (vlax-safearray->list low) high (vlax-safearray->list high))
      (foreach x (list (car low) (car high))
        (foreach y (list (cadr low) (cadr high))
          (foreach z (list (caddr low) (caddr high))
            (setq corners (cons (list x y z) corners)))))
      (setq boundsCache (cons (cons ent corners) boundsCache))
      corners)))

(defun ST:CheckInsert (data chain path / name record ent info typ result child points)
  (setq name (cdr (assoc 2 data)) record (tblsearch "BLOCK" name))
  (if (or (null record) (member (strcase name) path)
          (/= 0 (logand 28 (ST:Value record 70 0)))
          (> (ST:Value data 70 1) 1) (> (ST:Value data 71 1) 1))
    'Unknown
    (progn
      (setq chain (cons data chain) path (cons (strcase name) path)
            ent (entnext (tblobjname "BLOCK" name)) result 'Empty)
      (while (and ent (not (member result '(Outside Unknown)))
                  (setq info (entget ent)) (/= "ENDBLK" (setq typ (cdr (assoc 0 info)))))
        (cond
          ((member typ '("ATTDEF" "ATTRIB" "SEQEND" "VERTEX")))
          ((= typ "INSERT")
            (setq child (ST:CheckInsert info chain path))
            (if (not (eq child 'Empty)) (setq result child)))
          (T
            (setq points (vl-catch-all-apply 'ST:Bounds (list ent)))
            (if (vl-catch-all-error-p points)
              (setq result 'Unknown)
              (if (vl-every '(lambda (p) (ST:Within p chain)) points)
                (setq result 'Inside) (setq result 'Outside)))))
        (setq ent (entnext ent)))
      result)))

(defun ST:SelectInside (/ pick rectangle tolerance boundsCache all selected
                    index ent result outside unknown)
  (setq pick (entsel "\nPick a closed rectangular polyline (Enter to cancel): "))
  (cond
    ((null pick) (princ "\nCancelled."))
    ((not (setq rectangle (ST:Rectangle (car pick))))
      (princ "\nUse a closed 4-vertex rectangular LWPOLYLINE with straight edges and no thickness."))
    (T
      (setq tolerance 1e-7 boundsCache nil selected (ssadd)
            outside 0 unknown 0 index 0
            all (ssget "_X" (list '(0 . "INSERT") (cons 410 (getvar "CTAB")))))
      (princ "\nChecking main geometry; attributes excluded. Current layout only...")
      (if all
        (repeat (sslength all)
          (setq ent (ssname all index)
                result (vl-catch-all-apply 'ST:CheckInsert (list (entget ent) nil nil)))
          (cond
            ((and (not (vl-catch-all-error-p result)) (eq result 'Inside)) (ssadd ent selected))
            ((and (not (vl-catch-all-error-p result)) (eq result 'Outside)) (setq outside (1+ outside)))
            (T (setq unknown (1+ unknown))))
          (setq index (1+ index))))
      (sssetfirst nil (if (> (sslength selected) 0) selected nil))
      (princ (strcat "\nSelected: " (itoa (sslength selected))
        "; outside/crossing bounds: " (itoa outside) "; unsupported/empty: " (itoa unknown) "."))
      (princ "\nCurved/irregular geometry near edges may be conservatively omitted.")))
  (princ))


(defun ST:Accumulate (p chain / transform)
  (foreach transform chain (setq p (ST:Transform p transform)))
  (if geometryLow
    (setq geometryLow (mapcar 'min geometryLow p)
          geometryHigh (mapcar 'max geometryHigh p))
    (setq geometryLow p geometryHigh p)))

(defun ST:Geometry (data chain path / name record ent info typ valid points child)
  (setq name (cdr (assoc 2 data)) record (tblsearch "BLOCK" name))
  (if (or (null record) (member (strcase name) path)
          (/= 0 (logand 28 (ST:Value record 70 0)))
          (> (ST:Value data 70 1) 1) (> (ST:Value data 71 1) 1))
    nil
    (progn
      (setq chain (cons data chain) path (cons (strcase name) path)
            ent (entnext (tblobjname "BLOCK" name)) valid T)
      (while (and ent valid (setq info (entget ent))
                  (/= "ENDBLK" (setq typ (cdr (assoc 0 info)))))
        (cond
          ((member typ '("ATTDEF" "ATTRIB" "SEQEND" "VERTEX")))
          ((= typ "INSERT") (setq valid (ST:Geometry info chain path)))
          (T
            (setq points (vl-catch-all-apply 'ST:Bounds (list ent)))
            (if (vl-catch-all-error-p points)
              (setq valid nil)
              (foreach child points (ST:Accumulate child chain)))))
        (setq ent (entnext ent)))
      valid)))

(defun ST:GeometryCenter (ent / geometryLow geometryHigh valid)
  (setq valid (ST:Geometry (entget ent) nil nil))
  (if (and valid geometryLow geometryHigh)
    (mapcar '(lambda (a b) (/ (+ a b) 2.0)) geometryLow geometryHigh)))

;;; Read-only nested edge selection: no copies, exploding or unlocking.
(defun ST:PickEdge (prompt / pick ent data kind start end done answer)
  (while (not done)
    (setq pick (nentselp prompt))
    (if (null pick)
      (setq done T)
      (progn
        (setq ent (car pick) data (entget ent) kind (cdr (assoc 0 data)))
        ;; Legacy POLYLINE selection may return its VERTEX subentity.
        (if (= kind "VERTEX")
          (progn
            (while (and ent (/= "SEQEND" (cdr (assoc 0 (entget ent)))))
              (setq ent (entnext ent)))
            (if ent (setq ent (cdr (assoc -2 (entget ent)))))
            (setq data (if ent (entget ent)) kind (cdr (assoc 0 data)))))
        (if (and (member kind '("LINE" "LWPOLYLINE" "POLYLINE" "CIRCLE" "ARC"))
                 (not (and (= kind "POLYLINE")
                   (/= 0 (logand 80 (ST:Value data 70 0))))))
          (progn
            (setq start (vl-catch-all-apply 'vlax-curve-getStartParam (list ent))
                  end (vl-catch-all-apply 'vlax-curve-getEndParam (list ent)))
            (if (and (numberp start) (numberp end) (> end start))
              (setq done T answer (list ent (caddr pick) start end kind))
              (princ "\nThis edge cannot be read; pick another edge.")))
          (princ "\nPick a line, polyline, circle or arc edge (inside blocks is allowed).")))))
  answer)

(defun ST:EdgePoint (edge parameter / point matrix vector)
  (setq point (vlax-curve-getPointAtParam (car edge) parameter)
        matrix (cadr edge))
  (if (and point matrix)
    (progn
      (setq vector (append point '(1.0)))
      (mapcar '(lambda (row) (apply '+ (mapcar '* row vector)))
              (list (car matrix) (cadr matrix) (caddr matrix))))
    point))

(defun ST:EdgeDistance (edge parameter center / point)
  (setq point (ST:EdgePoint edge parameter))
  (if (null point) (exit))
  (+ (expt (- (car point) (car center)) 2)
     (expt (- (cadr point) (cadr center)) 2)))

;;; Minimise WCS XY distance, including nonuniformly scaled nested curves.
;;; Partition each polyline segment; refine every partition, not just one
;;; coarse winner. Curve points come from AutoCAD, not chord approximations.
(defun ST:ClosestEdge (edge center / start end count step index left right
                            x1 x2 d1 d2 parameter score best bestScore)
  (setq start (caddr edge) end (cadddr edge)
        count (if (member (nth 4 edge) '("LWPOLYLINE" "POLYLINE"))
                (* 4 (max 1 (fix (+ 0.999999 (- end start)))))
                (if (= (nth 4 edge) "LINE") 1 16))
        step (/ (- end start) count) index 0
        best start bestScore (ST:EdgeDistance edge start center))
  (setq score (ST:EdgeDistance edge end center))
  (if (< score bestScore) (setq best end bestScore score))
  (repeat count
    (setq left (+ start (* index step)) right (+ left step))
    (repeat 36
      (setq x1 (+ left (* 0.38196601125 (- right left)))
            x2 (+ left (* 0.61803398875 (- right left)))
            d1 (ST:EdgeDistance edge x1 center)
            d2 (ST:EdgeDistance edge x2 center))
      (if (< d1 d2) (setq right x2) (setq left x1)))
    (setq parameter (/ (+ left right) 2.0)
          score (ST:EdgeDistance edge parameter center))
    (if (< score bestScore) (setq best parameter bestScore score))
    ;; Include vertices exactly, including sharp polyline corners.
    (setq parameter (+ start (* (1+ index) step))
          score (ST:EdgeDistance edge parameter center))
    (if (< score bestScore) (setq best parameter bestScore score))
    (setq index (1+ index)))
  (ST:EdgePoint edge best))

(defun ST:EdgesMidpoint (center first second / a b)
  (setq a (ST:ClosestEdge first center) b (ST:ClosestEdge second center))
  (list (/ (+ (car a) (car b)) 2.0)
        (/ (+ (cadr a) (cadr b)) 2.0) (caddr center)))

(defun ST:MoveMid (/ ss first second boundsCache index ent data layer center
                   target plan result moved skipped failed unchanged item)
  (setq ss (ssget "_I" '((0 . "INSERT"))))
  (if (null ss)
    (progn (princ "\nSelect blocks to move individually: ")
      (setq ss (ssget '((0 . "INSERT"))))))
  (if (null ss)
    (princ "\nNo blocks selected; no changes made.")
    (progn
      (setq first (ST:PickEdge "\nPick first edge (Enter to cancel): "))
      (if first (setq second (ST:PickEdge "\nPick second edge (Enter to cancel): ")))
      (cond
        ((or (null first) (null second)) (princ "\nCancelled; no changes made."))
        (T
          (setq index 0 skipped 0 failed 0 moved 0 unchanged 0 boundsCache nil plan nil)
          ;; Plan all moves before changing the drawing.
          (repeat (sslength ss)
            (setq ent (ssname ss index) data (entget ent)
                  layer (if data (tblsearch "LAYER" (cdr (assoc 8 data))) nil))
            (if (or (null data) (and layer (/= 0 (logand 4 (ST:Value layer 70 0))))
                    (/= (ST:Value data 410 "") (getvar "CTAB")))
              (setq skipped (1+ skipped))
              (progn
                (setq center (vl-catch-all-apply 'ST:GeometryCenter (list ent)))
                (if (or (vl-catch-all-error-p center) (null center))
                  (setq skipped (1+ skipped))
                  (progn
                    (setq target (vl-catch-all-apply 'ST:EdgesMidpoint (list center first second)))
                    (cond
                      ((or (vl-catch-all-error-p target) (null target))
                        (setq skipped (1+ skipped)))
                      ((equal center target 1e-7)
                      (setq unchanged (1+ unchanged)))
                      (T (setq plan (cons (list ent center target) plan))))))))
            (setq index (1+ index)))
          (if plan
            (progn
              (setq doc (vla-get-ActiveDocument (vlax-get-acad-object)))
              (vla-StartUndoMark doc) (setq undo T)
              (sssetfirst nil nil)
              (foreach item (reverse plan)
                (setq result (vl-catch-all-apply 'vla-Move
                  (list (vlax-ename->vla-object (car item))
                        (vlax-3d-point (cadr item)) (vlax-3d-point (caddr item)))))
                (if (vl-catch-all-error-p result)
                  (progn
                    (setq failed (1+ failed))
                    (princ (strcat "\nMove failed for block "
                      (cdr (assoc 5 (entget (car item)))) ": "
                      (vl-catch-all-error-message result))))
                  (setq moved (1+ moved))))
              (vla-Regen doc 1)
              (vla-EndUndoMark doc) (setq undo nil)))
          (princ (strcat "\nMoveMid: moved " (itoa moved)
            "; already centred " (itoa unchanged) "; skipped " (itoa skipped)
            "; failed " (itoa failed) ". Use U to undo moves."))
          (princ "\nGeometry-bound centres used; attributes ignored. Block elevation, scale and rotation kept."))))))


;;; Follow center uses WCS X/Y, preserves each target's Z. Both overlaps targets.
(defun ST:FollowCenter (/ pick reference data base boundsCache axis ss index ent
                         layer center target plan result item moved skipped failed unchanged anchorMode)
  (setq boundsCache nil pick (entsel "\nPick reference block or circle (Enter to cancel): "))
  (if (null pick)
    (princ "\nCancelled; no changes made.")
    (progn
      (setq reference (car pick) data (entget reference))
      (initget "BasePoint GeometryCenter")
      (setq anchorMode (getkword "\nAlign using [BasePoint/GeometryCenter] <BasePoint>: "))
      (if (null anchorMode) (setq anchorMode "BasePoint"))
      (cond
        ((= "CIRCLE" (cdr (assoc 0 data)))
          (setq base (trans (cdr (assoc 10 data)) reference 0)))
        ((= "INSERT" (cdr (assoc 0 data)))
          (setq base (vl-catch-all-apply 'ST:BlockAnchor (list reference anchorMode)))
          (if (vl-catch-all-error-p base) (setq base nil))))
      (if (null base)
        (princ "\nUse a circle or a supported local block with readable geometry.")
        (progn
          (initget "X Y Both")
          (setq axis (getkword "\nFollow center direction [X/Y/Both] <X>: "))
          (if (null axis) (setq axis "X"))
          (princ "\nSelect target blocks to align: ")
          (setq ss (ssget '((0 . "INSERT"))))
          (if (null ss)
            (princ "\nNo blocks selected; no changes made.")
            (progn
              (setq index 0 moved 0 skipped 0 failed 0 unchanged 0 plan nil)
              (repeat (sslength ss)
                (setq ent (ssname ss index) data (entget ent)
                      layer (if data (tblsearch "LAYER" (cdr (assoc 8 data))) nil))
                (if (or (eq ent reference) (null data)
                        (and layer (/= 0 (logand 4 (ST:Value layer 70 0))))
                        (/= (ST:Value data 410 "") (getvar "CTAB")))
                  (setq skipped (1+ skipped))
                  (progn
                    (setq center (vl-catch-all-apply 'ST:BlockAnchor (list ent anchorMode)))
                    (if (or (vl-catch-all-error-p center) (null center))
                      (setq skipped (1+ skipped))
                      (progn
                        (setq target (list
                          (if (member axis '("X" "Both")) (car base) (car center))
                          (if (member axis '("Y" "Both")) (cadr base) (cadr center))
                          (caddr center)))
                        (if (equal center target 1e-7)
                          (setq unchanged (1+ unchanged))
                          (setq plan (cons (list ent center target) plan)))))))
                (setq index (1+ index)))
              (if plan
                (progn
                  (setq doc (vla-get-ActiveDocument (vlax-get-acad-object)))
                  (vla-StartUndoMark doc) (setq undo T)
                  (sssetfirst nil nil)
                  (foreach item (reverse plan)
                    (setq result (vl-catch-all-apply 'vla-Move
                      (list (vlax-ename->vla-object (car item))
                            (vlax-3d-point (cadr item)) (vlax-3d-point (caddr item)))))
                    (if (vl-catch-all-error-p result)
                      (progn
                        (setq failed (1+ failed))
                        (princ (strcat "\nMove failed for block "
                          (cdr (assoc 5 (entget (car item)))) ": "
                          (vl-catch-all-error-message result))))
                      (setq moved (1+ moved))))
                  (vla-Regen doc 1)
                  (vla-EndUndoMark doc) (setq undo nil)))
              (princ (strcat "\nFollow center " axis ": moved " (itoa moved)
                "; already aligned " (itoa unchanged) "; skipped " (itoa skipped)
                "; failed " (itoa failed) ". Use U to undo moves."))
              (princ "\nReference kept. WCS axes used; block Z, rotation and scale kept."))))))))


;;; Block insertion is OCS; convert it before comparing WCS coordinates.
(defun ST:BlockAnchor (ent mode)
  (if (= mode "BasePoint")
    (trans (cdr (assoc 10 (entget ent))) ent 0)
    (ST:GeometryCenter ent)))

(defun ST:ObjectBox (ent / low high result)
  (setq result (vl-catch-all-apply 'vla-GetBoundingBox
                 (list (vlax-ename->vla-object ent) 'low 'high)))
  (if (not (vl-catch-all-error-p result))
    (list (vlax-safearray->list low) (vlax-safearray->list high))))

(defun ST:ObjectPoint (ent / data box)
  (setq data (entget ent))
  (cond
    ((member (cdr (assoc 0 data)) '("INSERT" "CIRCLE" "ARC"))
      (trans (cdr (assoc 10 data)) ent 0))
    ((setq box (ST:ObjectBox ent))
      (mapcar '(lambda (a b) (/ (+ a b) 2.0)) (car box) (cadr box)))))

(defun ST:PickObject (prompt / pick)
  (setq pick (entsel prompt))
  (if pick (car pick)))

(defun ST:Movable (ent / data layer obj)
  (setq data (entget ent) layer (if data (tblsearch "LAYER" (cdr (assoc 8 data)))))
  (and data (= (ST:Value data 410 "") (getvar "CTAB"))
       (not (and layer (/= 0 (logand 4 (ST:Value layer 70 0)))))
       (setq obj (vlax-ename->vla-object ent))
       (vlax-method-applicable-p obj 'Move)))

;;; Dynamic locals groupLow/groupHigh are owned by the calling tool.
(defun ST:CollectGroup (ss references / index ent box result)
  (setq index 0 groupLow nil groupHigh nil groupSkipped 0)
  (if ss
    (repeat (sslength ss)
      (setq ent (ssname ss index))
      (if (or (member ent references) (not (ST:Movable ent))
              (null (setq box (ST:ObjectBox ent))))
        (setq groupSkipped (1+ groupSkipped))
        (progn
          (setq result (cons ent result))
          (if groupLow
            (setq groupLow (mapcar 'min groupLow (car box))
                  groupHigh (mapcar 'max groupHigh (cadr box)))
            (setq groupLow (car box) groupHigh (cadr box)))))
      (setq index (1+ index))))
  (reverse result))

;;; Whole group receives one vector; roll back successful moves on failure.
(defun ST:MoveGroup (entities delta / ent result completed failure rollback)
  (cond
    ((null entities) (princ "\nNo movable objects selected."))
    ((equal delta '(0.0 0.0 0.0) 1e-7) (princ "\nAlready at the requested position."))
    (T
      (setq doc (vla-get-ActiveDocument (vlax-get-acad-object)))
      (vla-StartUndoMark doc) (setq undo T)
      (sssetfirst nil nil)
      (foreach ent entities
        (if (not failure)
          (progn
            (setq result (vl-catch-all-apply 'vla-Move
              (list (vlax-ename->vla-object ent)
                    (vlax-3d-point '(0.0 0.0 0.0)) (vlax-3d-point delta))))
            (if (vl-catch-all-error-p result)
              (setq failure (vl-catch-all-error-message result))
              (setq completed (cons ent completed))))))
      (if failure
        (progn
          (foreach ent completed
            (setq result (vl-catch-all-apply 'vla-Move
              (list (vlax-ename->vla-object ent)
                    (vlax-3d-point delta) (vlax-3d-point '(0.0 0.0 0.0)))))
            (if (vl-catch-all-error-p result) (setq rollback T)))
          (princ (strcat "\nGroup move failed: " failure))
          (princ (if rollback "\nRollback incomplete; use U to undo the group."
                     "\nCompleted moves rolled back.")))
        (princ (strcat "\nMoved " (itoa (length completed)) " objects together. Use U to undo.")))
      (vla-Regen doc 1)
      (vla-EndUndoMark doc) (setq undo nil))))

;;; Gap uses WCS axis-aligned extents, including text/attached attributes.
;;; Only the chosen axis changes; relative spacing and elevation stay fixed.
(defun ST:MoveWithDistance (/ reference box gap direction ss entities delta
                              groupLow groupHigh groupSkipped)
  (setq reference (ST:PickObject "\nPick base reference object (Enter to cancel): "))
  (cond
    ((null reference) (princ "\nCancelled; no changes made."))
    ((null (setq box (ST:ObjectBox reference)))
      (princ "\nReference has no readable extents."))
    (T
      (princ "\nDistance means final gap between WCS bounding edges. Other axis stays unchanged.")
      (initget 4)
      (setq gap (getdist "\nEnter gap from reference in drawing units (Enter to cancel): "))
      (if gap
        (progn
          (initget "Left Right Up Down")
          (setq direction (getkword "\nPlace objects [Left/Right/Up/Down] <Right>: "))
          (if (null direction) (setq direction "Right"))
          (princ "\nSelect objects to move as a group, then Enter: ")
          (setq ss (ssget) entities (ST:CollectGroup ss (list reference)))
          (if entities
            (progn
              (setq delta
                (cond
                  ((= direction "Right")
                    (list (- (+ (car (cadr box)) gap) (car groupLow)) 0.0 0.0))
                  ((= direction "Left")
                    (list (- (- (car (car box)) gap) (car groupHigh)) 0.0 0.0))
                  ((= direction "Up")
                    (list 0.0 (- (+ (cadr (cadr box)) gap) (cadr groupLow)) 0.0))
                  (T (list 0.0 (- (- (cadr (car box)) gap) (cadr groupHigh)) 0.0))))
              (ST:MoveGroup entities delta))
            (princ "\nNo movable objects selected."))
          (princ (strcat "\nSkipped " (itoa groupSkipped) " references, locked or unsupported objects.")))
        (princ "\nCancelled; no changes made.")))))

;;; References: insertion point for blocks; center for circles/arcs;
;;; bounding-box center for other objects. Selected group uses bounds center.
(defun ST:InBetween (/ first second a b ss entities center midpoint delta
                       groupLow groupHigh groupSkipped)
  (setq first (ST:PickObject "\nPick first base reference object (Enter to cancel): "))
  (if first (setq second (ST:PickObject "\nPick second base reference object (Enter to cancel): ")))
  (cond
    ((or (null first) (null second)) (princ "\nCancelled; no changes made."))
    ((eq first second) (princ "\nChoose two different reference objects."))
    ((or (null (setq a (ST:ObjectPoint first))) (null (setq b (ST:ObjectPoint second))))
      (princ "\nA reference has no readable base point or center."))
    (T
      (princ "\nReferences use block base points, circle/arc centers or other object bounds centers.")
      (princ "\nSelect objects to place in between as one group, then Enter: ")
      (setq ss (ssget) entities (ST:CollectGroup ss (list first second)))
      (if entities
        (progn
          (setq midpoint (mapcar '(lambda (x y) (/ (+ x y) 2.0)) a b)
                center (mapcar '(lambda (x y) (/ (+ x y) 2.0)) groupLow groupHigh)
                delta (list (- (car midpoint) (car center))
                            (- (cadr midpoint) (cadr center)) 0.0))
          (ST:MoveGroup entities delta))
        (princ "\nNo movable objects selected."))
      (princ (strcat "\nSkipped " (itoa groupSkipped) " references, locked or unsupported objects.")))))



;; v1.5 selection additions; original positioning functions preserved.
(defun STX:ask (message / k)
  (initget "Yes No")
  (= "Yes" (getkword (strcat "\n" message " [Yes/No] <No>: "))))

(defun STX:space ()
  (list (cons 410 (if (= 1 (getvar "CVPORT")) (getvar "CTAB") "Model"))))

(defun STX:list (ss / i out)
  (if ss (repeat (setq i (sslength ss))
    (setq out (cons (ssname ss (setq i (1- i))) out)))) (reverse out))

(defun STX:pickset (lst / ss e)
  (setq ss (ssadd)) (foreach e lst (if (entget e) (ssadd e ss))) ss)

(defun STX:scope (filter / k)
  (initget "Select Current")
  (setq k (getkword "\nScope [Select/Current] <Select>: "))
  (if (= k "Current") (ssget "_X" (append filter (STX:space)))
    (progn (princ "\nSelect objects: ") (ssget filter))))

(defun STX:writeable (e / lay)
  (setq lay (tblsearch "LAYER" (cdr (assoc 8 (entget e)))))
  (and lay (= 0 (logand 4 (cdr (assoc 70 lay))))
    (vlax-write-enabled-p (vlax-ename->vla-object e))))

(defun STX:colourkey (e / ed lay)
  (setq ed (entget e))
  (cond ((assoc 420 ed) (list "RGB" (cdr (assoc 420 ed))))
    ((or (not (assoc 62 ed)) (= 256 (cdr (assoc 62 ed))))
      (setq lay (tblsearch "LAYER" (cdr (assoc 8 ed))))
      (if (assoc 420 lay) (list "RGB" (cdr (assoc 420 lay))) (list "ACI" (abs (cdr (assoc 62 lay))))))
    (t (list "ACI" (abs (cdr (assoc 62 ed)))))))

(defun STX:blockname (e / o)
  (setq o (vlax-ename->vla-object e))
  (if (vlax-property-available-p o 'effectivename) (vla-get-effectivename o) (vla-get-name o)))

(defun STX:similar (/ ref mode ed ss hits e key)
  (setq ref (car (entsel "\nPick reference object: ")))
  (if ref
    (progn
      (initget "Layer Block Both Colour")
      (setq mode (getkword "\nMatch [Layer/Block/Both/Colour] <Layer>: ") ed (entget ref))
      (if (null mode) (setq mode "Layer"))
      (if (and (member mode '("Block" "Both")) (/= "INSERT" (cdr (assoc 0 ed))))
        (princ "\nPick a block reference for Block/Both matching.")
        (progn
          (setq ss (ssget "_X" (STX:space)) key (STX:colourkey ref))
          (foreach e (STX:list ss)
            (if (cond
              ((= mode "Layer") (= (cdr (assoc 8 ed)) (cdr (assoc 8 (entget e)))))
              ((= mode "Colour") (equal key (STX:colourkey e)))
              (t (and (= "INSERT" (cdr (assoc 0 (entget e))))
                (= (STX:blockname ref) (STX:blockname e))
                (or (= mode "Block") (= (cdr (assoc 8 ed)) (cdr (assoc 8 (entget e))))))))
              (setq hits (cons e hits))))
          (sssetfirst nil (STX:pickset hits))
          (princ (strcat "\nSelected " (itoa (length hits)) " objects in current space."))
          (if (= mode "Colour") (princ "\nByLayer resolved; ByBlock remains a stored key. ACI/RGB equivalents are not merged.")))))))

(defun STX:inside (/ e o endparam p pts mode ss)
  (setq e (car (entsel "\nPick closed 2D polyline boundary: ")))
  (if (and e (= "LWPOLYLINE" (cdr (assoc 0 (entget e))))
    (= 1 (logand 1 (cdr (assoc 70 (entget e))))))
    (progn
      (initget "Inside Crossing")
      (setq mode (getkword "\nSelect [Inside/Crossing] <Inside>: ")
        endparam (vlax-curve-getendparam e) p 0.0)
      (while (< p endparam)
        (setq pts (cons (trans (vlax-curve-getpointatparam e p) 0 1) pts) p (+ p 0.05)))
      (princ "\nUses a sampled boundary; curved edges are approximate. Keep the whole boundary visible.")
      (setq ss (ssget (if (= mode "Crossing") "_CP" "_WP") (reverse pts)))
      (if ss (progn (if (ssmemb e ss) (ssdel e ss)) (sssetfirst nil ss)
        (princ (strcat "\nSelected " (itoa (sslength ss)) " objects.")))))
    (princ "\nRequires a closed lightweight polyline in the current view plane.")))

(defun c:SELTOOLS (/ *error* option doc undo)
  (setq undo nil)
  (defun *error* (msg)
    (if undo (progn (vl-catch-all-apply 'vla-EndUndoMark (list doc)) (setq undo nil)))
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*BREAK*")))
      (princ (strcat "\nSELTOOLS error: " msg)))
    (princ "\nStopped. If a movement tool changed objects, use U to undo.") (princ))
  (princ "\nSELTOOLS - available tools:")
  (princ "\n  1) Selection inside the rectangle")
  (princ "\n  2) move to the middle")
  (princ "\n  3) follow center")
  (princ "\n  4) move with distance")
  (princ "\n  5) in between")
  (princ "\n  6) select similar objects")
  (princ "\n  7) selection inside polyline")
  (initget "SelectionInsideRectangle MoveToMiddle FollowCenter MoveWithDistance InBetween SelectSimilar InsidePolyline")
  (setq option (getkword "\nChoose tool [SelectionInsideRectangle/MoveToMiddle/FollowCenter/MoveWithDistance/InBetween/SelectSimilar/InsidePolyline] <SelectionInsideRectangle>: "))
  (cond
    ((equal option "SelectSimilar") (STX:similar))
    ((equal option "InsidePolyline") (STX:inside))
    ((equal option "MoveToMiddle") (ST:MoveMid))
    ((equal option "FollowCenter") (ST:FollowCenter))
    ((equal option "MoveWithDistance") (ST:MoveWithDistance))
    ((equal option "InBetween") (ST:InBetween))
    (T (ST:SelectInside)))
  (princ))

(princ "\nSELTOOLS v1.5 loaded. Type SELTOOLS; choose a named tool.")
(princ)
