Module SpectrumModule
    Private myMgr As Ivi.Visa.Interop.ResourceManager
    Private mySpec As Ivi.Visa.Interop.FormattedIO488

    Private strQueryRes As String

    Public Function SpecOpen(SpecID As String, ToCount As Integer) As String
        Try
            myMgr = New Ivi.Visa.Interop.ResourceManager
            mySpec = New Ivi.Visa.Interop.FormattedIO488

            mySpec.IO = myMgr.Open(SpecID)
            'mySpec.IO.Clear()
            mySpec.IO.Timeout = ToCount

            strQueryRes = SpecQueryStr("*IDN?")

            Return strQueryRes

        Catch ex As Exception
            Return "FAIL"
        End Try
    End Function

    Public Function RunCommand(command As String) As String
        Dim errStr As String
        Try
            mySpec.WriteString(command)
            errStr = CheckError()
            If errStr.Replace(" ", "") <> "" Then
                Return errStr
            End If

            Return "PASS"
        Catch ex As Exception
            Return "VISA COM Error: " + vbCrLf + CStr(Err.Number) + ", " + Err.Source + "," + Err.Description
        End Try

    End Function

    Public Function SpecQueryStr(query As String) As String
        Dim errStr As String
        Try
            mySpec.WriteString(query)
            SpecQueryStr = mySpec.ReadString
            errStr = CheckError()
            If errStr.Replace(" ", "") <> "" Then
                Return SpecQueryStr & " / " & errStr
            End If
            Return SpecQueryStr

        Catch ex As Exception
            Return "VISA COM Error: " + vbCrLf + CStr(Err.Number) + ", " + Err.Source + "," + Err.Description
        End Try

    End Function

    Private Function CheckError() As String
        Dim strerrval As String
        Dim strout As String = ""

        mySpec.WriteString(":SYSTem:ERRor?")
        strerrval = mySpec.ReadString
        While Val(strerrval) <> 0
            strout = "INST Error: " + strerrval
            mySpec.WriteString(":SYSTem:ERRor?")
            strerrval = mySpec.ReadString
        End While

        If Not strout = "" Then
            'MsgBox(strout, vbExclamation, "INST Error Messages")
            mySpec.FlushWrite(False)
            mySpec.FlushRead()
            Return strout
        End If

        Return ""
    End Function

End Module
