download MKMidi.m
Language: ObjectiveC
Copyright: (c) 1988-1992, NeXT Computer, Inc. (c) 1994 Stanford University. (c) 1999-2004, The MusicKit Project. (c) 1994 NeXT Computer, Inc. and reproduced under license from NeXT
LOC: 1354
Project Info
The MusicKit(musickit)
Server: SourceForge
Type: cvs
...sicKit\Frameworks\MusicKit\
   _ArielQP.h
   _DSPMK.h
   _error.h
   _midi.h
   _MKAppProxy.h
   _MKAppProxy.m
   _MKNameTable.h
   _MKNameTable.m
   _MKParameter.h
   _MTCHelper.h
   _MTCHelper.m
   _musickit.h
   _noteRecorder.h
   _OrchloopbeginUG.h
   _OrchloopbeginUG.m
   _ParName.h
   _ParName.m
   _scorefile.h
   _ScorefileVar.h
   _ScorefileVar.m
   _SharedSynthInfo.h
   _SharedSynthInfo.m
   _synthElementMethods.m
   _time.h
   ArielQP.h
   ArielQP.m
   classFuncs.h
   ConductorPrivate.h
   dsp_types.h
   DSPSerialPortDevice.h
   dspwrap.h
   EnvelopePrivate.h
   equalTempered.m
   errors.h
   fastFFT.c
   fastFFT.h
   GNUmakefile.postamble
   GNUmakefile.preamble.in
   InstrumentPrivate.h
   keynums.h
   libMusicKit.def
   Localized.strings
   make.sh
   Makefile.postamble
   Makefile.preamble
   midi_spec.h
   midifile.h
   midifile.m
   MidiPrivate.h
   midiTranslation.h
   MKConductor.h
   MKConductor.m
   MKConductorDelegate.h
   MKDeviceStatus.h
   MKEnvelope.h
   MKEnvelope.m
   MKFilePerformer.h
   MKFilePerformer.m
   MKFileWriter.h
   MKFileWriter.m
   MKInstrument.h
   MKInstrument.m
   MKMidi.h
   MKMidi.m
   MKMixerInstrument.h
   MKMixerInstrument.m
   MKMTCPerformer.h
   MKMTCPerformer.m
   MKNote.h
   MKNoteFilter.h
   MKNoteFilter.m
   MKNoteReceiver.h
   MKNoteReceiver.m
   MKNoteSender.h
   MKNoteSender.m
   MKOrchestra.h
   MKPart.m
   MKPartials.h
   MKPartials.m
   ...tialsWaveshapingTable.m
   MKPartPerformer.h
   MKPartPerformer.m
   MKPartRecorder.h
   MKPartRecorder.m
   MKPatch.h
   MKPatch.m
   MKPatchConnection.h
   MKPatchConnection.m
   MKPatchEntry.h
   MKPatchEntry.m
   MKPatchTemplate.h
   MKPatchTemplate.m
   MKPerformer.h
   MKPerformer.m
   MKPerformerDelegate.h
   MKPlugin.h
   MKSamplerInstrument.h
   MKSamplerInstrument.m
   MKSamples.h
   MKScore.h
   MKScore.m
   MKScorefileObject.h
   MKScorefilePerformer.h
   MKScorefilePerformer.m
   MKScorefileWriter.m
   MKScorePerformer.h
   MKScorePerformer.m
   MKScoreRecorder.h
   MKScoreRecorder.m
   MKSynthData.h
   MKSynthData.m
   MKSynthInstrument.h
   MKSynthPatch.h
   MKTimbre.h
   MKTimbre.m
   MKTuningSystem.h
   MKTuningSystem.m
   MKUnitGenerator.h
   MKUnitGenerator.m
   MKWaveTable.h
   MKWaveTable.m
   mtcMidi.m
   mtcMidiPrivate.m
   MusicKit-Info.plist
   MusicKit.h
   MusicKitConfig.h.in
   names.h
   noDVal.h
   noteDispatcherMethods.m
   NotePrivate.h
   noteRecorderCFuncs.m
   noteRecorderMethods.m
   orch.h
   OrchestraPrivate.h
   OrchloopbeginUG.h
   OrchloopbeginUG.m
   orchloopbeginUGInclude.m
   params.h
   parNames.m
   partialsDBInclude.m
   PartialsPrivate.h
   PartPerformerPrivate.h
   PartPrivate.h
   PartRecorderPrivate.h
   PatchTemplatePrivate.h
   PB.project
   PerformerPrivate.h
   pitches.h
   platform.make
   ...efilePerformerPrivate.h
   ScorePerformerPrivate.h
   ScorePrivate.h
   ScoreRecorderPrivate.h
   SynthDataPrivate.h
   synthElementCFuncs.m
   synthElementMethods.m
   SynthInstrumentPrivate.h
   SynthPatchList.h
   SynthPatchList.m
   SynthPatchPrivate.h
   timetagInclude.m
   timeunits.h
   tokenNames.m
   tokens.h
   trigonometry.c
   trigonometry.h
   TuningSystemPrivate.h
   UnitGeneratorPrivate.h
   win32-def.top
   writeBinary.m
   writeMidi.m
   writeScore.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
/*
  $Id: MKMidi.m,v 1.58 2005/05/11 07:59:01 leighsmith Exp $
  Defined In: The MusicKit
  HEADER FILES: MusicKit.h

  Description:
    MKMidi is made to look somewhat like a MKPerformer. It differs from a
    performer, however, in that it responds not to messages sent by a
    conductor, but by MIDI input which arrives through the serial port.

    Note that the MKConductor must be clocked to use MKMidi.

    The elaborate support here for shared ownership stems from the fact that, 
    unlike with DSP drivers, the MIDI driver is also a time base.  That means
    that it must be shared among all instances.
    This complicates matters if we ever have more than one driver (as opposed to
    multiple instances of one driver.)  For now, I'm going to punt on that. If
    the situation ever comes up, we may have to factor the time stuff out of the
    driver and make a separate time server, which will be hard, seeing how MIDI
    time code must be parsed, etc.

    There is another subtle difference between MIDI and DSP handling.
    In the case of MIDI, we are perfectly happy to allocate objects for bogus
    midi objects.  We don't find out they're bogus until we try to open them.

    Note that the support for MIDI devices on different hosts is currently disabled.
    Hence if the host machine (the one the MusicKit app is running on) is a non-NeXT
    machine, we ignore the hostName.

    Also, if a NeXT host tries to access a MIDI driver on an Intel machine, it
    will fail because there's no device "midiN" on Intel.

    Explanation of MIDI driver support:

    For Win32, Linux and MacOS X, the MKPerformSndMIDI framework interfacing to
    DirectMusic, portmusic or CoreMIDI will return a list of "drivers", which can be hardware MIDI
    interfaces, PCM ROM playback engines on soundcards, software sound synthesisers
    etc. The device name can be either a driver and port description string (exactly matching one of
    the driverNames), or can be "midiX" i.e. the soft form described above, where X is the
    0 base index referring to a driver.

    For NeXTStep/OpenStep Intel:

    On the DSP, we use "soft" integers to map to "hard" driver/unit pairs.
    Here, we pass in a device 'name' in the form "midiN", where N is an integer.
    On the NeXT hardware, "midi" is a "hard" driver name and "N" is a hard unit
    number.  So, to maintain backward compatibility, we keep this interface, but
    we consider "midi" to be a signal to use soft numbering.

    Therefore, the algorithm is:

    If we're running on a non-NeXT machine,
    look at root of name (everything up to the final integer).
    If it's "midi", assume the final number is "soft".
    Otherwise, accept anything that's not "midi" as a hard driver name.

    There are two different schemes of management of interface to the MKMD functions.
    To achieve maximum portablity, we assume a Mach port is nothing more than an integer
    and functions as a handle with which to refer to a MIDI driver. It is only when receiving
    data do we need to actually behave as a Mach port. This is conditionally compiled using
    MKMD_RECEPTION_USING_PORTS defined in MKPerformSndMIDI/PerformMIDI.h. The alternative
    is to use a call back function. Therefore, while we do need a NSPort or NSMachPort,
    their support can be minimal and we are not enforced to run on a Mach type operating system.

  Original Author: David A. Jaffe
  Substantially rewritten: Leigh M. Smith

  Copyright (c) 1988-1992, NeXT Computer, Inc.
  Portions Copyright (c) 1994 NeXT Computer, Inc. and reproduced under license from NeXT
  Portions Copyright (c) 1994 Stanford University.
  Portions Copyright (c) 1999-2004, The MusicKit Project.
*/
/*
Modification history prior to commit to CVS:

  09/19/89/daj - Change to accomodate new way of doing parameters (structs 
                 rather than objects).
  01/06/90/daj - Added mergeInput option. Flushed flase cond comp.
                 Added some comments. 
  01/31/90/daj - Changed mergeInput to be an "extra var" and changed 
                 midiPorts struct to be a generic "extra var" struct. This
		 all in the interest of 1.0 backward header file compatability.
  02/25/90/daj - Moved putSysExclByte to writeMidi.
                 Changes to accomodate new way of doing midiFiles.
  03/13/90/daj - Added import of _NoteSender.h to accomodate new compiler.
  03/18/90/daj - Fixed bug in _open (needed DPSAddPort)		 
  03/19/90/daj - Changed to use MKGetNoteClass()
  04/21/90/daj - Small mods to get rid of -W compiler warnings.
  04/23/90/daj - Changes to make it a shlib and to make header files more
                 modular.
  07/24/90/daj - Changed to use _MKSprintf and _MKVsprintf for thread-safety
                 in a multi-threaded Music Kit performance.
  08/25/90/daj - Added error for "can't become owner".
  03/29/91/daj - Added awaitMidiOutDone() after allNotesOff in close and abort
  04/16/91/daj - Changed to buffer up incoming sys excl and then convert it 
                 into a string.
  04/24/91/daj - Removed (!) allNotesOff from close and abort (mmcnabb thinks
                 they should be orthogonal). Since the allNotesOff feature was
		 added only for 2.1 and wasn't documented, and since Music 
		 Prose probably isn't going to ship until 3.0, this is ok.
		 Fixed bug in awaiting for output queue to empty -- if the
		 driver was paused (we're in stopped or open mode and we've
		 sent something), the Music Kit hangs.
  08/26/91/daj - Internationalized strings.
  08/30/91/daj - Changed to set time tag of incoming notes.
                 Flushed superfluous setting of timeTag when creating MKNote
		 in sysex method.
  09/06/91/daj - Switched to new driver.  Need to release unit and driver.
  01/07/92/daj - Added break out of my_data_reply when the response
                 to the incoming MKNote is to abort.
  06/04/92/daj - Added settable conductor.
  10/20/92/daj - Set table name to _MK_ERRTAB so that localization will work.
  10/31/92/daj - Got rid of bad free of NXAtom hostname.
  11/16/92/daj - Changes for Midi time code.
  11/17/92/daj - Changes to flush warnings.
  06/30/93/daj - Added timeout to awaitMidiOutDone and such.  This is to work
                 around a (possible??) driver bug whereby MIDIAwaitReply() 
		 never returns.  I don't know what's wrong.  Maybe the driver
		 never sends the bytes or maybe the queue is available and
		 the driver doesn't tell us for some reason.  Or maybe the
		 message gets dropped on the floor, though I don't see how this
		 could happen!
  07/1/93/daj -  Added an arg to machErr for more descriptive error reporting.
  03/16/94/daj - Hacked to work around NEXTSTEP 3.2 libmididriver bug.
  09/7/94/daj -  Updated to not use libsys functions.
  10/31/98/lms - Major reorganization for OpenStep conventions, allocation and classes.
*/
#import <Foundation/NSUserDefaults.h>

