~setupMidiForNdef = { |ndefName, midiChan = 0, ccMap|
    var ndef = Ndef(ndefName);

    // Remove old defs if they exist
    MIDIdef.noteOn((ndefName ++ "_On").asSymbol).clear;
    MIDIdef.noteOff((ndefName ++ "_Off").asSymbol).clear;
    MIDIdef.cc((ndefName ++ "_CC").asSymbol).clear;

    // Note on/off
    MIDIdef.noteOn(
        (ndefName ++ "_On").asSymbol,
        { |vel, note, chan|
            ndef.put(
                note,
                ndef.source,
                0,
                [\freq, note.midicps, \gt, 1, \lev, vel / 127]
            );
        },
        chan: midiChan
    ).fix;

    MIDIdef.noteOff(
        (ndefName ++ "_Off").asSymbol,
        { |vel, note, chan| ndef.removeAt(note) },
        chan: midiChan
    ).fix;

    // MIDI CC mapping
    MIDIdef.cc(
        (ndefName ++ "_CC").asSymbol,
        { |val, num|
            var param = ccMap[num];
            if (param.notNil) {
                var spec = ndef.getSpec(param) ?? ControlSpec(0, 1);
                ndef.set(param, spec.map(val / 127));
            };
        },
        ccNum: ccMap.keys,
        chan: midiChan
    ).fix;
};

~setupMidiForNdef.(
    \,
    0,
    (
		0: \freq, 60;
    )
);

