INT32 MIDI_Utils_StartDevice(MacMidiDeviceHandle* handle) {
    OSStatus err = noErr;
    
    if (!handle || !handle->h.deviceHandle) {
        ERROR0("ERROR: MIDI_Utils_StartDevice: handle or native is NULL\n");
        return MIDI_INVALID_HANDLE;
    }

    // Clears all the events from the queue.
    MIDI_QueueClear(handle->h.queue);

    if (!handle->isStarted) {
        /* set the flag that we can now receive messages */
        handle->isStarted = TRUE;

        if (handle->direction == MIDI_IN) {
            // The handle->h.platformData field contains the (pthread_cond_t*)
            // associated with the source of the MIDI input stream, and is
            // used in the CoreMIDI's callback to signal the arrival of new
            // data.
            //
            // Similarly, handle->h.queue is used in the CoreMDID's callback
            // to dispatch the incoming messages to the appropriate queue.
            //
            err = MIDIPortConnectSource(inPort, (MIDIEndpointRef) (intptr_t) (handle->h.deviceHandle), (void*) handle);
        } else if (handle->direction == MIDI_OUT) {
            // Unschedules previous-sent packets.
            err = MIDIFlushOutput((MIDIEndpointRef) (intptr_t) handle->h.deviceHandle);
        }

        MIDI_CHECK_ERROR;
    }
    return MIDI_SUCCESS; /* don't fail */
}
INT32 MIDI_Utils_StopDevice(MacMidiDeviceHandle* handle) {
    OSStatus err = noErr;
    
    if (!handle || !handle->h.deviceHandle) {
        ERROR0("ERROR: MIDI_Utils_StopDevice: handle or native handle is NULL\n");
        return MIDI_INVALID_HANDLE;
    }

    if (handle->isStarted) {
        /* set the flag that we don't want to receive messages anymore */
        handle->isStarted = FALSE;

        if (handle->direction == MIDI_IN) {
            err = MIDIPortDisconnectSource(inPort, (MIDIEndpointRef) (intptr_t) (handle->h.deviceHandle));
        } else if (handle->direction == MIDI_OUT) {
            // Unschedules previously-sent packets.
            err = MIDIFlushOutput((MIDIEndpointRef) (intptr_t) handle->h.deviceHandle);
        }

        MIDI_CHECK_ERROR;
    }
    return MIDI_SUCCESS;
}
JNIEXPORT jint JNICALL Java_com_apple_audio_midi_MIDIEndpoint_MIDIFlushOutput
  (JNIEnv *, jclass, jint dest)
{
	return (jint)MIDIFlushOutput((MIDIEndpointRef)dest);
}