#ifmain ;-----------------------------------------------------------------------
                    #ListOff
                    #Uses     mcu.inc
                    #ListOn
#endif ;------------------------------------------------------------------------
                    #Uses     deletechar.sub
;*******************************************************************************
; Purpose: Trim string from leading, trailing, and duplicate in-between spaces
; Input  : HX -> ASCIZ string
; Output : A = Length of updated string

StringTrim          macro     [[#]String]
                    mset      #
          #ifb ~1~
                    call      ~0~
                    mexit
          #endif
                    #push
                    #spauto   :sp
                    pshhx
                    @@lea     ~1~
                    call      ~0~
                    pulhx
                    #pull
                    endm

;-------------------------------------------------------------------------------

                    #spauto

StringTrim          proc
                    clra                          ;character position
                    psha      pos@@
                    pshhx
                    #ais
                    bra       Loop@@
          ;--------------------------------------
Delete@@            lda       pos@@,sp
                    cbeqa     #1,DeleteNow@@      ;if at 1st position, delete

                    tst       1,x                 ;if at last position, delete
                    beq       DeleteNow@@

                    lda       -1,x                ;load previous character
                    cmpa      #' '                ;if previous not a space
                    bne       Cont@@              ; skip deleting

DeleteNow@@         @StringDeleteChar             ;HX -> 1st string position
                    dbnz      pos@@,sp,Previous@@
          ;--------------------------------------
Loop@@              lda       ,x
                    beq       Done@@              ;end of string, exit

                    inc       pos@@,sp            ;increment character position
                    cbeqa     #' ',Delete@@

Cont@@              aix       #1                  ;skip non-blank
                    bra       Loop@@

Previous@@          aix       #-1
                    dec       pos@@,sp            ;decrement character position
                    bra       Loop@@

Done@@              pull
                    rtc

;*******************************************************************************
                    #sp
;*******************************************************************************