o<m10> sub

; Move tool carousel best direction to pocket P
; Parameter #3989 is used to track if the carousel is homed (M13) (volatile)
; Parameter #3990 is used to track the current tool pocket (persistently)
; #<number_of_pockets>: The number of pockets in the ATC is automaticity pulled from the INI via #<_ini[atc]pockets>
(PRINT, o<m10> P#<p>)

o100 if [#3989 NE 1]
    M13
o100 endif

; default to a 12 pocket ATC (matching DynATC Widget behaviour), then update based on INI settings
#<number_of_pockets> = 12
o110 if [EXISTS[#<_ini[atc]pockets>]]
    #<number_of_pockets> = #<_ini[atc]pockets>
o110 endif

#<steps> = [#3990 - #<p>]
(PRINT, o<m10> P#<p>, steps=#<steps>)
o120 if [#<steps> GT [#<number_of_pockets> / 2]]
    #<steps>=[#<steps> - #<number_of_pockets>]
o120 endif

o130 if [#<steps> LT -[#<number_of_pockets> / 2]]
    #<steps>=[#<steps> + #<number_of_pockets>]
o130 endif

o140 if [#<steps> GT 0]
    M12 P[#<steps>]
o140 elseif [#<steps> LT 0]
    #<steps>=[#<steps> * -1]
    M11 P[#<steps>]
o140 endif

(PRINT, o<m10> endsub)
o<m10> endsub [1]

M2
