;
; Functions for holding and repeating keys
;

Hold(Primary, Secondary) {
    Send {%Primary% down}
    if ( Secondary.Length() != 0 ) {
        ThisLoop := Func("HoldLoop").bind(Primary,Secondary)
        SetTimer, %ThisLoop%, 50
    }
}

HoldLoop(Primary, Secondary) {
    if GetKeyState(Primary,"P") {
        SetTimer, , Delete
    }
    for index,key in Secondary {
        if GetKeyState(key,"P") {
            Send {%Primary% up}
            SetTimer, , Delete
        }
    }
}

Repeat(Primary, Secondary) {
    Send {%Primary% up}
    Sleep 100
    RepeatVar := 0
    Loop {
        if GetKeyState(Primary,"P") {
            return
        }
        for index,key in Secondary {
            if GetKeyState(key,"P") {
                return
            }
        }
        if (RepeatVar == 1) {
            Send, {%Primary% down}
            RepeatVar := 0
        } else {
            Send, {%Primary% up}
            RepeatVar := 1
        }
        Sleep 100
    }
}

; Sets key to hold if single tap, or repeat if double tap
HoldOrRepeat(Primary, Secondary) {
    Send {%Primary% down}
    KeyWait, %Primary%, D, T0.2
    if (ErrorLevel = 0) {
        Repeat(Primary,Secondary)
    } else {
        Hold(Primary,Secondary)
    }
}