Attribute VB_Name = "Midi_Setup"
Option Explicit

Function ChooseMIDI() As Integer
    Dim xx As Integer
        
    ' MIDI In
    If BCF.MIDIInput1.State <> MIDISTATE_CLOSED Then
        BCF.MIDIInput1.Action = MIDIIN_STOP
        BCF.MIDIInput1.Action = MIDIIN_CLOSE
    End If
    If inputport <> 0 Then
        MIDIInOpen
        If BCF.MIDIInput1.State = MIDISTATE_CLOSED > 0 Then
            ChooseMIDI = 0
            Exit Function
        End If
    End If
    ' MIDI Out
    If BCF.MIDIOutput1.State <> MIDISTATE_CLOSED Then
        BCF.MIDIOutput1.Action = MIDIOUT_CLOSE
    End If
    If outputport <> 0 Then
        MIDIOutOpen
        If BCF.MIDIOutput1.State = MIDISTATE_CLOSED Then
            MsgBox "Cannot open MIDI Output port", vbExclamation, "Open MIDI Output port"
            ChooseMIDI = 0
            Exit Function
        End If
    End If
    If BCF.MIDIInput1.State <> MIDISTATE_CLOSED Then
        BCF.MIDIInput1.MessageEventEnable = True
    End If
    ChooseMIDI = 1
End Function

Sub MIDIInOpen()
    Dim wRtn As Integer
    
    If BCF.MIDIInput1.State >= MIDISTATE_OPEN Then
        ' Close midiin port
        BCF.MIDIInput1.Action = MIDIIN_CLOSE
    End If
    If inputport = 0 Then Exit Sub
    ' Get selected device id
    BCF.MIDIInput1.DeviceID = inputport - 1
    ' Open and display handle
    BCF.MIDIInput1.Action = MIDIIN_OPEN
    ' Start midi input
    BCF.MIDIInput1.Action = MIDIIN_START
    'note = 0
    BCF.MIDIInput1.Filter(FILTER_ACTIVE_SENSE) = True
End Sub

Sub MIDIOutOpen()

    If BCF.MIDIOutput1.State >= MIDISTATE_OPEN Or BCF.MIDIOutput1.DeviceID = -1 Then
        ' Close
        BCF.MIDIOutput1.Action = MIDIOUT_CLOSE
    End If
    If outputport = 0 Then Exit Sub
    ' Open selected device
    BCF.MIDIOutput1.DeviceID = outputport
    BCF.MIDIOutput1.Action = MIDIOUT_OPEN
End Sub


