Module mdlXfer
    Public boolCancelXfer As Boolean
    Public boolBusy As Boolean

    Const errUserCancelled As Integer = 0
    Const errTimedOut As Integer = 1
    Const errFailure As Integer = 2
    Const errNoSending As Integer = 3
    Const errChecksum As Integer = 4
    Const errNoAck As Integer = 5

    Dim lngCurTime As Long
    Dim intErrorCode As Integer

    Dim lngTotalBytes As Long
    Dim lngProgressed As Long

    Dim intLinkSpeed As Integer = 256
    Dim intSpeedCount As Integer = 0

    Dim lngChkSum As Long

    Public Class directoryListing
        Public freeBytes As Long
        Public variables() As tiVariable
    End Class

    Public Class tiVariable
        Public type As Byte
        Public name As String
        Public contents() As Byte
        Public archived As Boolean
    End Class
    Sub xferWait()
        lngCurTime += 1
        'If lngCurTime >= 500000 Then
        'intErrorCode = errTimedOut
        'boolCancelXfer = True
        'End If
        intSpeedCount = (intSpeedCount + 1) Mod intLinkSpeed
        If intSpeedCount = 0 Then Application.DoEvents()
    End Sub

    ' Sub which waits for the next bit change
    Sub xferWaitBit(ByVal comXfer As AxMSCommLib.AxMSComm)
        lngCurTime = 0
        Do Until comXfer.DSRHolding = False Or comXfer.CTSHolding = False Or boolCancelXfer = True
            xferWait()
        Loop
    End Sub

    ' Routines to set individual bits on data lines
    Sub xferD0L(ByVal comXfer As AxMSCommLib.AxMSComm)
        lngCurTime = 0
        comXfer.Handshaking = MSCommLib.HandshakeConstants.comNone
        Do Until (comXfer.DSRHolding = False) Or boolCancelXfer = True
            xferWait()
        Loop
    End Sub
    Sub xferD0H(ByVal comXfer As AxMSCommLib.AxMSComm)
        lngCurTime = 0
        comXfer.Handshaking = MSCommLib.HandshakeConstants.comRTS
        Do Until (comXfer.DSRHolding = True) Or boolCancelXfer = True
            xferWait()
        Loop
    End Sub

    Sub xferD1L(ByVal comXfer As AxMSCommLib.AxMSComm)
        comXfer.DTREnable = False
        Do Until (comXfer.CTSHolding = False) Or boolCancelXfer = True
            xferWait()
        Loop
    End Sub
    Sub xferD1H(ByVal comXfer As AxMSCommLib.AxMSComm)
        lngCurTime = 0
        comXfer.DTREnable = True
        Do Until (comXfer.CTSHolding = True) Or boolCancelXfer = True
            xferWait()
        Loop
    End Sub

    ' Get a single bit
    Function xferGetBitDirect(ByVal comXfer As AxMSCommLib.AxMSComm) As Boolean
        lngCurTime = 0
        xferWaitBit(comXfer)
        If comXfer.CTSHolding = False Then
            xferGetBitDirect = False
            comXfer.DTREnable = False
            Do Until (comXfer.CTSHolding = True) Or boolCancelXfer = True
                xferWait()
            Loop
            comXfer.DTREnable = True
        Else
            xferGetBitDirect = True
            comXfer.Handshaking = MSCommLib.HandshakeConstants.comNone
            Do Until (comXfer.DSRHolding = True) Or boolCancelXfer = True
                xferWait()
            Loop
            comXfer.Handshaking = MSCommLib.HandshakeConstants.comRTS
        End If
    End Function

    ' Send a byte to the TI
    Sub xferSendByte(ByVal comXfer As AxMSCommLib.AxMSComm, ByVal byteToSend As Byte)
        lngCurTime = 0
        Dim ANDFactor As Byte
        Dim i As Integer

        For i = 0 To 7
            ANDFactor = 2 ^ i
            If (byteToSend And ANDFactor) <> 0 Then
                xferD1L(comXfer)
                xferD1H(comXfer)
            Else
                xferD0L(comXfer)
                xferD0H(comXfer)
            End If
            If boolCancelXfer Then Exit Sub
        Next i

        lngChkSum = (lngChkSum + byteToSend) Mod &H10000

        ' Debug.WriteLine("-> " & Hex(byteToSend) & " " & byteToSend & "d")
        Debug.Write(",S" & byteToSend)
    End Sub

    ' Receive a byte from the TI
    Function xferGetByte(ByVal comXfer As AxMSCommLib.AxMSComm) As Byte
        lngCurTime = 0
        xferGetByte = 0
        Dim i As Integer

        For i = 0 To 7
            If xferGetBitDirect(comXfer) = True Then
                xferGetByte = xferGetByte + (2 ^ i)
            End If
        Next i

        lngChkSum = (lngChkSum + xferGetByte) Mod &H10000


        'Debug.WriteLine("<- " & Hex(xferGetByte) & " " & xferGetByte & "d")
        Debug.Write(",G" & xferGetByte)

    End Function

    ' Send a keypress to the TI
    Sub xferSendKey(ByVal comXfer As AxMSCommLib.AxMSComm, ByVal keyToSend As Byte)
        boolCancelXfer = False
        lngCurTime = 0

        xferSendCommandString(comXfer, &H73, &H87, keyToSend, &H0)

        Dim i As Integer
        For i = 1 To 8
            xferGetByte(comXfer)
        Next i
    End Sub

    ' Receive a screenshot
    Function xferGetScreenshot(ByVal comXfer As AxMSCommLib.AxMSComm) As Array

        boolBusy = True
        lngTotalBytes = 768
        lngProgressed = 0

        boolCancelXfer = False
        lngCurTime = 0
        Dim outPicture(768) As Byte

        xferSendCommandString(comXfer, &H73, &H6D, &H0, &H0)

        Dim r As Byte
        xferGetIgnoreBytes(comXfer, 1)
        r = xferGetByte(comXfer)
        xferGetIgnoreBytes(comXfer, 2)
        If r <> &H56 Then boolCancelXfer = True : intErrorCode = errFailure : Exit Function


        xferGetIgnoreBytes(comXfer, 4)
        Dim i As Integer
        For i = 0 To 767
            outPicture(i) = xferGetByte(comXfer)
            lngProgressed = i
            If boolCancelXfer Then boolBusy = False : Exit Function
        Next

        xferGetScreenshot = outPicture
        boolBusy = False

    End Function


    Function xferCheckReady(ByVal comXfer As AxMSCommLib.AxMSComm) As Boolean
        boolBusy = True
        boolCancelXfer = False
        lngCurTime = 0

        xferSendCommandString(comXfer, &H73, &H68, &H0, &H0)

        Dim r As Byte
        xferGetIgnoreBytes(comXfer, 1)
        r = xferGetByte(comXfer)
        xferGetIgnoreBytes(comXfer, 2)
        If r = &H56 Then xferCheckReady = True Else xferCheckReady = False
        boolBusy = False
    End Function

    Sub xferForceCancel()
        boolCancelXfer = True
        intErrorCode = errUserCancelled
    End Sub

    Sub xferErrorDialog()
        Dim errorMessage As String
        If intErrorCode = errTimedOut Then
            errorMessage = "Connection timed out."
        ElseIf intErrorCode = errUserCancelled Then
            errorMessage = "User cancelled the transfer."
        ElseIf intErrorCode = errFailure Then
            errorMessage = "There was an error in the transfer."
        ElseIf intErrorCode = errNoSending Then
            errorMessage = "The calculator will not send that variable"
        ElseIf intErrorCode = errChecksum Then
            errorMessage = "Checksum error in the last transfer"
        ElseIf intErrorCode = errNoAck Then
            errorMessage = "The transfer has not been acknowledged correctly"
        End If

        MsgBox(errorMessage, MsgBoxStyle.Exclamation, "Error performing request")
    End Sub
    Sub xferNotReady()
        MsgBox("The connection is not ready. Please wait until any existing transfers are complete, and that the calculator is switched on and in an idle state at the homescreen.", MsgBoxStyle.Information, "Error performing request")
    End Sub

    Sub xferGetIgnoreBytes(ByVal comXfer As AxMSCommLib.AxMSComm, ByVal numBytesToIgnore As Integer)
        Dim i As Integer
        For i = 1 To numBytesToIgnore
            xferGetByte(comXfer)
            If boolCancelXfer Then Exit Sub
        Next
    End Sub

    Function xferCheckAck(ByVal comXfer As AxMSCommLib.AxMSComm) As Boolean
        Dim r As Byte
        xferGetByte(comXfer)
        r = xferGetByte(comXfer)
        xferGetIgnoreBytes(comXfer, 2)
        If r = &H56 Then Return True Else Return False
    End Function

    Function xferSendCommandString(ByVal comXfer As AxMSCommLib.AxMSComm, ByVal ParamArray commandString() As Byte)
        Dim i As Integer
        For i = 0 To commandString.GetUpperBound(0)
            xferSendByte(comXfer, commandString(i))
            If boolCancelXfer Then Exit Function
        Next
    End Function

    Function xferGetStatus()
        If Not (boolBusy) Then
            Return -1
        ElseIf lngTotalBytes = -1 Then
            Return -2
        Else
            Return Int(100 * (lngProgressed / lngTotalBytes))
        End If
    End Function

    Sub xferSendAck(ByVal comXfer As AxMSCommLib.AxMSComm)
        xferSendCommandString(comXfer, &H23, &H56, &H0, &H0)
    End Sub
    Sub xferSendWord(ByVal comXfer As AxMSCommLib.AxMSComm, ByVal wordToSend As Long)
        xferSendByte(comXfer, wordToSend Mod 256)
        xferSendByte(comXfer, wordToSend \ 256)
    End Sub

    ' Returns a variable as a string, requested by the header
    Function xferGetVariable(ByVal comXfer As AxMSCommLib.AxMSComm, ByVal varName As String) As String
        boolBusy = True
        boolCancelXfer = False
        lngCurTime = 0
        lngProgressed = 0
        Dim strOut As String
        Dim tr As Long = 0
        xferSendCommandString(comXfer, &H73, &HA2, &HD, &H0, &H0, &H0)
        Dim i As Long
        lngChkSum = 0
        For i = 0 To 8
            xferSendByte(comXfer, Asc(varName.Chars(i)))
        Next
        xferSendCommandString(comXfer, &H0, &H0)
        Debug.WriteLine(lngChkSum & "-" & tr)
        xferSendWord(comXfer, lngChkSum)

        If xferCheckAck(comXfer) Then
            ' The calc sends the header BACK
            xferGetIgnoreBytes(comXfer, 19)
            xferSendAck(comXfer)
            xferSendCommandString(comXfer, &H73, &H9, &H0, &H0) ' Send "Clear to send"
            If xferCheckAck(comXfer) Then
                'Here's where the MAGIC BEGINS!

                xferGetIgnoreBytes(comXfer, 4)

                lngChkSum = 0

                lngTotalBytes = xferGetByte(comXfer) + xferGetByte(comXfer) * 256

                Debug.WriteLine("STARTING TRANSFER! (File size = " & lngTotalBytes & " bytes)")

                Dim r As Byte

                For i = 1 To lngTotalBytes
                    r = xferGetByte(comXfer)
                    If boolCancelXfer Then Exit For
                    strOut &= Chr(r)
                    lngProgressed = i
                Next
                Dim testedChkSum As Long = lngChkSum
                Dim realChkSum As Long
                realChkSum = xferGetByte(comXfer) + xferGetByte(comXfer) * 256
                If testedChkSum = realChkSum Then
                    xferSendAck(comXfer)
                Else
                    Debug.WriteLine("EXPECTED CHKSUM: " & Hex(lngChkSum) & " [" & Hex(realChkSum) & "]")
                    boolCancelXfer = True
                    intErrorCode = errChecksum
                End If
            Else
                intErrorCode = errNoSending
                boolCancelXfer = True
            End If
        Else
            intErrorCode = errNoAck
            boolCancelXfer = True
        End If
        boolBusy = False
        Return strOut
    End Function
    ' Get a directory listing as an array of strings (each string is the variable header)
    Function xferGetDirectoryListing(ByVal comXfer As AxMSCommLib.AxMSComm) As Array
        Dim dirList() As String

        boolBusy = True
        boolCancelXfer = False
        lngTotalBytes = -1
        lngCurTime = 0
        xferSendCommandString(comXfer, &H73, &HA2, &HD, &H0, &H0, &H0, &H19, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H19, &H0)

        Dim r As Byte
        xferGetIgnoreBytes(comXfer, 1)
        r = xferGetByte(comXfer)
        xferGetIgnoreBytes(comXfer, 2)
        If r <> &H56 Then boolCancelXfer = True : intErrorCode = errFailure : Exit Function

        xferGetIgnoreBytes(comXfer, 4)

        Dim freeBytes As Integer = xferGetByte(comXfer) + xferGetByte(comXfer) * 256

        xferGetIgnoreBytes(comXfer, 2)
        xferSendAck(comXfer)

        Dim eot As Boolean = False
        Dim i As Integer
        Dim p As Long = 0

        While Not (eot) And Not (boolCancelXfer)

            xferGetByte(comXfer)
            r = xferGetByte(comXfer)
            xferGetIgnoreBytes(comXfer, 2)


            If r = &H92 Then eot = True
            If Not (eot) Then
                Dim varType As Byte
                Dim varName As String = ""
                xferGetIgnoreBytes(comXfer, 2)
                ReDim Preserve dirList(p)
                dirList(p) = ""
                For i = 0 To 8

                    dirList(p) &= Chr(xferGetByte(comXfer))
                    If i = 0 And dirList(p) = Chr(64) Then dirList(p) = Chr(0)
                Next
                xferGetIgnoreBytes(comXfer, 4)
                p += 1
            End If
            xferSendAck(comXfer)

        End While

        boolBusy = False
        Return dirList
    End Function
End Module