/* MusicKit include files */
#import "_musickit.h"
#import "tokens.h"
#import "_error.h"
#import "_ParName.h"
#import "_midi.h"
#import "_time.h"
#import "ConductorPrivate.h"
#import "MidiPrivate.h"

@implementation MKMidi

#define MIDIINPTR(midiobj) (((MKMidi *)(midiobj))->_pIn)
#define MIDIOUTPTR(midiobj) ((midiobj)->_pOut)

#define INPUTENABLED(_x) ((_x) != MKMidiOutputOnly)
#define OUTPUTENABLED(_x) ((_x) != MKMidiInputOnly)

#define MSG_LEN_IS_VARIABLE 3

#define UNAVAIL_DRIVER_ERROR \
NSLocalizedStringFromTableInBundle(@"MIDI driver is unavailable. Perhaps another application is using it", _MK_ERRTAB, _MKErrorBundle(), "")

#define UNAVAIL_UNIT_ERROR \
NSLocalizedStringFromTableInBundle(@"MIDI port is unavailable. Perhaps another application is using the port", _MK_ERRTAB, _MKErrorBundle(), "")

#define INPUT_ERROR \
NSLocalizedStringFromTableInBundle(@"Problem receiving MIDI from the MIDI device driver port", _MK_ERRTAB, _MKErrorBundle(), "This error occurs when an error is received from the Mach MIDI driver when receiving MIDI data.")

#define OUTPUT_ERROR \
NSLocalizedStringFromTableInBundle(@"Problem sending MIDI to the MIDI device driver port", _MK_ERRTAB, _MKErrorBundle(), "This error occurs when an error is received from the MIDI driver when sending MIDI data.")

#define OWNER_ERROR \
NSLocalizedStringFromTableInBundle(@"Can't become owner of MIDI driver", _MK_ERRTAB, _MKErrorBundle(), "This error occurs when an attempt to become owner of the MIDI driver fails.")

#define OPEN_ERROR \
NSLocalizedStringFromTableInBundle(@"Problem setting up MIDI device driver", _MK_ERRTAB, _MKErrorBundle(), "This error occurs when a Mach error occurs in the course of setting up access to the MIDI device driver.")

#define NETNAME_ERROR \
NSLocalizedStringFromTableInBundle(@"Problem finding MIDI device driver", _MK_ERRTAB, _MKErrorBundle(), "This error occurs when the MIDI device driver cannot be found.")

#define CLOCK_ERROR \
NSLocalizedStringFromTableInBundle(@"Problem communicating with MIDI device driver clock", _MK_ERRTAB, _MKErrorBundle(), "This error occurs when a Mach error occurs in the course of communicating between the Music Kit and the MIDI device driver clock.")

/* Defines for system ignores. */
#define IGNORE_CLOCK	 0x0100
#define IGNORE_START	 0x0400
#define IGNORE_CONTINUE	 0x0800
#define IGNORE_STOP	 0x1000
#define IGNORE_ACTIVE	 0x4000
#define IGNORE_RESET	 0x8000
/* All of the above */
#define IGNORE_REAL_TIME (IGNORE_CLOCK + IGNORE_START + IGNORE_CONTINUE + IGNORE_STOP + IGNORE_ACTIVE + IGNORE_RESET)

// TODO This should be able to be removed.
#define FCC_DID_NOT_APPROVE_DRIVER_CHANGE 1 

#define DEFAULT_SOFT_NAME @"midi0"

#define NO_UNIT (-1)

// class variables
static int addedPortsCount = 0;
// Maps driver names to MKMidi instances. This is a slight misnomer since instances are added when 
// they are initialised, not when they are opened, yet they are removed when they are closed, not deallocated.
static NSMutableDictionary *openDrivers = nil;  
static MKMidi *receivingMidi = nil;           // the instance that has received the MIDI driver NSPort machMessage
static NSMutableArray *bidirectionalDriverNames = nil;
static NSMutableArray *inputDriverNames = nil;
static NSMutableArray *outputDriverNames = nil;
static unsigned int systemDefaultDriverNum;   // index into the midiDriverNames and units that the operating system has nominated as default
static double mtcTimeOffset = 0;

/* Some forward decls */
void handleCallBack(void *midiObj);

/* TYPE: Archiving; Writes object.
 You never send this message directly.  
 Archives the note senders and receivers, device and host names, the ports used as handles
 for communication to the performance framework, conductors, timing, I/O mode, queue sizes, status etc.
 */
- (void) encodeWithCoder: (NSCoder *) aCoder
{
    if([aCoder allowsKeyedCoding]) {
	[aCoder encodeObject: midiDevName forKey: @"MKMidi_midiDevName"];
	[aCoder encodeObject: hostname forKey: @"MKMidi_hostname"];
	[aCoder encodeObject: noteSenders forKey: @"MKMidi_noteSenders"];
	[aCoder encodeObject: noteReceivers forKey: @"MKMidi_noteReceivers"];
	
	[aCoder encodeConditionalObject: devicePort forKey: @"MKMidi_devicePort"];
	[aCoder encodeConditionalObject: ownerPort forKey: @"MKMidi_ownerPort"];
	[aCoder encodeConditionalObject: recvPort forKey: @"MKMidi_recvPort"];
	[aCoder encodeConditionalObject: queuePort forKey: @"MKMidi_queuePort"];
	[aCoder encodeConditionalObject: conductor forKey: @"MKMidi_conductor"];
	[aCoder encodeConditionalObject: synchConductor forKey: @"MKMidi_synchConductor"];
	[aCoder encodeConditionalObject: exceptionPort forKey: @"MKMidi_exceptionPort"];
	[aCoder encodeConditionalObject: alarmPort forKey: @"MKMidi_alarmPort"];
	[aCoder encodeConditionalObject: mtcMidiObj forKey: @"MKMidi_mtcMidiObj"];
	
	[aCoder encodeDouble: localDeltaT forKey: @"MKMidi_localDeltaT"];
	[aCoder encodeDouble: timeOffset forKey: @"MKMidi_timeOffset"];
	[aCoder encodeBool: useInputTimeStamps forKey: @"MKMidi_useInputTimeStamps"];
	[aCoder encodeBool: outputIsTimed forKey: @"MKMidi_outputIsTimed"];
	[aCoder encodeInt: ioMode forKey: @"MKMidi_ioMode"];
	[aCoder encodeInt: deviceStatus forKey: @"MKMidi_deviceStatus"];
	[aCoder encodeBool: isOwner forKey: @"MKMidi_isOwner"];
	[aCoder encodeBool: mergeInput forKey: @"MKMidi_mergeInput"];
	
	[aCoder encodeInt: inputUnit forKey: @"MKMidi_inputUnit"];
	[aCoder encodeInt: outputUnit forKey: @"MKMidi_outputUnit"];
	[aCoder encodeInt: queueSize forKey: @"MKMidi_queueSize"];
	[aCoder encodeDouble: alarmTime forKey: @"MKMidi_alarmTime"];
	[aCoder encodeInt: intAlarmTime forKey: @"MKMidi_intAlarmTime"];
	[aCoder encodeBool: alarmTimeValid forKey: @"MKMidi_alarmTimeValid"];
	[aCoder encodeBool: alarmPending forKey: @"MKMidi_alarmPending"];
	[aCoder encodeInt: systemIgnoreBits forKey: @"MKMidi_ignoreBits"];
    }
    else {
	[aCoder encodeObject: midiDevName];
	[aCoder encodeObject: hostname];
	[aCoder encodeObject: noteSenders];
	[aCoder encodeObject: noteReceivers];

	[aCoder encodeConditionalObject: devicePort];
	[aCoder encodeConditionalObject: ownerPort];
	[aCoder encodeConditionalObject: recvPort];
	[aCoder encodeConditionalObject: queuePort];
	[aCoder encodeConditionalObject: conductor];
	[aCoder encodeConditionalObject: synchConductor];
	[aCoder encodeConditionalObject: exceptionPort];
	[aCoder encodeConditionalObject: alarmPort];
	[aCoder encodeConditionalObject: mtcMidiObj];

	[aCoder encodeValuesOfObjCTypes: "ddcccccc", &localDeltaT, &timeOffset, &useInputTimeStamps,
	    &outputIsTimed, &ioMode, &deviceStatus, &isOwner, &mergeInput];
	[aCoder encodeValuesOfObjCTypes: "iidiccI", &outputUnit, &queueSize, &alarmTime,
	    &intAlarmTime, &alarmTimeValid, &alarmPending, &systemIgnoreBits];
    }
    //_MKMidiInStruct *_pIn;                  // TODO perhaps we can get away without archiving
    //_MKMidiOutStruct *_pOut;                // TODO perhaps we can get away without archiving
    
    NSLog(@"encodeWithCoder: queueSize = %d\n", queueSize);	
}

