o<m11> sub

; Move tool carousel CW Parameter P number of steps
; Without parameter one step CW.
; 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<m11> P#<p>)

o100 if [#3989 NE 1]
    (PRINT, atc not homed, homing)
    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

o120 if [EXISTS[#<p>]]
    #<steps_to_move> = #<p>
o120 else
    #<steps_to_move> = 1
    (tells the atc widget move 1 step forward)
o120 endif

(tells the atc widget how many steps to move and start moving forward)
(DEBUG, EVAL[vcp.getWidget{"dynatc"}.rotate{#<steps_to_move>, "cw"}])

M64 P4 ; Move atc motor FWD

o130 do
    M66 P4 L1 Q3 ; wait for rising edge on rotation index
    o131 if [#5399 LT 0]
        M65 P4 ; Stop atc motor
        (abort, Failed to get rotation index)
    o131 endif
    #3990 = [[[#3990+2] MOD #<number_of_pockets>]-1] ; Pocket is no.1-#<number_of_pockets>
    #<steps_to_move> = [#<steps_to_move>-1]
o130 while [#<steps_to_move> GT 0]

M65 P4 ; Stop motor

#<_my_current_pocket> = #3990

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

M2