- (id) initWithCoder: (NSCoder *) aDecoder
{
    if([aDecoder allowsKeyedCoding]) {
	midiDevName = [aDecoder decodeObjectForKey: @"MKMidi_midiDevName"];
	hostname = [aDecoder decodeObjectForKey: @"MKMidi_hostname"];
	noteSenders = [aDecoder decodeObjectForKey: @"MKMidi_noteSenders"];
	noteReceivers = [aDecoder decodeObjectForKey: @"MKMidi_noteReceivers"];
	
	devicePort = [aDecoder decodeObjectForKey: @"MKMidi_devicePort"];
	ownerPort = [aDecoder decodeObjectForKey: @"MKMidi_ownerPort"];
	recvPort = [aDecoder decodeObjectForKey: @"MKMidi_recvPort"];
	queuePort = [aDecoder decodeObjectForKey: @"MKMidi_queuePort"];
	conductor = [aDecoder decodeObjectForKey: @"MKMidi_conductor"];
	synchConductor = [aDecoder decodeObjectForKey: @"MKMidi_synchConductor"];
	exceptionPort = [aDecoder decodeObjectForKey: @"MKMidi_exceptionPort"];
	alarmPort = [aDecoder decodeObjectForKey: @"MKMidi_alarmPort"];
	mtcMidiObj = [aDecoder decodeObjectForKey: @"MKMidi_mtcMidiObj"];
	
	localDeltaT = [aDecoder decodeDoubleForKey: @"MKMidi_localDeltaT"];
	timeOffset = [aDecoder decodeDoubleForKey: @"MKMidi_timeOffset"];
	useInputTimeStamps = [aDecoder decodeBoolForKey: @"MKMidi_useInputTimeStamps"];
	outputIsTimed = [aDecoder decodeBoolForKey: @"MKMidi_outputIsTimed"];
	ioMode = [aDecoder decodeIntForKey: @"MKMidi_ioMode"];
	deviceStatus = [aDecoder decodeIntForKey: @"MKMidi_deviceStatus"];
	isOwner = [aDecoder decodeBoolForKey: @"MKMidi_isOwner"];
	mergeInput = [aDecoder decodeBoolForKey: @"MKMidi_mergeInput"];
	
	inputUnit = [aDecoder decodeIntForKey: @"MKMidi_inputUnit"];
	outputUnit = [aDecoder decodeIntForKey: @"MKMidi_outputUnit"];
	queueSize = [aDecoder decodeIntForKey: @"MKMidi_queueSize"];
	alarmTime = [aDecoder decodeDoubleForKey: @"MKMidi_alarmTime"];
	intAlarmTime = [aDecoder decodeIntForKey: @"MKMidi_intAlarmTime"];
	alarmTimeValid = [aDecoder decodeBoolForKey: @"MKMidi_alarmTimeValid"];
	alarmPending = [aDecoder decodeBoolForKey: @"MKMidi_alarmPending"];
	systemIgnoreBits = [aDecoder decodeIntForKey: @"MKMidi_ignoreBits"];
    }
    else {	
	if ([aDecoder versionForClassName: @"MKMidi"] == 1) {
	    midiDevName = [[aDecoder decodeObject] retain];
	    hostname = [[aDecoder decodeObject] retain];
	    noteSenders = [[aDecoder decodeObject] retain];
	    noteReceivers = [[aDecoder decodeObject] retain];
	    
	    devicePort = [[aDecoder decodeObject] retain];
	    ownerPort = [[aDecoder decodeObject] retain];
	    recvPort = [[aDecoder decodeObject] retain];
	    queuePort = [[aDecoder decodeObject] retain];
	    conductor = [[aDecoder decodeObject] retain];
	    synchConductor = [[aDecoder decodeObject] retain];
	    exceptionPort = [[aDecoder decodeObject] retain];
	    alarmPort = [[aDecoder decodeObject] retain];
	    mtcMidiObj = [[aDecoder decodeObject] retain];

	    [aDecoder decodeValuesOfObjCTypes:"ddcccccc", &localDeltaT, &timeOffset, &useInputTimeStamps,
		&outputIsTimed, &ioMode, &deviceStatus, &isOwner, &mergeInput];
	    [aDecoder decodeValuesOfObjCTypes:"iidiccI", &outputUnit, &queueSize, &alarmTime,
		&intAlarmTime, &alarmTimeValid, &alarmPending, &systemIgnoreBits];
	}
    }
    NSLog(@"initWithCoder: queueSize = %d\n", queueSize);
    return self;
}

NSString *midiDriverErrorString(int errorCode)
{
    return [NSString stringWithCString: MKMDErrorString(errorCode)];
}

- (BOOL) unitHasMTC
{
    return (synchConductor && mtcMidiObj == self);
}

// This method searches for any other Midi objects on hostname NOT matching the specified unit.
+ (NSMutableArray *) midisOnHost: (NSString *) midiHostname
	      otherThanInputUnit: (int) midiInputUnit
		    orOutputUnit: (int) midiOutputUnit
{
    MKMidi *midiObj;
    NSMutableArray *midisNotMatching = [NSMutableArray array];
    // This is inefficient, once we can do better compares we should retrieve the objectsForKeys:notFoundMarker:.
    // which has the port as the key
    NSEnumerator *enumerator = [openDrivers objectEnumerator];
    
    while ((midiObj = [enumerator nextObject])) {
        if ([midiObj->hostname isEqualToString: midiHostname] && 
	    (midiObj->inputUnit != midiInputUnit) &&
	    (midiObj->outputUnit != midiOutputUnit))
            [midisNotMatching addObject: midiObj];
    }
    return midisNotMatching;
}

// Returns YES if we closed the MIDI device correctly
- (BOOL) closeMidiDevice
{
    BOOL somebodyElseHasOwnership = NO;
    NSMutableArray *otherMidis = nil;

    if (!ownerPort)
	return YES;
    otherMidis = [MKMidi midisOnHost: hostname otherThanInputUnit: inputUnit orOutputUnit: outputUnit];
    
    if (INPUTENABLED(ioMode)) {
	MKMDReleaseUnit(YES, (MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], inputUnit);
	if (recvPort) {
#if MKMD_RECEPTION_USING_PORTS
	    _MKRemovePort(recvPort);
	    addedPortsCount--;
#endif
	    [recvPort release];
	}
    }
    if (OUTPUTENABLED(ioMode)) {
	MKMDReleaseUnit(NO, (MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], outputUnit);
	[queuePort release];	
    }
    if ([self unitHasMTC])
        [self tearDownMTC];
    if ([otherMidis count] == 0) 
        somebodyElseHasOwnership = NO;
    else {
	MKMidi *aMidi;
	int i, cnt = [otherMidis count];
	for (i = 0; i < cnt && !somebodyElseHasOwnership; i++) {
	    aMidi = [otherMidis objectAtIndex: i];
	    if (aMidi->ownerPort) 
                somebodyElseHasOwnership = YES;
	}
    }
    if (!somebodyElseHasOwnership) {
	MKMDReleaseOwnership((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort]);
	[ownerPort release];
    } 
    ownerPort = nil;
    // Release our device port, reset all ports to nil to guard against reuse. Better no output than crashing, well maybe...
    [devicePort release];
    devicePort = nil;
    // released earlier.
    recvPort = nil;
    queuePort = nil;
    // This is actually a bit too early to remove ourselves from the port table, since we were added during initOnDevice:hostname:.
    // However we can not do this in dealloc since removeObjectForKey: will release the object causing a dealloc infinite loop.
    // This is almost the right place to remove it, since it is now closed and cannot receive further MIDI.
    [openDrivers removeObjectForKey: midiDevName]; 
    return YES;
}

/* "Opens". If the device represented by devicePortName is already 
   accessed by this task, uses the ownerPort currently accessed.
   Otherwise, if ownerPort is nil, allocates a new
   port. Otherwise, uses ownerPort as specified. 
   To make the device truly public, you can pass the device port as the
   owner port. Returns the MIDI driver MKMDReturn status, MKMD_SUCCESS 
   if the device was successfully opened.
   */
- (MKMDReturn) openMidiDevice
{
    MKMDReturn r;
    NSMutableArray *otherMidis = nil;
    MKMDPort driverDevicePort;

    // We know that midiDevName has already been mapped to a hard device since it is done when this instance is initialised.
    if (INPUTENABLED(ioMode))
	inputUnit = [inputDriverNames indexOfObject: midiDevName];
    if (OUTPUTENABLED(ioMode))
	outputUnit = [outputDriverNames indexOfObject: midiDevName];
    
    driverDevicePort = MKMDGetMIDIDeviceOnHost([hostname cString]);

    if (driverDevicePort == (MKMDPort) NULL) {
        MKErrorCode(MK_machErr, NETNAME_ERROR, @"Unable to find devicePort", @"MIDI Port Server lookup");
        return !MKMD_SUCCESS;
    }
    devicePort = [[NSMachPort portWithMachPort: (int) driverDevicePort] retain];
    otherMidis = [MKMidi midisOnHost: hostname otherThanInputUnit: inputUnit orOutputUnit: outputUnit];
    if ([otherMidis count]) {
        int unitIndex;
        int unitCount = [otherMidis count];
	
        for (unitIndex = 0; unitIndex < unitCount; unitIndex++) {
	    MKMidi *aMidi = [otherMidis objectAtIndex: unitIndex];
	    
            /* Should be the first one, but just in case... */
            if (aMidi->ownerPort != nil) {
                ownerPort = aMidi->ownerPort;
                break;
            }
        }
    }
    if (!ownerPort) {
        ownerPort = [[NSPort port] retain];
        if (ownerPort == nil) {
            MKErrorCode(MK_machErr, OWNER_ERROR, @"Unable to create ownerPort", @"-openMidiDevice owner NSPort allocate");
	    return !MKMD_SUCCESS;
	}
	r = MKMDBecomeOwner((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort]);
	if (r != MKMD_SUCCESS) {
	    isOwner = NO;
	    MKErrorCode(MK_musicKitErr, UNAVAIL_DRIVER_ERROR);
	    [self closeMidiDevice];
	    return r;
	}
    }
    if (INPUTENABLED(ioMode)) {
	r = MKMDClaimUnit(YES, (MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], inputUnit);
	if (r != MKMD_SUCCESS) {
	    MKErrorCode(MK_musicKitErr, UNAVAIL_UNIT_ERROR);
	    [self closeMidiDevice];
	    return r;
	}
    }
    if (OUTPUTENABLED(ioMode)) {
	r = MKMDClaimUnit(NO, (MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], outputUnit);
	if (r != MKMD_SUCCESS) {
	    MKErrorCode(MK_musicKitErr, UNAVAIL_UNIT_ERROR);
	    [self closeMidiDevice];
	    return r;
	}	
    }

    r = MKMDSetClockQuantum((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], _MK_MIDI_QUANTUM);
    if (r != MKMD_SUCCESS) {
	MKErrorCode(MK_musicKitErr, OPEN_ERROR);
	[self closeMidiDevice];
	return r;
    }

    r = MKMDSetClockMode((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], -1, MKMD_CLOCK_MODE_INTERNAL);
    if (r != MKMD_SUCCESS) {
	MKErrorCode(MK_musicKitErr,OPEN_ERROR);
	[self closeMidiDevice];
	return r;
    }

    /* Input */
    if (INPUTENABLED(ioMode)) {
        recvPort = [[NSPort port] retain];
        if (recvPort == nil) {
            MKErrorCode(MK_machErr, OPEN_ERROR, @"Unable to create recvPort", @"-openMidiDevice recv NSPort allocate");
	    [self closeMidiDevice];
	    return !MKMD_SUCCESS;
	}
#if MKMD_RECEPTION_USING_PORTS
        /* sb: first self was midiIn. Changed to self because 'self' responds to -handleMachMessage */
        _MKAddPort([NSMachPort portWithMachPort: (int) recvPort], self, 0, self, _MK_DPSPRIORITY);
	addedPortsCount++;
#else
        MKMDSetReplyCallback((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], inputUnit, handleCallBack, (void *) self);
#endif
    }
    if (OUTPUTENABLED(ioMode)) {
        queuePort = [[NSPort port] retain];
        if (queuePort == nil) {
            MKErrorCode(MK_machErr, OPEN_ERROR, @"Unable to create queuePort", @"-openMidiDevice queue NSPort allocate");
	    [self closeMidiDevice];
            return !MKMD_SUCCESS;
	}
	r = MKMDGetAvailableQueueSize((MKMDPort) [devicePort machPort],
				      (MKMDOwnerPort) [ownerPort machPort],
				      outputUnit,
				      &(queueSize));
	if (r != MKMD_SUCCESS) {
            MKErrorCode(MK_machErr, OPEN_ERROR, midiDriverErrorString(r), @"MKMDGetAvailableQueueSize");
	    [self closeMidiDevice];
	    return r;
	}
    }
    if ([self unitHasMTC])
	[self setUpMTC];
    return MKMD_SUCCESS;
}    

// At the moment this is really just a stub for determining time from a host
- (void) getTimeInfoFromHost: (NSString *) timeInfoHostname
{
    static NSMutableDictionary *timeInfoTable = nil;
    NSData *timeVarsEncoded;

    if (!timeInfoTable) /* Mapping from hostname to tvs pointer */
        timeInfoTable = [[NSMutableDictionary dictionary] retain];
    if ((timeVarsEncoded = [timeInfoTable objectForKey: timeInfoHostname]) != nil) {
        // TODO Assign ivars from [timeVarsEncoded bytes] or somesuch if timeVarsEncoded changes to be an object.
    }
    else { // initialise MTC ivars
        synchConductor = nil;                // If non-nil, time mode is MTC Synch
        exceptionPort =  nil;                // Exception port.  Only one unit per device may have one
        alarmPort =  nil;                    // Alarm port.  Only one unit per device may have one
        mtcMidiObj = nil;                    // No unit is receiving MTC.
        alarmTime = 0.0;
        intAlarmTime = 0;
        alarmTimeValid = NO;
        alarmPending = NO;
        // TODO assign MTC ivars into NSData or object and use the following to save it.
        // [timeInfoTable setObject: [NSData dataWithBytes: ?] forKey: hostname];
    }
}

static void waitForRoom(MKMidi *self, int elements, int timeOut)
{
    MKMDReturn r;
    MKMDReplyFunctions recvStruct = {0};
    r = MKMDRequestQueueNotification((MKMDPort) [self->devicePort machPort],
				     (MKMDOwnerPort) [self->ownerPort machPort],
				     self->outputUnit,
				     (MKMDReplyPort) [self-> queuePort machPort],
				     elements);
    if (r != MKMD_SUCCESS)
        MKErrorCode(MK_machErr, OUTPUT_ERROR, midiDriverErrorString(r),
                    @"waitForRoom queue notification request");
    r = MKMDAwaitReply((MKMDReplyPort) [self->queuePort machPort], &recvStruct, timeOut); // THIS BLOCKS!
    if (r != MKMD_SUCCESS) 
	MKErrorCode(MK_machErr, OUTPUT_ERROR, midiDriverErrorString(r),
		  @"waitForRoom MKMDAwaitReply");
}

static void awaitMidiOutDone(MKMidi *self,int timeOut)
    /* Wait until Midi is done and then return */
{
    // NSLog(@"waiting for room of %d, with timeOut = %d\n", self->queueSize, timeOut);
    waitForRoom(self, self->queueSize, timeOut);
}

static int stopMidiClock(MKMidi *self)
{
    MKMDReturn r;
    if (self->synchConductor) {
	r = MKMDRequestExceptions((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], MKMD_PORT_NULL);
	if (r != MKMD_SUCCESS)
	    MKErrorCode(MK_machErr,CLOCK_ERROR, midiDriverErrorString(r), @"stopMidiClock MKMDRequestExceptions");
	r = MKMDSetClockMode((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, MKMD_CLOCK_MODE_INTERNAL);
	if (r != MKMD_SUCCESS)
	    MKErrorCode(MK_machErr,CLOCK_ERROR, midiDriverErrorString(r), @"stopMidiClock MKMDSetClockMode");
        r = MKMDRequestAlarm((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], MKMD_PORT_NULL, 0);
	if (r != MKMD_SUCCESS)
	    MKErrorCode(MK_machErr,CLOCK_ERROR, midiDriverErrorString(r), @"stopMidiClock MKMDRequestAlarm");
	self->alarmPending = NO;
	return r;
    }
    r = MKMDStopClock((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort]);
    if (r != MKMD_SUCCESS)
	MKErrorCode(MK_machErr, CLOCK_ERROR, midiDriverErrorString(r), @"stopMidiClock MKMDStopClock");
    return r;
}

static int resumeMidiClock(MKMidi *self)
{
    MKMDReturn r;
    
    if (self->synchConductor) {
	r = MKMDRequestExceptions((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], (MKMDReplyPort) [self->exceptionPort machPort]);
	if (r != MKMD_SUCCESS)
	    MKErrorCode(MK_machErr, CLOCK_ERROR, midiDriverErrorString(r), @"resumeMidiClock MKMDRequestExceptions");
	r = MKMDSetClockMode((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, MKMD_CLOCK_MODE_MTC_SYNC);
	if (r != MKMD_SUCCESS)
	    MKErrorCode(MK_machErr, CLOCK_ERROR, midiDriverErrorString(r), @"resumeMidiClock MKMDSetClockMode");
	if (self->alarmTimeValid) {
	    r = MKMDRequestAlarm((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], (MKMDReplyPort) [self->alarmPort machPort], self->alarmTime);
	    self->alarmPending = YES;
	    if (r != MKMD_SUCCESS)
		MKErrorCode(MK_machErr, CLOCK_ERROR, midiDriverErrorString(r), @"resumeMidiClock MKMDRequestAlarm");
	}
	return r;
    }
    r = MKMDStartClock((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort]);
    if (r != MKMD_SUCCESS)
	MKErrorCode(MK_machErr, CLOCK_ERROR, midiDriverErrorString(r), @"resumeMidiClock MKMDStartClock");
    return r;
}

static int resetAndStopMidiClock(MKMidi *self)
{
    MKMDReturn r;
    
    stopMidiClock(self);
    r = MKMDSetClockTime((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], 0);
    if (r != MKMD_SUCCESS)
      MKErrorCode(MK_machErr, CLOCK_ERROR, midiDriverErrorString(r), @"resetAndStopMidiClock");
    return r;
}

static int emptyMidi(MKMidi *self)
    /* Get rid of enqueued outgoing midi messages */
{
    MKMDReturn r;
    r = MKMDClearQueue((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], self->outputUnit);
    if (r != MKMD_SUCCESS)
        MKErrorCode(MK_machErr, OUTPUT_ERROR, midiDriverErrorString(r), @"emptyMidi");
    // NSLog(@"emptying the enqued MIDI messages\n");
    return r;
}

static int setMidiSysIgnore(MKMidi *self,unsigned bits)
    /* Tell driver to ignore particular incoming MIDI system messages */
{
#if FCC_DID_NOT_APPROVE_DRIVER_CHANGE
    int r = MKMDSetSystemIgnores((MKMDPort) [self->devicePort machPort], (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, bits);
#else 
    int r = 0;
    r |= MKMDFilterMessage(devicePort, (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, 
			   MIDI_CLOCK, bits & IGNORE_CLOCK);
    r |= MKMDFilterMessage(devicePort, (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, 
			   MIDI_START, bits & IGNORE_START);
    r |= MKMDFilterMessage(devicePort, (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, 
			   MIDI_CONTINUE, bits & IGNORE_CONTINUE);
    r |= MKMDFilterMessage(devicePort, (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, 
			   MIDI_STOP, bits & IGNORE_STOP);
    r |= MKMDFilterMessage(devicePort, (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, 
			   MIDI_ACTIVE, bits & IGNORE_ACTIVE);
    r |= MKMDFilterMessage(devicePort, (MKMDOwnerPort) [self->ownerPort machPort], self->inputUnit, 
			   MIDI_RESET, bits & IGNORE_RESET);
#endif
    if (r != MKMD_SUCCESS) 
      MKErrorCode(MK_machErr, INPUT_ERROR, midiDriverErrorString(r), @"");
    return r;
}


/* Low-level output routines */

/* We currently use MIDI "raw" mode. Perhaps cooked mode would be more efficient? */

#define MIDIBUFSIZE MKMD_MAX_EVENT

static MKMDRawEvent midiBuf[MIDIBUFSIZE];
static MKMDRawEvent *bufPtr = &(midiBuf[0]);

static void putTimedByte(unsigned curTime, unsigned char aByte)
    /* output a MIDI byte */
{
    bufPtr->time = curTime;
    bufPtr->byte = aByte;
    bufPtr++;
}

static void sendBufferedData(struct __MKMidiOutStruct *ptr)
    /* Send any buffered bytes and reset pointer to start of buffer */
{
    MKMDReturn r;
    MKMidi *midiObj;
    int nBytes;
    nBytes = bufPtr - &(midiBuf[0]);
    if (nBytes == 0)
	return;
    midiObj = ((MKMidi *) ptr->_owner);
    for (; ;) {
	r = MKMDSendData((MKMDPort) [midiObj->devicePort machPort],
	                 (MKMDOwnerPort) [midiObj->ownerPort machPort],
                         midiObj->outputUnit, &(midiBuf[0]), nBytes);
	if (r == MKMD_ERROR_QUEUE_FULL) 
	    waitForRoom(midiObj, nBytes, MKMD_NO_TIMEOUT);
	else
            break;
    }
    if (r != MKMD_SUCCESS) 
	MKErrorCode(MK_machErr, OUTPUT_ERROR, midiDriverErrorString(r), @"sendBufferedData");
    bufPtr = &(midiBuf[0]);
}

static void putTimedByteWithCheck(struct __MKMidiOutStruct *ptr, unsigned curTime, unsigned char aByte)
    /* Same as above, but checks for full buffer */
{
    if ((&(midiBuf[MIDIBUFSIZE])) == bufPtr) 
        sendBufferedData(ptr);
    putTimedByte(curTime, aByte);
}


static void putMidi(struct __MKMidiOutStruct *ptr)
    /* Adds a complete MIDI message to the output buffer */
{
    unsigned int curTime = .5 + ptr->_timeTag * _MK_MIDI_QUANTUM;
    if (((&(midiBuf[MIDIBUFSIZE])) - bufPtr) < ptr->_outBytes)
      sendBufferedData(ptr);
    putTimedByte(curTime,ptr->_bytes[0]);
    if (ptr->_outBytes >= 2)
      putTimedByte(curTime,ptr->_bytes[1]);
    if (ptr->_outBytes == 3)
      putTimedByte(curTime,ptr->_bytes[2]);
}

static void putSysExcl(struct __MKMidiOutStruct *ptr, NSString *sysExclString)
{
    /* sysExStr is a string. The string consists of system exclusive bytes
	separated by any non-digit delimiter. The musickit uses the 
	delimiter ','. E.g. "f8,13,f7".  This function converts each ASCII
	byte into the corresponding number and sends it to serial port.
       Note that if you want to give each sysex byte a different
       delay, you need to do a separate call to this function.
       On a higher level, this means that you need to put each
       byte in a different MKNote object. 
	The string may but need not begin with MIDI_SYSEXCL and end with
	MIDI_EOX. 
       */
    /* note we cast to char* not const char* because although we're not
     * going to alter the contents of the string, we are going to need to
     * alter the *sysExclStr pointer (in _MKGetSysExByte).
     */
    char *sysExclStr = (char *)[sysExclString cString];
    unsigned char c;
    unsigned int curTime = .5 + ptr->_timeTag * _MK_MIDI_QUANTUM;
    sendBufferedData(ptr);
    c = _MKGetSysExByte(&sysExclStr);
    if (c == MIDI_EOX)
        return;
    if (c != MIDI_SYSEXCL) 
        putTimedByte(curTime, MIDI_SYSEXCL);
    putTimedByte(curTime, c);
    while (*sysExclStr) {
        c = _MKGetSysExByte(&sysExclStr);
	putTimedByteWithCheck(ptr, curTime, c);
        // Add an inter-byte delay of 300mS to avoid overflow problems in slow synthesisers.
        // TODO this should actually be a note parameter: MK_interByteDelay
//        curTime += 300 * _MK_MIDI_QUANTUM;
//        curTime += 300;
    }
    if (c != MIDI_EOX) 
        putTimedByteWithCheck(ptr, curTime, MIDI_EOX);  /* Terminate it properly */
}

/* Midi parsing. */

/* Currently we use raw input mode. That means we have to parse the MIDI
   ourselves. Perhaps it'd be more efficient to let the driver do the
   parsing (i.e. use the driver's "cooked" mode). But for 1.0, the driver 
   was finished so late, I was afraid to trust its hardly-debugged code. -
   DAJ */

static unsigned char parseMidiStatusByte(unsigned char statusByte, _MKMidiInStruct *ptr)
    /* This is called when a status byte is found. Returns YES if the status
       byte is a system real time or system exclusive message. */
{
    switch (MIDI_OP(statusByte)) {
      case MIDI_PROGRAM: 
      case MIDI_CHANPRES:
	ptr->_statusByte = ptr->_runningStatus = statusByte;
	ptr->_dataBytes = 1;
	return 0;
      case MIDI_NOTEON:
      case MIDI_NOTEOFF:
      case MIDI_POLYPRES:
      case MIDI_CONTROL:
      case MIDI_PITCH:
	ptr->_statusByte = ptr->_runningStatus = statusByte;
	ptr->_dataBytes = 2;
	ptr->_firstDataByteSeen = NO;
	return 0;
      case MIDI_SYSTEM:
	if (!(statusByte & MIDI_SYSRTBIT)) {
	    ptr->_runningStatus = 0;
	    ptr->_statusByte = statusByte;
	    switch (statusByte) {
	      case MIDI_SONGPOS:
		ptr->_dataBytes = 2;
		ptr->_firstDataByteSeen = NO;
		return 0;
	      case MIDI_TIMECODEQUARTER:
	      case MIDI_SONGSEL:
		ptr->_dataBytes = 1;
		return 0;
	      case MIDI_SYSEXCL:
		ptr->_dataBytes = MSG_LEN_IS_VARIABLE;
		return MIDI_SYSEXCL;
	      case MIDI_TUNEREQ:         
		ptr->_dataBytes = 0;
		return MIDI_TUNEREQ;
	      case MIDI_EOX: {          
		  BOOL isInSysEx = (ptr->_dataBytes == MSG_LEN_IS_VARIABLE);
		  ptr->_dataBytes = 0;
		  return (isInSysEx) ? MIDI_SYSEXCL : 0;
	      }
	    }
	}
	else switch (statusByte) {
	  case MIDI_CLOCK:            /* System real time messages. */
	  case MIDI_START:
	  case MIDI_STOP:
	  case MIDI_ACTIVE:
	  case MIDI_RESET:
	  case MIDI_CONTINUE:
	    return statusByte; /* Doesn't affect running status. */
	                       /* Also doesn't affect _dataBytes. This
				  is because real-time messages may occur
				  anywhere, even in a system exclusive 
				  message. */
	  default:             /* Omit unrecognized status. */
	    return 0;         
	}                      
      default:                 /* Garbage */
	ptr->_dataBytes = 0;
	return 0;             
    }   
}

static unsigned char parseMidiByte(unsigned char aByte, _MKMidiInStruct *ptr)
    /* Takes an incoming byte and parses it */
{
    if (MIDI_STATUSBIT & aByte)  
      return parseMidiStatusByte(aByte,ptr);
    switch (ptr->_dataBytes) {
      case 0:                      /* Running status or garbage */
	if (!ptr->_runningStatus)  /* Garbage */
	  return 0;
	parseMidiStatusByte(ptr->_runningStatus,ptr);
	return parseMidiByte(aByte,ptr);
      case 1:                      /* One-argument midi message. */
	ptr->_dataByte1 = aByte;
	ptr->_dataBytes = 0;  /* Reset */
	return ptr->_statusByte;
      case 2:                      /* Two-argument midi message. */
	if (ptr->_firstDataByteSeen) {
	    ptr->_dataByte2 = aByte;
	    ptr->_dataBytes = 0;
	    return ptr->_statusByte;
	}
	ptr->_dataByte1 = aByte;
	ptr->_firstDataByteSeen = YES;
	return 0;
      case MSG_LEN_IS_VARIABLE:
	return MIDI_SYSEXCL;
      default:
	return 0;
    }
}

static id handleSysExclbyte(_MKMidiInStruct *ptr,unsigned char midiByte)
    /* Parsing routine for incoming system exclusive */
    /* We don't return an autoreleased object - just the raw
     * MKNote because there's only one place where this is called
     * and we know we don't need the autorelease
     */
{
#   define DEFAULTLEN 256
    if (midiByte == MIDI_SYSEXCL) {  /* It's a new one. */
	if (!ptr->_sysExBuf) {
	    _MK_MALLOC(ptr->_sysExBuf,unsigned char,DEFAULTLEN);
	    ptr->_sysExSize = DEFAULTLEN;
	} 
	ptr->_endOfSysExBuf = ptr->_sysExBuf + ptr->_sysExSize;
	ptr->_sysExP = ptr->_sysExBuf;
	*ptr->_sysExP++ = midiByte;
    }
    else {
	if (ptr->_sysExP >= ptr->_endOfSysExBuf) { 
	    int offset = ptr->_sysExP - ptr->_sysExBuf; 
	    ptr->_sysExSize *= 2;
	    _MK_REALLOC(ptr->_sysExBuf,unsigned char,ptr->_sysExSize);
	    ptr->_endOfSysExBuf = ptr->_sysExBuf + ptr->_sysExSize;
	    ptr->_sysExP = ptr->_sysExBuf + offset;
	}
	*ptr->_sysExP++ = midiByte;
    }
    if (midiByte == MIDI_EOX) {
	unsigned char *p;
	NSString *sysExString;

	[ptr->_note release]; /* Free old note. */ 
	ptr->_note = [MKGetNoteClass() new];
	p = ptr->_sysExBuf;
        sysExString = [NSString stringWithFormat: @"%-2x", (unsigned) *p++]; /* First byte */
	while (p < ptr->_sysExP) {
            sysExString = [sysExString stringByAppendingFormat: @",%-2x", (unsigned) *p++];
	}
	[ptr->_note setPar: MK_sysExclusive toString: sysExString];
	/* We might want to use a special setPar: that doesn't turn the
	   thing into an NXAtom.  This would involve introducing a
	   noCopy type into Note.m.  FIXME */
	ptr->chan = _MK_MIDISYS; 	
	return (id)ptr->_note;
    }
    return nil; /* We're not done yet. */
} 

static void sendIncomingNote(short chan, MKNote *aNote, MKMidi *sendingMidi, int quanta)
{
    if (aNote) {
	MKConductor *synchCond = sendingMidi->synchConductor;
	double t = (((double) quanta) * _MK_MIDI_QUANTUM_PERIOD + sendingMidi->timeOffset);
	
	if (MKGetDeltaTMode() == MK_DELTAT_SCHEDULER_ADVANCE) 
	    t += MKGetDeltaT();
	if (synchCond)
	    t -= mtcTimeOffset;
	[aNote setTimeTag: t];
        if (sendingMidi->useInputTimeStamps) 
	    if (synchCond)
		[synchCond _setMTCTime: (double) t];
	    else 
		_MKAdjustTime(t); /* Use input time stamp time */
	else 
	    [_MKClassConductor() adjustTime]; 
	if (sendingMidi->mergeInput) { /* Send all on one MKNoteSender? */
	    MKSetNoteParToInt(aNote, MK_midiChan, chan);
            [[sendingMidi->noteSenders objectAtIndex: 0] sendNote: aNote];
	}
        else {
            [[sendingMidi->noteSenders objectAtIndex: chan] sendNote: aNote];
        }
	[_MKClassOrchestra() flushTimedMessages]; /* Off to the DSP */
    }
}

static int incomingDataCount = 0; /* We use a static here to allow us to
				   * break out of my_data_reply.  Note that
				   * my_data_reply can never be called
				   * recursively so there's no danger in doing
				   * this. 
				   */

// my_data_reply manages the incoming MIDI events. It is called from MKMDHandleReply.
// It may be called multiple times successively with events from the MKMDHandleReply mechanism.
static void my_data_reply(MKMDReplyPort reply_port, short unit, MKMDRawEvent *events, unsigned int count) {
    _MKMidiInStruct *ptr;
    MKNote *aNote;
    unsigned char statusByte;

    // check we assigned this in handleMachMessage/handleCallback and it survives the driver.
    if(receivingMidi == nil) { 
        MKErrorCode(MK_musicKitErr, @"Internal error, receiving MKMidi has not been assigned");
        return;
    }
    ptr = MIDIINPTR(receivingMidi);
    if(receivingMidi->displayReceivedMIDI)
	NSLog(@"MKMidi received %d bytes: first is %02X\n", count, events->byte);
    for (incomingDataCount = count; incomingDataCount--; events++) {
	if ((statusByte = parseMidiByte(events->byte, ptr))) {
	    if (statusByte == MIDI_SYSEXCL)
                aNote = handleSysExclbyte(ptr, events->byte); /* not retained or autoreleased */
	    else
                aNote = _MKMidiToMusicKit(ptr, statusByte); /* autoreleased */
	    if (aNote) {
                sendIncomingNote(ptr->chan, aNote, receivingMidi, events->time);
		/* sending the MKNote can have unknown side-effects, since the
		 * user defines the behavior here.  For example, the MKMidi obj 
		 * could be aborted or re-opened. It could even be freed!
		 * So when we abort, we clear incomingDataCount.  This 
		 * guarantees that we won't be left in a bad state */
	    }
	}
    }
    // since my_data_reply can be called several times successively, we let the 
    // handleMachMessage/handleCallback routines reset receivingMidi to nil.
}

/*sb: added the following method to handle mach messages. This replaces the earlier function
 * because instead of DPSAddPort specifying a function,
 * DPSAddPort() replaced with:
 * [[NSPort portWithMachPort:] retain]
 * [NSPort setDelegate:]
 * [NSRunLoop addPort:forMode:]
 *
 * The delegate has to repond to selector -handleMachMessage or -handlePortMessage
 */

- (void) handleMachMessage: (void *) machMessage
{
    msg_header_t *msg = (msg_header_t *) machMessage;
    NSString *errorMessage;
    MKMDReturn r;
    /* Tells driver funcs to call: */ 
    // MKMDReplyFunctions recvStruct = { my_data_reply, my_alarm_reply, my_exception_reply, 0};
    MKMDReplyFunctions recvStruct = { my_data_reply, 0, 0, 0};

    // determine what the port is that called this method, then set the appropriate my_*_reply function
    // and error message.
    // if the error is from midiAlarm or Exception, CLOCK_ERROR rather than INPUT_ERROR should be used.
    errorMessage = INPUT_ERROR;

    receivingMidi = self;
    // Eventually MKMDHandleReply should be unnecessary, when we receive the MIDI data direct into handlePortMessage
    // Then we can merge this method and my_data_reply into a single handlePortMessage. 
    r = MKMDHandleReply(msg, &recvStruct);        /* This gets data */
    if (r != MKMD_SUCCESS) {
      MKErrorCode(MK_machErr, errorMessage, midiDriverErrorString(r), @"midiIn");
    }

    // to rigorously check handleMachMessage does its job, detects spurious wrong messages being sent.
    receivingMidi = nil; 
}

// The alternative to using a Mach message is to use a call back function to receive the MIDI data.
void handleCallBack(void *midiObj)
{
    NSString *errorMessage;
    MKMDReturn result;
    /* Tells driver funcs to call: */ 
    // TODO MKMDReplyFunctions recvStruct = { my_data_reply, my_alarm_reply, my_exception_reply, 0};
    MKMDReplyFunctions recvStruct = { my_data_reply, 0, 0, 0};
    // since the callback is coming in from the cold harsh world of C, not cozy ObjC:
    NSAutoreleasePool *handlerPool = [[NSAutoreleasePool alloc] init]; 

    // TODO determine what the port is that called this method, then set the appropriate my_*_reply function
    // and error message.
    // TODO if the error is from midiAlarm or Exception, CLOCK_ERROR rather than INPUT_ERROR should be used.
    errorMessage = INPUT_ERROR;

    receivingMidi = (MKMidi *) midiObj;
    // NSLog(@"receivingMIDI %@\n", receivingMidi);
    result = MKMDHandleReply(NULL, &recvStruct);        /* This gets data */
    if (result != MKMD_SUCCESS) {
	MKErrorCode(MK_machErr, errorMessage, midiDriverErrorString(result), @"midiIn");
    }
    
    // to rigorously check handleCallBack does its job, detects spurious wrong messages being sent.
    receivingMidi = nil; 
    [handlerPool release];
}
/* Input configuration */

- setUseInputTimeStamps: (BOOL) yesOrNo
{
    if (deviceStatus != MK_devClosed)
      return nil;
    useInputTimeStamps = yesOrNo;
    return self;
}

- (BOOL) useInputTimeStamps
{
    return useInputTimeStamps;
}

 
static unsigned ignoreBit(unsigned param)
{
    switch (param) {
      case MK_sysActiveSensing:
	return IGNORE_ACTIVE;
      case MK_sysClock:
	return IGNORE_CLOCK;
      case MK_sysStart:
	return IGNORE_START;
      case MK_sysContinue:
	return IGNORE_CONTINUE;
      case MK_sysStop:
	return IGNORE_STOP;
      default:
	break;
    }
    return 0;
}

- ignoreSys: (MKMidiParVal) param
{
    systemIgnoreBits |= ignoreBit(param);
    if (deviceStatus != MK_devClosed)
	setMidiSysIgnore(self, systemIgnoreBits);
    return self;
} 

- acceptSys: (MKMidiParVal) param 
{
    systemIgnoreBits &= ~(ignoreBit(param));
    if (deviceStatus != MK_devClosed)
	setMidiSysIgnore(self, systemIgnoreBits);
    return self;
}

/* MKPerformer-like methods. */

- (MKConductor *) conductor
{
    return conductor ? conductor : [_MKClassConductor() clockConductor];
}

- setConductor: (MKConductor *) aConductor
{
    conductor = aConductor;
    return self;
}

/* Creation */

/* This mechanism is more general than we need, because the rest of this
   object currently assumes that there's only one MIDI driver called 
   MK_NAME.  However, in case we ever support others, I want to support
   the general API.  And since this code was already written for the DSP
   case, I thought I'd just grab it from there.
   LMS: The day is rapidly approaching when we may need all of David's functionality
   with Win32 named ports, MacOS X CoreMIDI USB devices etc.
 */

// This retieves MIDI drivers via MKPerformSndMIDI framework based drivers.
// Return YES if able to retrieve lists of names of input, output and bidirectional MIDI drivers.
// A driver is considered here to be a named service providing 16 channels of MIDI in or out.
// Bidirectional drivers are determined to be those drivers which are the intersection of the input and 
// output lists. If the MKPerformSndMIDI framework for a given platform does not distinguish between
// input and output drivers (for example the original NeXT hardware assumes bidirectionality of all drivers
// returned), all three driver name lists will be the same.
// Returns NO if there was no MIDI driver found. 
+ (BOOL) getAllAvailableMidiDevices
{
    int systemInputDriverIndex = 0;
    int systemOutputDriverIndex = 0;
    const char **systemInputDriverNames;
    const char **systemOutputDriverNames;

    [inputDriverNames release];
    inputDriverNames = [[NSMutableArray array] retain];
    // Use the cross-platform means to obtain the available input drivers.
    systemInputDriverNames = MKMDGetAvailableDrivers(YES, &systemDefaultDriverNum);
    for(systemInputDriverIndex = 0; systemInputDriverNames[systemInputDriverIndex] != NULL; systemInputDriverIndex++) {
        [inputDriverNames addObject: [NSString stringWithUTF8String: systemInputDriverNames[systemInputDriverIndex]]];
	// NSLog(@"getAllAvailableMidiDevices input[%d] = %s\n", systemInputDriverIndex, systemInputDriverNames[systemInputDriverIndex]);
    }
    
    [outputDriverNames release];
    outputDriverNames = [[NSMutableArray array] retain];
    // Use the cross-platform means to obtain the available output drivers.
    systemOutputDriverNames = MKMDGetAvailableDrivers(NO, &systemDefaultDriverNum);
    for(systemOutputDriverIndex = 0; systemOutputDriverNames[systemOutputDriverIndex] != NULL; systemOutputDriverIndex++) {
        [outputDriverNames addObject: [NSString stringWithUTF8String: systemOutputDriverNames[systemOutputDriverIndex]]];
	// NSLog(@"getAllAvailableMidiDevices output[%d] = %s\n", systemOutputDriverIndex, systemOutputDriverNames[systemOutputDriverIndex]);
    }
    
    [bidirectionalDriverNames release];
    bidirectionalDriverNames = [NSMutableArray array];
    
    {
	int inputDriverIndex = 0;
	int outputDriverIndex = 0;
	
	// Ideally we should be eliminating chosen names from a copy of the outputDriverNames list to reduce the
	// search from O(n^2), but the lists are usually very small n typically < 8. 
	for(inputDriverIndex = 0; inputDriverIndex < [inputDriverNames count]; inputDriverIndex++) {
	    for(outputDriverIndex = 0; outputDriverIndex < [outputDriverNames count]; outputDriverIndex++) {
		NSString *inputDriverName = [inputDriverNames objectAtIndex: inputDriverIndex];
		
		if([inputDriverName isEqualToString: [outputDriverNames objectAtIndex: outputDriverIndex]]) {
		    [bidirectionalDriverNames addObject: inputDriverName];
		}
	    }
	}
    }
    
    if([bidirectionalDriverNames count] == 0) {
        bidirectionalDriverNames = nil; /* ensure we don't have stale pointers around */
        return NO;
    }
    // NSLog(@"input drivers %@ output drivers %@ bidirectional drivers %@\n", inputDriverNames, outputDriverNames, bidirectionalDriverNames);
    [bidirectionalDriverNames retain];
    // Return YES if there was at least one driver.
    return YES;
}

/* Assumes deviceName is valid string. Returns NO if no final number found or if 
* entire string is one number. Otherwise, returns number in unitNum and YES. */
static BOOL isSoftDevice(NSString *deviceName, int *unitNum)
{
    NSScanner *scanner = [NSScanner scannerWithString: deviceName];
    BOOL gotInt;
    NSRange softDevPrefixRange = {0, 4};
    
    [scanner scanUpToCharactersFromSet: [NSCharacterSet decimalDigitCharacterSet] intoString: NULL]; 
    gotInt = [scanner scanInt: unitNum];
    if(!gotInt || ![scanner isAtEnd] || [scanner scanLocation] == 0) {
	*unitNum = NO_UNIT;
        return NO;
    }
    else {
        return [deviceName compare: @"midi" 
			   options: NSAnchoredSearch
			     range: softDevPrefixRange] == NSOrderedSame;
    }
}

/* Maps a name of the form "midi0" to a name of the form "Mididriver2".
 * See above long explanation.
 */
+ (NSString *) mapSoftNameToDriverName: (NSString *) devName
{
    NSString *midiNumStrArr;
    unsigned int deviceIndex;
    NSString *defaultsValue;
    int deviceNumber = 0;
    BOOL isSoft;
    NSMutableArray *unionOfDrivers = [NSMutableArray arrayWithCapacity: [inputDriverNames count] + [outputDriverNames count]];

    // assigns the separate lists of driver names for input, output and bidirectional devices.
    if(![[self class] getAllAvailableMidiDevices])
        return nil;
    if(devName == nil || [devName length] == 0)
	return nil;
    // devName can be of the soft form "midi0", or the hard driver name "Mididriver0" or "SB Live! MIDI Out 1"
    if (isSoftDevice(devName, &deviceNumber)) {
        midiNumStrArr = [NSString stringWithFormat: @"MKMIDI%d", deviceNumber];

        // The owner will be whatever application links against this framework. 
        // This is what we want to allow for different applications to use different MIDI
        // devices if necessary.
        defaultsValue = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey: midiNumStrArr];
	if ([defaultsValue length]) {
            isSoft = isSoftDevice(defaultsValue, &deviceNumber);
	}
	else if (deviceNumber == 0) { 
            // Use the system default MIDI driver for midi0, not necessarily the first entry.
            // TODO this should probably be changed to allow "midiDefault" as a device name,
            // or consign midi0 to be the default, midi1 as [midiDriverNames objectAtIndex: 0], etc.
            return [bidirectionalDriverNames objectAtIndex: systemDefaultDriverNum];
	}
	return [bidirectionalDriverNames objectAtIndex: deviceNumber];
    }
    // Here we assume if we didn't have a soft device name, we are referring to a described device.
    // Ensure the driver was on the legitimate list, which we form by a redundant union of input and output devices.
    // Note we don't check if the direction is being used correctly.
    [unionOfDrivers addObjectsFromArray: inputDriverNames];
    [unionOfDrivers addObjectsFromArray: outputDriverNames];
    for (deviceIndex = 0; deviceIndex < [unionOfDrivers count]; deviceIndex++) {
        if ([devName isEqualToString: [unionOfDrivers objectAtIndex: deviceIndex]]) {
	    return devName;
	}
    }
    return nil;
}

// Returns autoreleased copies of all available input driver names as an NSArray
+ (NSArray *) getDriverNamesForInput
{
    [[self class] getAllAvailableMidiDevices];
    return [[inputDriverNames copy] autorelease];
}

// Returns autoreleased copies of all available output driver names as an NSArray
+ (NSArray *) getDriverNamesForOutput
{
    [[self class] getAllAvailableMidiDevices];
    return [[outputDriverNames copy] autorelease];
}

// Just return the bidirectional drivers for applications which only want those drivers (ports) which are both
// input and output.
+ (NSArray *) getDriverNames
{
    [[self class] getAllAvailableMidiDevices];
    return [[bidirectionalDriverNames copy] autorelease];
}

- (NSString *) driverName 
{
    return [[midiDevName copy] autorelease];
}

- (NSString *) description
{
    return [NSString stringWithFormat: @"%@ %s %@, unit %d, on host %@", [super description],
      ioMode == MKMidiInputOnly ? "Input from" : ioMode == MKMidiOutputOnly ? "Output to" : "I/O from/to",
	midiDevName, ioMode == MKMidiInputOnly ? inputUnit : outputUnit, hostname];
}

// Here we initialize our class variables.
+ (void) initialize
{
    NSDictionary *MKMIDIDefaults;

    if (self != [MKMidi class])
        return;

    openDrivers = [[NSMutableDictionary dictionary] retain];
    MKMIDIDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
        @"", @"MKMIDI0",
        @"", @"MKMIDI1",
        @"", @"MKMIDI2",
        @"", @"MKMIDI3",
        @"", @"MKMIDI4",
        @"", @"MKMIDI5",
        @"", @"MKMIDI6",
        @"", @"MKMIDI7",
        @"", @"MKMIDI8",
        @"", @"MKMIDI9",
        @"", @"MKMIDI10",
        @"", @"MKMIDI11",
        @"", @"MKMIDI12",
        @"", @"MKMIDI13",
        @"", @"MKMIDI14",
        @"", @"MKMIDI15",
       NULL, NULL];
    // insert these in the temporary defaults that are searched last.
    [[NSUserDefaults standardUserDefaults] registerDefaults: MKMIDIDefaults];  
}

// This is where all the initialisation is performed.
- initOnDevice: (NSString *) devName hostName: (NSString *) hostName
{
    self = [super init];
    if(self != nil) {
	MKMidi *obj;
	NSString *hostAndDevName;
	int notePortIndex;
	NSString *driverName = [[self class] mapSoftNameToDriverName: devName];
	
	if (driverName == nil)
	    return nil;
	devName = driverName;
#if !m68k
	hostName = @""; /* Only on local host, see extensive comment above */
#endif
	hostAndDevName = [hostName stringByAppendingString: devName];
	if ((obj = [openDrivers objectForKey: hostAndDevName]) == nil) {         // Doesn't already exist
	    [self getTimeInfoFromHost: hostName];
	    [openDrivers setObject: self forKey: hostAndDevName]; 
	}
	// even if the device is in the openDrivers, we still need to set the device and host name
	hostname = [hostName retain];
	midiDevName = [devName retain];
	
	if (noteSenders != nil) /* Already initialized */
	    return nil;
	outputIsTimed = YES;               /* Default is outputIsTimed */
	noteSenders = [NSMutableArray arrayWithCapacity: _MK_MIDINOTEPORTS];
	[noteSenders retain];
	noteReceivers = [NSMutableArray arrayWithCapacity: _MK_MIDINOTEPORTS];
	[noteReceivers retain];
	for (notePortIndex = 0; notePortIndex < _MK_MIDINOTEPORTS; notePortIndex++) {
	    MKNoteSender *aNoteSender = [MKNoteSender new];
	    MKNoteReceiver *aNoteReceiver = [MKNoteReceiver new];
	    
	    [noteReceivers addObject: aNoteReceiver];
	    [aNoteReceiver _setOwner: self];
	    [aNoteReceiver _setData: [NSNumber numberWithInt: notePortIndex]]; // Encode the note channel.

	    [noteSenders addObject: aNoteSender];
	    [aNoteSender _setPerformer: self];
	    [aNoteReceiver release];
	    [aNoteSender release]; /*sb: retains are held in arrays */
	}
	useInputTimeStamps = YES;
	timeOffset = 0;
	systemIgnoreBits = (IGNORE_ACTIVE |
			    IGNORE_CLOCK |
			    IGNORE_START |
			    IGNORE_CONTINUE |
			    IGNORE_STOP);
	deviceStatus = MK_devClosed;
	// TODO Maybe we don't want this here, in case we ever want to use MKMidi without MKNotes.
	_MKCheckInit(); 
	_MKClassOrchestra(); /* Force find-class here */
	ioMode = MKMidiInputOutput;
	displayReceivedMIDI = [[NSUserDefaults standardUserDefaults] boolForKey: @"MKDisplayReceivedMIDI"];
    }
    return self;
}

- initOnDevice: (NSString *) devName
{
    return [self initOnDevice: devName hostName: @""];
}

- init
{
    return [self initOnDevice: DEFAULT_SOFT_NAME];
}

+ midiOnDevice: (NSString *) devName host: (NSString *) hostName
{
    return [[[MKMidi alloc] initOnDevice: devName hostName: hostName] autorelease];
}

+ midiOnDevice: (NSString *) devName
{
    return [[[MKMidi alloc] initOnDevice: devName] autorelease];
}

+ midi
{
    return [self midiOnDevice: DEFAULT_SOFT_NAME];
}

- copyWithZone: (NSZone *) zone
  /* Overridden to return self. */
{
    return self;
}

/* Overridden to return self. */
- copy
{
    return self;
}

/* Aborts and frees the receiver. */
- (void) dealloc
{    
    [self abort];
    if ([self unitHasMTC]) 
        [synchConductor _setMTCSynch: nil];
    [self _setSynchConductor: nil];
    // Debugging:
#if 0
    NSLog(@"disconnecting noteReceivers %@\n", noteReceivers);
    id firstNoteReceiver = [noteReceivers objectAtIndex: 0];
    NSLog(@"retain count of first noteReceiver %p is %d\n", firstNoteReceiver, [firstNoteReceiver retainCount]);
#endif
    [noteReceivers makeObjectsPerformSelector: @selector(disconnect)];
    
#if 0
    NSLog(@"noteSenders remaining after disconnecting noteReceivers %@\n", noteSenders);
    MKNoteSender *firstNoteSender = [noteSenders objectAtIndex: 0];
    id firstNoteSendersReceiver = [firstNoteSender->noteReceivers objectAtIndex: 0];
    NSLog(@"retain count of first firstNoteSendersReceiver %@ is %d\n", firstNoteSendersReceiver, [firstNoteSendersReceiver retainCount]);
#endif
    [noteSenders makeObjectsPerformSelector: @selector(disconnectAllReceivers)];
    
    // Now we can release in the usual fashion.
    // NSLog(@"releasing noteReceivers and noteSenders\n");
    [noteReceivers release];
    noteReceivers = nil;
    [noteSenders release];
    noteSenders = nil;
    [super dealloc];
}
/* Control of device */

/* Returns MKDeviceStatus of receiver. */
- (MKDeviceStatus) deviceStatus
{
    return deviceStatus;
}

// After opening the MIDI device, assigns the MIDI parser system ignores, and output structure.
- openMidi
{
    if ([self openMidiDevice] != MKMD_SUCCESS)
        return nil;
    if (INPUTENABLED(ioMode)) {
        if (!(_pIn = (void *)_MKInitMidiIn()))
            return nil;
        else
            setMidiSysIgnore(self, systemIgnoreBits);
    }
    if (OUTPUTENABLED(ioMode)) {
	if (!(_pOut = (void *) _MKInitMidiOut()))
            return nil;
	else {
	    _MKMidiOutStruct *p = _pOut;
	    p->_owner = self;
	    p->_putSysMidi = putMidi;
	    p->_putChanMidi = putMidi;
	    p->_putSysExcl = putSysExcl;
	    p->_sendBufferedData = sendBufferedData;
	}
    }
    resetAndStopMidiClock(self);
    deviceStatus = MK_devOpen;
    return self;
}

- allNotesOff
   /* This is a conservative version of allNotesOff.  It only sends
    * noteOffs for notes if those notes are sounding.
    * The notes are sent immediately (but will be
    * queued behind any notes that have already been queued up).
    */
{
    NSMutableArray *aList;
    int i, cnt, j;
    
    if (!MIDIOUTPTR(self) || deviceStatus != MK_devRunning)
	return nil;
    MKMDFlushQueue((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], outputUnit);
    /* Not MKMDClearQueue, which can leave MIDI devices confused. */
    for (i = 1; i <= MIDI_NUMCHANS; i++) {
	aList = _MKGetNoteOns(MIDIOUTPTR(self), i);
	for (j = 0, cnt = [aList count]; j < cnt; j++)
            _MKWriteMidiOut([aList objectAtIndex: j], 0, i, MIDIOUTPTR(self), [self channelNoteReceiver: i]);
        MKMDFlushQueue((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], outputUnit);
	[aList removeAllObjects];
	[aList release];
    }
    awaitMidiOutDone(self, 1000); /* Timeout to work around driver (?) bug */
    return self;
}

int _MKAllNotesOffPause = 500; /* mSec between MIDI channel blasts 
				* This is a temporary hack and should
				* not be depended on!  It may change in 
				* the future.
				*/

- allNotesOffBlast
    /* If object is open for output, sends noteOff on every keyNum/channel.
       Note that this object assumes we're NOT encoding running status.
       (Currently, it is, indeed, the case that we're not encoding
       running status.) */
{
    MKMDRawEvent tmpMidiBuf[257];                     /* 1 for "noteOff", 256 for keyNum/chan */
    MKMDRawEvent *tmpBufPtr = &(tmpMidiBuf[1]);
    unsigned char chan;
    int i, r;
    if (deviceStatus == MK_devClosed || !OUTPUTENABLED(ioMode))
	return nil;
    for (i = 0; i < 128; i++) {
	tmpBufPtr->time = 0; 
	tmpBufPtr++->byte = i;   /* Keynum */
	tmpBufPtr->time = 0; 
	tmpBufPtr++->byte = 0;   /* Velocity */
    }
    /* FIXME Need to slow this down to prevent sound-out underrun during
     * barrage of outgoing MIDI data and so that external synthesizers have
     * time to respond.  Need to insert rests between channel resets. 
     */
    MKMDFlushQueue((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], outputUnit);
    /* Not ClearQueue, which can leave MIDI devices confused. */
    for (i = 0; i < 16; i++) {       
	int j, k;
	
	chan = i;
	tmpMidiBuf[0].time = 0;
	tmpMidiBuf[0].byte = MIDI_NOTEOFF | chan;
	for (j = 0; j < 257; j += MKMD_MAX_EVENT) {
	    k = 257 - j;
	    for (; ;) {
		r = MKMDSendData((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], outputUnit, &(tmpMidiBuf[j]), MIN(MKMD_MAX_EVENT, k));
	        if (r != MKMD_ERROR_QUEUE_FULL)
		    break;
		/* MIDI goes at a rate of a byte every 1/3 ms */
                [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow: (k / 3) / 1000.0]];
	    }
	    MKMDFlushQueue((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], outputUnit);
	    /* Slow it down so synths don't freak out */
            [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow: (_MKAllNotesOffPause) / 1000.0]];
	}
	MKMDFlushQueue((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], outputUnit);
	if (r != MKMD_SUCCESS) {
	    MKErrorCode(MK_machErr, OUTPUT_ERROR, midiDriverErrorString(r), @"allNotesOffBlast");
	    return nil;
	}
    }
    awaitMidiOutDone(self, 5000);
    return self;
}

- (void) listenToMIDI: (BOOL) receiveOnRecvPort
{
    MKMDReturn r;
    
    r = MKMDRequestData((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort], inputUnit,
                        (MKMDReplyPort) (receiveOnRecvPort) ? [recvPort machPort] : MKMD_PORT_NULL);
    if (r != MKMD_SUCCESS) 
	MKErrorCode(MK_machErr, INPUT_ERROR, midiDriverErrorString(r), @"listenToMIDI");
}

- (void) cancelQueueReq
{
    MKMDReturn r;
    r = MKMDRequestQueueNotification((MKMDPort) [devicePort machPort], (MKMDOwnerPort) [ownerPort machPort],
                                     outputUnit, (MKMDReplyPort) MKMD_PORT_NULL, 0);
    if (r != MKMD_SUCCESS) 
	MKErrorCode(MK_machErr, INPUT_ERROR, midiDriverErrorString(r), @"cancelQueueReq");
}

- openIfNecessary: (enum MKMidiDirection) direction
{
    ioMode = direction;
    switch (deviceStatus) {
    case MK_devClosed: /* Need to open it */
	return [self openMidi];
    case MK_devOpen:
	break;
    case MK_devRunning:
	if (INPUTENABLED(ioMode)) 
	    [self listenToMIDI: NO];
	if (OUTPUTENABLED(ioMode)) 
	    [self cancelQueueReq];
	/* no break here */
    case MK_devStopped:
	if (OUTPUTENABLED(ioMode))
            emptyMidi(self);
	resetAndStopMidiClock(self);
	deviceStatus = MK_devOpen;
	break;
    default:
	break;
    }
    return self;
}

- openOutputOnly
  /* Same as open but does not enable output. */
{
    if ((deviceStatus != MK_devClosed) && (ioMode != MKMidiOutputOnly))
        [self close];
    return [self openIfNecessary: MKMidiOutputOnly];
}

- openInputOnly
{
    if ((deviceStatus != MK_devClosed) && (ioMode != MKMidiInputOnly))
        [self close];
    return [self openIfNecessary: MKMidiInputOnly];
}

- open
  /* Opens device if not already open.
     If already open, flushes output queue. 
     Sets deviceStatus to MK_devOpen. 
     Returns nil if failure.
     */
{
    if ((deviceStatus != MK_devClosed) && (ioMode != MKMidiInputOutput))
        [self close];
    return [self openIfNecessary: MKMidiInputOutput];
}

- (double) localDeltaT
{
    return localDeltaT;
}

- setLocalDeltaT: (double) value
{
    localDeltaT = value;
    return self;
}

- run
{
    switch (deviceStatus) {
    case MK_devClosed:
	if (![self openMidi])
            return nil;
	/* no break here */
    case MK_devOpen:
/*	doDeltaT(self);  Needed if we'd ever use relative time to the driver */
	timeOffset = MKGetTime(); /* This is needed by MidiOut. */
	/* no break here */
    case MK_devStopped:
	if (INPUTENABLED(ioMode)) 
            [self listenToMIDI: YES];
	resumeMidiClock(self);
	deviceStatus = MK_devRunning;
    default:
	break;
    }
    return self;
}

- stop
{
    switch (deviceStatus) {
    case MK_devClosed:
	return [self open];
    case MK_devOpen:
    case MK_devStopped:
	return self;
    case MK_devRunning:
	stopMidiClock(self);
	if (INPUTENABLED(ioMode)) 
	    [self listenToMIDI: NO];
	if (OUTPUTENABLED(ioMode)) 
	    [self cancelQueueReq];
	deviceStatus = MK_devStopped;
    default:
	break;
    }
    return self;
}

- abort
{
    switch (deviceStatus) {
      case MK_devClosed:
	break;
      case MK_devRunning:
	if (INPUTENABLED(ioMode)) 
	    [self listenToMIDI: NO];
	if (OUTPUTENABLED(ioMode)) 
	    [self cancelQueueReq];
	/* No break here */
      case MK_devStopped:
      case MK_devOpen:
	if (OUTPUTENABLED(ioMode)) {
	    emptyMidi(self);
	}
	_pIn = (void *)_MKFinishMidiIn(MIDIINPTR(self));
	incomingDataCount = 0;
	_pOut = (void *)_MKFinishMidiOut(MIDIOUTPTR(self));
	[self closeMidiDevice];
	deviceStatus = MK_devClosed;
    }
    return self;
}

/* Need to ask for a message when queue is empty and wait for that message. */
- (void) close
{
    switch (deviceStatus) {
    case MK_devClosed:
	break;
    case MK_devRunning:
	if (INPUTENABLED(ioMode)) 
	    [self listenToMIDI: NO];
	if (OUTPUTENABLED(ioMode)) 
	    [self cancelQueueReq];
	    /* No break here */
    case MK_devStopped:
    case MK_devOpen:
	if (INPUTENABLED(ioMode)) {
	    _pIn = (void *)_MKFinishMidiIn(MIDIINPTR(self));
	    incomingDataCount = 0;
	}
	if (OUTPUTENABLED(ioMode)) {
	    [self awaitQueueDrain];
	    emptyMidi(self);
	    _pOut = (void *)_MKFinishMidiOut(MIDIOUTPTR(self));
	}
	[self closeMidiDevice];
	deviceStatus = MK_devClosed;
    }
}

- awaitQueueDrain
{
    if (deviceStatus == MK_devRunning) 
        awaitMidiOutDone(self, MKMD_NO_TIMEOUT);
    return self;
}
/* output configuration */

- setOutputTimed: (BOOL) yesOrNo
/* Controls whether MIDI commands are sent timed or untimed. The default
   is timed. It is permitted to change
   from timed to untimed during a performance. */
{
    outputIsTimed = yesOrNo;
    return self;
}

- (BOOL) outputIsTimed
  /* Returns whether MIDI commands are sent timed. */
{
    return outputIsTimed;
}

/* Receiving notes */

- _realizeNote: (MKNote *) aNote fromNoteReceiver: (MKNoteReceiver *) aNoteReceiver
    /* Performs note by converting it to midi and emiting it. 
       Is careful about matching noteOns with noteOffs. For
       notes of type MK_noteDur, schedules up a message to
       self, implementing the noteOff. If the receiver is not in devRunning
       status, aNote is ignored. */
{
    double t;
    int chan;
    if ((!MIDIOUTPTR(self)) || (!aNote) || (deviceStatus != MK_devRunning))
        return nil;
    if (outputIsTimed) {
        if (self->synchConductor) {
	    t = ([self->synchConductor clockTime] - timeOffset + localDeltaT + mtcTimeOffset);
	    if (MKGetDeltaTMode() == MK_DELTAT_DEVICE_LAG) 
                t += MKGetDeltaT();
	}
	else 
            t = MKGetDeltaTTime() - timeOffset + localDeltaT;
    }
    else
        t = 0;
    chan = [[aNoteReceiver _getData] intValue];
    _MKWriteMidiOut(aNote, t, chan, MIDIOUTPTR(self), aNoteReceiver);
    return self;
}

/* Accessing MKNoteSenders and MKNoteReceivers */

- (MKNoteSender *) channelNoteSender: (unsigned) channel
  /* Returns the MKNoteSender corresponding to the specified channel or nil
     if none. If n is 0, returns the MKNoteSender used for MKNotes fasioned
     from midi channel mode and system messages. */
{ 
    return (channel > MIDI_NUMCHANS) ? nil : [noteSenders objectAtIndex: channel];
}

- (MKNoteReceiver *) channelNoteReceiver: (unsigned) channel
  /* Returns the NoteReceiver corresponding to the specified channel or nil
     if none. If n is 0, returns the NoteReceiver used for MKNotes fasioned
     from midi channel mode and system messages. */
{ 
    return (channel > MIDI_NUMCHANS) ? nil : [noteReceivers objectAtIndex: channel];
}

- (NSArray *) noteSenders
  /* TYPE: Processing 
   * Returns a copy of the receiver's MKNoteSender List. 
   */
{
    return _MKLightweightArrayCopy(noteSenders);
    // return [_MKLightweightArrayCopy(noteSenders) autorelease];
}

- (MKNoteSender *) noteSender
  /* Returns the default MKNoteSender. This is used when you don't care
     which MKNoteSender you get. */
{
    return [noteSenders objectAtIndex: 0];
}

- (NSArray *) noteReceivers	
  /* TYPE: Querying; Returns a copy of the List of MKNoteReceivers.
   * Returns a copy of the List of MKNoteReceivers. The MKNoteReceivers themselves
   * are not copied.	
   */
{
    return _MKLightweightArrayCopy(noteReceivers);
    // return [_MKLightweightArrayCopy(noteReceivers) autorelease];
}

- (MKNoteReceiver *) noteReceiver
  /* TYPE: Querying; Returns the receiver's first MKNoteReceiver.
   * Returns the first MKNoteReceiver in the receiver's NSArray.
   * This is particularly useful for MKInstruments that have only
   * one MKNoteReceiver.
   */
{
    return [noteReceivers objectAtIndex: 0];
}

- setMergeInput: (BOOL) yesOrNo
{
    mergeInput = yesOrNo;
    return self;
}

// Download the patch numbers (NSNumbers) supplied in the NSArray as Downloadable Sounds (DLS).
// The patch format per integer follows the Microsoft convention:
// X0000000MMMMMMM0LLLLLLL0PPPPPPP
// X bit 31     = Patch is a DrumKit
// M bits 24-16 = MSB Bank Select(cc=0)
// L bits 15-8  = LSB bank select(cc=32)
// P bits 6-0   = Program Change number 
- (void) downloadDLS: (NSArray *) dlsPatches
{
    unsigned int *dlsPatchArray;
    unsigned int i;

    if (OUTPUTENABLED(ioMode) && deviceStatus != MK_devClosed) {
        _MK_MALLOC(dlsPatchArray, unsigned int, [dlsPatches count]);
        for(i = 0; i < [dlsPatches count]; i++)
            dlsPatchArray[i] = [[dlsPatches objectAtIndex: i] unsignedIntValue];
        MKMDDownloadDLSInstruments(dlsPatchArray, [dlsPatches count]);
        if (dlsPatchArray != NULL) {
          free(dlsPatchArray);
          dlsPatchArray = NULL;
        }
    }
}

#import "mtcMidi.m"

@end

#import "mtcMidiPrivate.m"

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us