File: seqread.c

package info (click to toggle)
audacity 2.0.6-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 80,076 kB
  • sloc: cpp: 192,859; ansic: 158,072; sh: 34,021; python: 24,248; lisp: 7,495; makefile: 3,667; xml: 573; perl: 31; sed: 16
file content (1890 lines) | stat: -rw-r--r-- 58,800 bytes parent folder | download | duplicates (9)
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
/****************************************************************************
               seqread.c -- Phase 1 of adagio compilation...

 this module parses adagio programs and builds a linked list structure
 consisting of notes and control changes in time order.

 Copyright 1989 Carnegie Mellon University
*****************************************************************************/

/*****************************************************************************
*       Change Log
*  Date     | Change
*-----------+-----------------------------------------------------------------
* 31-Dec-85 | Created changelog
* 31-Dec-85 | Add c:\ to include directives
* 31-Dec-85 | Added standard command scanner, metronome variable, need to add 
*           | cmdline_help procedure
* 31-Dec-85 | Call intr_init
* 31-Dec-85 | Set musictrace from command line via -trace
* 31-Dec-85 | Added -poll
*  1-Jan-86 | Put error messages out to stderr
*  1-Jan-86 | Set IsAT.     Can be later overridden by -at and -xt switches,
*           | currently only used for diagnostics (may be needed for
*           | compatibles, who knows?  In which case remove the tests which
*           | confirm the type of processor)
*  1-Jan-86 | <rgd/jmn> Removed dur-adjusted message
*  1-Jan-86 | Added miditrace
* 18-Jan-86 | Shortened durations by 1/200 s to avoid roundoff problems --
*           | see buildnote for details.
*  3-Mar-86 | Allow octave and accidentals in either order after pitch name.
*           | Default octave is now one that gets nearest previous pitch,
*           |  the tritone (half an octave) interval is descending by default.
*           | Special commands handled by table search, !Rate command added
*           |  to scale all times by a percentage (50 = half speed).
*  9-Mar-86 | Use space to limit amount of storage allocation.    Otherwise
*           |    exhausting storage in phase1 caused phase2 to fail.
* 12-Mar-86 | Broke off command line parser into adagio.c, only parser remains
* 24-Mar-86 | Changed representation from note_struct to event_struct
*           | Parse M, N, O, X, and Y as control change commands
* 23-May-86 | Added , and ; syntax: "," means "N0\n", ";" means "\n"
* 16-Jul-86 | modify to only call toupper/lower with upper/lower case as
*           |  parameter to be compatible with standard C functions
*  7-Aug-86 | fixed bug with default pitches and rests
*  5-Jul-87 | F.H: Introduced new memory handling from Mac version.
*           |    Changed:    init()
*           |       ins_event()
*           |       ins_ctrl()
*           |       ins_note()
*           |    Deleted:    reverse()
*           |       nalloc()
*           |    Introduced:    event_alloc()
*           |       phase1_FreeMem()
*           |       system.h & system.c dependencies
* 10-Feb-88 | fixed parseend to accept blanks and tabs,
*           | fixed rate scaling of durations
* 11-Jun-88 | commented out gprintf of \n to ERROR after parsing finished.
* 13-Oct-88 | JCD : exclusive AMIGA version.
* 13-Apr-89 | JCD : New portable version.
* 31-Jan-90 | GWL : Cleaned up for LATTICE
* 30-Jun-90 | RBD : further changes
*  2-Apr-91 | JDW : further changes
* 30-Jun-91 | RBD : parse '+' and '/' in durations, * after space is comment
* 28-Apr-03 |  DM : changes for portability
*****************************************************************************/

#include "switches.h"

#include <stdio.h>
#include <string.h>

#include "cext.h"
#include "cmdline.h"
#include "midifns.h" /* to get time_type */
#include "timebase.h"
#include "moxc.h"    /* to get debug declared */
#include "seq.h"
#include "seqread.h"
#include "userio.h"
/* ctype.h used to be included only by UNIX and AMIGA,
   surely everyone wants this? */
#include "ctype.h"

#ifndef toupper
/* we're already taking precautions, so inline version of toupper is ok: */
#define toupper(c) ((c)-'a'+'A')
/* CAUTION: AZTEC V5.0 defines an inline version of toupper called _toupper,
   but they got it wrong!
 */
#endif

/* cmtcmd.h references amiga message ports */
#ifdef AMIGA
#ifdef LATTICE
#include "amiga.h"
#endif
#include "exec/exec.h"
#endif
#include "cmtcmd.h"

/* public stuff */
extern long space;    /* remaining free bytes */
extern int abort_flag;

/****************************************************************************
 The following are used to simulate fixed point with the radix point
 8 bits from the right:
****************************************************************************/

#define precise(x) (((time_type) x) << 8)
#define seqround(x) ((((time_type) x) + 128) >> 8)
#define trunc(x) (((time_type) x) >> 8)

#define nullstring(s) (s[0] == EOS)


/****************************************************************************
* Routines local to this module:
****************************************************************************/
private void            do_a_rest();
private time_type       doabsdur();
private int             doabspitch();
private void            doclock();
private void            docomment();
private void            doctrl();
private void            dodef();
private time_type       dodur();
private void            doerror();
private int             doloud();
void            domacro();
private void            donextdur();
private int             dopitch();
private void            doprogram();
private void            dorate();
private void            doset();
private void            dospecial();
private time_type       dosymdur();
private void            dotempo();
private void            dotime();
private void            dovoice();
private void            fferror();
private void            init();
private int             issymbol();
private void            marker();
private void            parseend();
private void            parsefield();
private boolean         parsenote();
private boolean         parseparm();
private int             scan();
private int             scan1();
private long            scanint();
private void            scansymb();
private long            scansgnint();

/****************************************************************************
* data structures for parser lookup tables
****************************************************************************/

struct durt {    /* duration translation table */
    char symbol;
    time_type value;
};

#define durtable_len 7
struct durt durtable[durtable_len] = {
    {'W', 4800L},
    {'H', 2400L},
    {'Q', 1200L},
    {'I', 600L},
    {'S', 300L},
    {'%', 150L},
    {'^', 75L}
};

struct loudt {    /* loudness translation table */
    char symbol[4];
    int value;
};

struct loudt loudtable[] = {
    {"PPP", 20},
    {"PP\0", 26},
    {"P\0\0", 34},
    {"MP\0", 44},
    {"MF\0", 58},
    {"F\0\0", 75},
    {"FF\0", 98},
    {"FFF", 127}
};

char too_many_error[] = "Too many parameters";

private char *ssymbols[] = {"TEMPO", "RATE", "CSEC", "MSEC", 
                            "SETI", "SETV", "CALL", "RAMP",
                            "CLOCK", "DEF", "END"};

#define sym_tempo 0
#define sym_rate 1
#define sym_csec 2
#define sym_msec 3
#define sym_seti 4
#define sym_setv 5
#define sym_call 6
#define sym_ramp 7
#define sym_clock 8
#define sym_def 9
#define sym_end 10

/* number of symbols */
#define sym_n 11

#define linesize 100
private char line[linesize];    /* the input line */
private char token[linesize];    /* a token scanned from the input line */

private boolean pitch_flag;    /* set when a pitch is indicated */
/* (if controls changes are given, only allocate a note event if
     *  a pitch was specified -- i.e. when pitch_flag is set)
     */
private boolean rest_flag;    /* set when a rest (R) is found */
/* this flag is NOT inherited by the next line */

private boolean symbolic_dur_flag;
/* TRUE if last dur was not absolute
         * (if this is set, then the default duration is changed
         *  accordingly when the tempo is changed.)
         */


#define nctrl 8

private boolean ctrlflag[nctrl];
/* TRUE if control change was present
         * ctrlflag[0] TRUE if ANY control change
         * was present
         */
private int ctrlval[nctrl];
/* the new value of the control */
#define nmacroctrl 10
short macctrlx;                 /* index into the following: */
short macctrlnum[nmacroctrl];   /* macro ctrl number, e.g. for ~4(67), or
                                 * number of parameters for a symbolic macro */
short macctrlparmx[nmacroctrl]; /* ctrl value for ctrl change, or index of
                                 * parameters for symbolic macro */
short macctrlparms[nmacroctrl*nmacroparms]; /* parameters for symbolic macros */
short macctrlnextparm;
def_type macctrldef[nmacroctrl]; /* definition for symbolic macro */

private time_type time_scale; /* 1000 if centisec, 100 if millisec */
/* note: user_specified_time * (time_scale / rate) = millisec */



/****************************************************************************
*
*    variables private to this module
*
****************************************************************************/

private boolean end_flag = FALSE;    /* set "true" when "!END" is seen */

/****************************************************************************
*               state variables
* Because each line of an Adagio score inherits properties from the previous
* line, it makes sense to implement the parser as a collection of routines
* that make small changes to some global state.     For example, pitch is a
* global variable.  When the field G4 is encountered, the dopitch routine
* assigns the pitch number for G4 to the variable pitch.  After all fields
* are processed, these variables describe the current note and contain the
* default parameters for the next note as well.
*
* Global variables that are used in this way by the parsing rountines are:
****************************************************************************/
private int
linex,    /* index of the next character to be scanned */
lineno,    /* current line number */
fieldx,    /* index of the current character within a field */
pitch,    /* pitch of note */
loud,    /* loudness of note */
voice,    /* voice (midi channel) of note */
artic;  /* articulation (a percentage of duration) */

private boolean ndurp;  /* set when a next (N) is indicated */
/* (next time defaults to the current time plus duration unless
     *  overridden by a next (N) command whose presence is signalled
     *  by ndurp.)
     */

private time_type
thetime,    /* the starting time of the note */
rate,    /* time rate -- scales time and duration, default = 100 */
ntime,    /* the starting time of the next note */
dur,    /* the duration of the note */
tempo,    /* the current tempo */
start,    /* the reference time (time of last !tempo or !rate cmd) */
ticksize; /* set by !clock command, zero for no clock */

private int pitchtable[7] = { 
    69, 71, 60, 62, 64, 65, 67 };

extern char score_na[name_length];

private seq_type the_score;  /* this is the score we are parsing */


/* def_append -- append a byte to the current definition */
/*
 * The def data structure:
 *     [code][offset][code][offset]...[0][length][data][data][data]...
 * where code is 1:nmacroparms for %n,
 *               nmacroparms+1 for %v,
 *               nmacroparms+2:nmacroparms*2+1 for ^n
 * and offset is the byte offset (from the offset byte) to the data
 *      where the parameter should be substituted
 * and length is the number of data bytes
 */
boolean def_append(def, nparms, data)
  unsigned char def[];
  int nparms;
  int data;
{
    int base = (nparms << 1) + 1;       /* this byte is the length */
    /* first parameter has to be able to reference last byte: */
    if ((def[base])++ >= (254 - (nparms << 1))) {
        fferror("Data too long");
        return FALSE;
    }
    def[base + def[base]] = data;
    return TRUE;
}


def_type def_lookup(symbol)
  char *symbol;
{
    def_type defn = seq_dictionary(the_score);
    while (defn) {
        if (strcmp(defn->symbol, symbol) == 0) {
            return defn;
        }
        defn = defn->next;
    }
    return NULL;
}


void def_parm(def, nparms, code)
  unsigned char def[];
  int nparms;
  int code;
{
    int i, j;
    /* in order to insert a 2-byte parameter descriptor, the offsets from
     * previous descriptors (that precede the data) need to be increased by 2:
     */
    for (i = 1; i < (nparms << 1); i += 2) {
        def[i] += 2;
    }
    /* now i is index of length; work backwards from the last byte, moving
     * everything up by 2 bytes to make room for the new descriptor:
     */
    for (j = i + def[i] + 2; j > i; j--) {
        def[j] = def[j - 2];
    }
    /* now i is index of offset; insert the descriptor code (first byte)
     * and the offset to the parameter location in the message (second byte)
     */
    def[i - 1] = code;
    def[i] = def[i + 2] + 2;
}

/****************************************************************************
*               do_a_rest
* Effect: parses a rest (R) command
****************************************************************************/

private void do_a_rest()
{
    if (token[fieldx])
        fferror("Nothing expected after rest");
    rest_flag = TRUE;
}

/****************************************************************************
*               doabsdur
* Effect: parses an absolute dur (U) command
****************************************************************************/

private time_type doabsdur()
{
    time_type result=1000L;
    register char c;
    if (isdigit(token[fieldx])) {
        result = precise(scanint());
        /* allow comma or paren for use in parameter lists */
        if ((c = token[fieldx]) && (c != ',') && (c != ')') && (c != '+')) {
            fferror("U must be followed by digits only");
        }
        if (time_scale == 1000) result *= 10; /* convert to ms */
    } else fferror("No digit after U");
    return result;
}

/****************************************************************************
*               doabspitch
* Effect: parses an absolute pitch (P) command
****************************************************************************/

private int doabspitch()
{
    int result = 60;
    int startx = fieldx;
    register char c;
    int savex;
    if (isdigit (token[fieldx])) {
        result = (int) scanint();
        /* allow comma or paren for abspitch in parameter */
        if ((c = token[fieldx]) && c != ',' && c != ')')
            fferror("P must be followed by digits only");
        else if (result < minpitch) {
            savex = fieldx;
            fieldx = startx;
            fferror("Minimum pitch of 0 will be used");
            result = minpitch;
            fieldx = savex;
        } else if (result > maxpitch) {
            savex = fieldx;
            fieldx = startx;
            fferror("Maximum pitch of 127 will be used");
            result = maxpitch;
            fieldx = savex;
        }
    } else fferror("No digits after P");
    return result;
}


/* doartic -- compute an articulation factor */
/*
  NOTE: artic is a percentage that scales the duration
  of notes but not the time to the next note onset. It
  is applied to the final computed duration after all
  other scaling is applied.
 */
private void doartic()
{
    if (isdigit(token[fieldx])) {
        artic = (int) scanint();
        if (token[fieldx])
            fferror("Only digits were expected here");
    } else fferror("No digits after /");
}


/* docall -- parse a call in the form !CALL fn(p1,p2,p3) */
/**/
private void docall()
{
    boolean error_flag = TRUE;
    ndurp = FALSE;

    linex += scan();

    if (token[0] == 0) fferror("Function name expected");
    else {
        char symbol[100];
        struct symb_descr *desc;
        long value[SEQ_MAX_PARMS];
        int i=0;

        scansymb(symbol);
        if (fieldx == 1) fferror("Routine name expected");
        else if (token[fieldx] != '(') fferror("Open paren expected");
        else {
            desc = &HASHENTRY(lookup(symbol));
            if (!desc->symb_type) {
                fieldx = 0;
                fferror("Function not defined");
            } else if (desc->symb_type != fn_symb_type) {
                fieldx = 0;
                gprintf(TRANS, "desc->symb_type is %d\n", desc->symb_type);
                fferror("This is not a function");
            } else {
                error_flag = FALSE;
                fieldx++;       /* skip over paren */
                for (i = 0; i < SEQ_MAX_PARMS; i++) value[i] = 0;
                i = 0;
                /* note that no params "()" is legal */
                while (i < SEQ_MAX_PARMS && token[fieldx] != ')' && 
                       parseparm(&value[i])) {
                    i++;
                    if (token[fieldx] == ',') {
                        fieldx++;
                    } else if (token[fieldx] != ')') {
                        fferror("Unexpected character");
                        error_flag = TRUE;
                        break;
                    }
                }
                fieldx++;
                if (i > SEQ_MAX_PARMS) fferror("Too many parameters");
            }
            while (TRUE) {
                linex += scan();
                if (nullstring(token)) {
                    break;
                } 
                switch (token[0]) {
                  case 'T':
                    fieldx = 1;
                    dotime();
                    break;
                  case 'V':
                    fieldx = 1;
                    dovoice();
                    break;
                  case 'N':
                    fieldx = 1;
                    donextdur();
                    break;
                  default:
                    fferror("Unexpected character");
                }
            }
            if (!error_flag)
                insert_call(the_score, seqround(thetime), lineno, voice, 
                            desc->ptr.routine, value, i);
            /* advance the time only if an N field was given */
            if (ndurp) thetime += ntime;
        }
    }
}


/* doclock -- insert a clock command */
/*
 * derivation: if there is no previous clock running, then start the
 *     clock on time.  Otherwise, start the clock half a tick early.
 *     ticksize = (beattime / 24) = ((60sec/tempo)/24) =
 *      ((60000ms/tempo)/24) = (60000/24)/tempo = 2500/tempo
 */
private void doclock()
{
    int oldticksize = ticksize;
    ticksize = (2500L << 16) / tempo;
    insert_clock(the_score, seqround(thetime) - (oldticksize >> 17),
                 lineno, ticksize);
}


/****************************************************************************
*               docomment
* Effect: parses a comment (*) command
****************************************************************************/

private void docomment()
{
    line[linex] = '\n'; /* force end of line to skip comment line */
    line[linex+1] = EOS;
}

/****************************************************************************
*               doctrl
* Inputs:
*    n: control number
* Effect: parses a control (K, M, O, X, or Y) command
****************************************************************************/

private void doctrl(n)
int n;
{
    ctrlval[n] = (int) scanint();
    if (token[fieldx]) {
        fferror("Only digits expected here");
    } else {
        ctrlflag[n] = TRUE;
        ctrlflag[0] = TRUE;    /* ctrlflag[0] set if any flag is set */
    }
}


private void dodef()
{
    /* maximum def size is 256 + 9 parms * 2 + 2 = 276 */
    unsigned char def[280];
    char symbol[100];
    int nparms = 0;
    int nibcount = 0;
    int data = 0;
    register char c;

    linex += scan();

    if (!token[0]) fferror("Symbol expected");
    else {
        strcpy(symbol, token);
        def[0] = def[1] = 0;
        while (TRUE) {
            linex += scan1(&line[linex]);
            c = token[0];
            if (!c) {
                linex--;
                if (nibcount & 1) {
                    fferror("Expected pairs of hex digits: one missing");
                    return;
                }
                break;
            } else if (c == ' ' || c == '\t' || c == '\n') continue;
            else if (isdigit(c)) {
                data = (data << 4) + (c - '0');
                nibcount++;
                if (!(nibcount & 1)) {
                    if (!def_append(def, nparms, data))
                        return;
                    data = 0;
                }
            } else if ('A' <= c && c <= 'F') {
                data = (data << 4) + (c - 'A') + 10;
                nibcount++; 
                if (!(nibcount & 1)) {
                    if (!def_append(def, nparms, data))
                        return;
                    data = 0;
                }
            } else if (c == 'V') {
                data = data << 4;
                nibcount++;
                /* v without a leading nibble is equivalent to 0v: */
                if (nibcount & 1) nibcount++;
                if (!def_append(def, nparms, data))
                    return;
                def_parm(def, nparms++, nmacroparms+1);
            } else if (c == '%') {
                linex += scan1(&line[linex]);
                c = token[0];
                if (c < '1' || c > ('0' + nmacroparms)) {
                    fferror(parm_expected_error);
                    break;
                }
                if (!def_append(def, nparms, 0))
                    return;
                def_parm(def, nparms++, c - '0');               
            } else if (c == '^') {
                linex += scan1(&line[linex]);
                c = token[0];
                if (c < '1' || c > ('0' + nmacroparms)) {
                    fferror(parm_expected_error);
                    break;
                }
                if (!def_append(def, nparms, 0))
                    return;
                def_parm(def, nparms++, (c - '0') + nmacroparms + 1);
            } else {  /* something unexpected here -- just exit */
                linex--;
                fferror("Unexpected data");
                return;
            }
        }
        insert_def(the_score, symbol, def,
                   (nparms << 1) + def[(nparms << 1) + 1] + 2);
    }
}

/****************************************************************************
*               dodur
* Effect: parses a duration (sum of dosymdur and/or doabsdur)
* sets symbolic_dur_flag (according to the first addend in mixed arithmetic)
*
* Returns: duration in "precise" units
****************************************************************************/
private time_type dodur()
{
    time_type result = 0L;
    symbolic_dur_flag = TRUE;

    if (token[fieldx-1] == 'U') {
        result = doabsdur();
        symbolic_dur_flag = FALSE;
    } else result = dosymdur();
    while (token[fieldx] == '+') {
        fieldx += 2;
        if (token[fieldx-1] == 'U') result += doabsdur();
        else result += dosymdur();
    }
    return scale(result, 100L, rate);
}

/****************************************************************************
*               doerror
* Effect: parse an unrecognized field by reporting an error
****************************************************************************/

private void doerror()
{
    fieldx = 0;
    fferror("Bad field");
}

/****************************************************************************
*               doloud
* Effect: parse a loudness (L) command
****************************************************************************/

private int doloud()
{
    int i, j;
    int result;
    int oldfieldx = fieldx;
    int newfieldx;
    char symbol[100];

    if (!token[fieldx] || token[fieldx]==')' || token[fieldx]==',') {
        fferror("L must be followed by loudness indication");
        return 100;
    }
    if (isdigit(token[fieldx])) {
        result = (int) scanint();
        newfieldx = fieldx;
        if (token[fieldx] && token[fieldx]!=')' && token[fieldx]!=',')
            fferror("Digits expected after L");
        else if (result > 127) {
            fieldx = oldfieldx;
            fferror("Maximum loudness of 127 will be used");
            fieldx = newfieldx;
            result = 127;
        } else if (result == 0) {
            fieldx = oldfieldx;
            fferror("Minimum loudness of 1 will be used");
            fieldx = newfieldx;
            result = 1;
        }
        return result;
    }
    scansymb(symbol);
    newfieldx = fieldx;
    if ((i = strlen(symbol)) > 3 ) {    /* maximum is 3, e.g. "ppp" */
        fieldx = oldfieldx;
        fferror("Loudness field too long");
        fieldx = newfieldx;
        return 100;
    }
    symbol[i + 1] = '\0';   /* pad short symbols with 0    */
                            /* e.g. "p\0" -> "p\0\0"    */
    for (i = 0; i <= 7; i++) {    /* loop through possibilities    */
        for (j = 0; j <= 2; j++) {    /* test 3 characters    */
            if (symbol[j] != loudtable[i].symbol[j])
                break;
        }
        if (j == 3) {
            return loudtable[i].value;
        }
    }
    fieldx = oldfieldx;
    fferror("Bad loudness indication");
    fieldx = newfieldx;
    return 100;
}


void domacro()
{
    int control_num;
    int value;
    if (isdigit(token[1])) {
        control_num = (int) scanint();
        if (token[fieldx] == '(') {
            fieldx++;
            if (!isdigit(token[fieldx])) {
                fferror("Control value expected");
            } else {
                value = (int) scanint();
                if (token[fieldx] != ')') {
                    fferror("Missing close paren");
                } else {
                    fieldx++;
                    if (token[fieldx])
                        fferror("Nothing expected after paren");
                    else if (macctrlx < nmacroctrl - 1) {
                        macctrlnum[macctrlx] = control_num;
                        macctrlparmx[macctrlx] = value;
                        macctrldef[macctrlx] = NULL;
                        macctrlx++;
                    } else fferror("Too many controls");
                }
            }
        } else fferror("Missing paren");
    } else {
        def_type def;
        char symbol[100];
        scansymb(symbol);
        if (fieldx == 1) fferror("Macro name expected");
        else if (token[fieldx] != '(') fferror("Open paren expected");
        else {
            fieldx++;
            def = def_lookup(symbol);
            if (!def) {
                fieldx = 1;
                fferror("Undefined macro");
            } else {
                long val;
                macctrlnum[macctrlx] = 0;
                macctrlparmx[macctrlx] = macctrlnextparm;
                macctrldef[macctrlx] = def;
                while (token[fieldx] != ')' && parseparm(&val)) {
                    macctrlparms[macctrlnextparm++] = (short) val;
                    macctrlnum[macctrlx]++;
                    if (token[fieldx] == ',') {
                        fieldx++;
                    } else if (token[fieldx] != ')') {
                        fferror("Unexpected character");
                        break;
                    }
                }
                fieldx++;
                macctrlx++;
            }
        }
    }
}


/****************************************************************************
*               donextdur
* Effect: parse a next (N) command
* Implementation:
*    The syntax is N followed by a duration, so save dur and use dosymdur()
*    to parse the duration field.
*    The form N<digits> is parsed directly with scanint().
****************************************************************************/

private void donextdur()
{
    ndurp = TRUE;    /* flag that N was given */
    if (isdigit(token[fieldx])) {
        ntime = precise(scanint());
        ntime = scale(ntime, (ulong)time_scale, rate);
        if (token[fieldx])
            fferror("Only digits were expected here");
    } else {
        fieldx++;
        ntime = dodur();
    }
}

/****************************************************************************
*               dopitch
* Effect: parses a pitch command
****************************************************************************/

private int dopitch()
{
    int p, octave=0;
    int octflag = FALSE;    /* set if octave is specified */
    int oldfieldx = fieldx;

    p = pitchtable[token[fieldx-1]-'A'];
    while (TRUE) {
        if (token[fieldx] == 'S') {                /* sharp */
            p++;
            fieldx++;
        } 
        else if (token[fieldx] == 'N') {            /* skip */
            fieldx++;
        } 
        else if (token[fieldx] == 'F') {            /* flat */
            p--;
            fieldx++;
        } 
        else if (isdigit(token[fieldx]) && !octflag) {      /* octave */
            octave = (int) scanint();
            octflag = TRUE;
        } 
        else break;                /* none of the above */
    }
    if (octflag) p = (p-48) + 12 * octave;  /* adjust p to given octave */
    else {        /* adjust p to note nearest the default pitch */
        int octdiff = (p + 126 - pitch) / 12;
        p = p + 120 - (octdiff * 12);
    }
    if (p > maxpitch) {              /* pitch in range? */
        int newfield = fieldx;
        fieldx = oldfieldx;
        fferror("Pitch too high");
        fieldx = newfield;
        p = maxpitch;
    }
    /* We really should test for end-of-field, but we don't know if we're
       in a parameter list, so comma may or may not be legal */
    return p;
}

/****************************************************************************
*               doprogram
* Effect: parses a program change (Z) command
****************************************************************************/

private void doprogram()
{
    register int program = (int) scanint();
    ctrlflag[PROGRAM_CTRL] = ctrlflag[0] = TRUE;
    if (token[fieldx]) {
        fferror("Z must be followed by digits only");
    } else if (program < minprogram) {
        fieldx = 1;
        fferror("Minimum program of 1 will be used");
        program = minprogram;
    } else if (program > maxprogram) {
        fieldx = 1;
        fferror("Maximum program of 128 will be used");
        program = maxprogram;
    }
    ctrlval[PROGRAM_CTRL] = program - 1;
}


private void doramp()
{
    int values[2];
    time_type stepsize = 100L;  /* default 10 per second */
    int index = 0;
    ndurp = FALSE;
    values[0] = values[1] = 0;
    while (TRUE) {
        linex += scan();
        fieldx = 1;
        if (nullstring(token)) {
            break;
        } else if (index == 2) { /* must be stepsize in dur syntax */
            stepsize = dodur();
        } else {
            int ctrlx = 0;
            static int ctrl_map[] = { -BEND_CTRL, VOLUME, -TOUCH_CTRL, MODWHEEL };

            switch (token[0]) {
              case 'M': ctrlx++;        /* modwheel */
              case 'O': ctrlx++;        /* aftertouch */
              case 'X': ctrlx++;        /* volume */
              case 'Y':                 /* pitch bend */

                if (index < 2) {
                    macctrlnum[index] = ctrl_map[ctrlx];
                    macctrlparmx[index] = (int) scanint();
                    if (token[fieldx])
                        fferror("Only digits expected here");
                    macctrldef[index] = NULL;
                } else fferror("Unexpected control");
                break;
              case '~':
                if (index < 2) {
                    domacro();
                    if (token[fieldx]) fferror("Unexpected character");
                } else fferror("Unexpected control");
                break;
              case 'T':
                if (index < 2) fferror("Control expected");
                dotime();
                break;
              case 'V':
                if (index < 2) fferror("Control expected");
                dovoice();
                break;
              case 'N':
                if (index < 2) fferror("Control expected");
                donextdur();
                break;
              default:
                if (index < 2) fferror("Control expected");
                dur = dodur();
                break;
            }
            if (index == 1 && (macctrlnum[0] != macctrlnum[1] ||
                               macctrldef[0] != macctrldef[1])) {
                fferror("Controls do not match");
            }
        }
        index++;
    }
    if (index < 3) fferror("Expected 2 controls and step size");
    else {
        if (macctrldef[0]) {
            int i, j, n;
            n = 0;
            i = macctrlparmx[0];
            j = macctrlparmx[1];
            while (n < macctrlnum[0]) {
                if (macctrlparms[i] != macctrlparms[j]) break;
                n++; i++; j++;
            }
            if (n >= macctrlnum[0]) n = 0;
            /* Note: duration shortened to prevent overlap with next ramp */
            insert_deframp(the_score, seqround(thetime), lineno, voice,
                seqround(stepsize), trunc(dur) - 1, macctrldef[0], macctrlnum[0],
                macctrlparms + macctrlparmx[0], n, macctrlparms[j]);
        } else {
            /* Note: duration shortened to prevent overlap with next ramp */
            insert_ctrlramp(the_score, seqround(thetime), lineno, voice,
                seqround(stepsize), trunc(dur) - 1,
                macctrlnum[0], macctrlparmx[0], macctrlparmx[1]);
        }
    }
    /* advance the time only if an N field was given */
    if (ndurp) thetime += ntime;
    else thetime += dur;
}


/****************************************************************************
*               dorate
* Effect: parses a !rate command
****************************************************************************/

private void dorate()
{
    linex += scan();
    if (!token[0])
        fferror("rate number expected");
    else {
        long oldrate = rate;
        rate = (int) scanint();
        if (token[fieldx])
            fferror("Only digits expected here");
        if (rate == 0) {
            fieldx = 0;
            fferror("Rate 100 will be used here");
            rate = 100L;
        }
        start = thetime;
        /* adjust dur in case it is inherited by next note */
        dur = (dur * oldrate);
        dur = dur / rate;
    }
}


private void doset(vec_flag)
  boolean vec_flag;
{
    ndurp = FALSE;
    linex += scan();
    if (!token[0]) fferror("Variable name expected");
    else {
        struct symb_descr *desc = &HASHENTRY(lookup(token));
        if (!desc->symb_type) fferror("Called function not defined");
        else if (vec_flag && (desc->symb_type != vec_symb_type)) {
                fferror("This is not an array");
        } else if (!vec_flag && (desc->symb_type != var_symb_type)) {
                fferror("This is not a variable");
        } else {
            int numargs = 1 + vec_flag;
            int value[2];
            int i;
            int *address = desc->ptr.intptr;
            value[0] = value[1] = 0;
            i = 0;
            while (TRUE) {
                linex += scan();
                if (nullstring(token)) {
                    break;
                } else if (isdigit(token[0]) || token[0] == '-' ||
                           token[0] == '+') {
                    if (i < numargs) {
                        value[i++] = (int) scansgnint();
                        if (token[fieldx])
                            fferror("Only digits expected here");
                    } else fferror(too_many_error);
                } else {
                    switch (token[0]) {
                      case 'T':
                        fieldx = 1;
                        dotime();
                        break;
                      case 'V':
                        fieldx = 1;
                        dovoice();
                        break;
                      case 'N':
                        fieldx = 1;
                        donextdur();
                        break;
                      default:
                        fieldx++;
                        if (i < numargs) {
                            value[i++] = seqround(dodur());
                        } else fferror(too_many_error);
                        break;
                    }
                }
            }
            if (vec_flag && i != 2) fferror("No index given");
            if (vec_flag) {
                if (value[0] >= desc->size) {
                    fferror("Subscript out of bounds");
                    return;
                }
                /* reduce to the seti case: */
                address += value[0];    /* compute the vector address */
                value[0] = value[1];    /* set up value[] and i as if */
                i--;                    /* this were seti, not setv */
            }
            if (i != 1) fferror("No value given");
            insert_seti(the_score, seqround(thetime), lineno, voice,
                        address, value[0]);
            /* advance the time only if an N field was given */
            if (ndurp) thetime += ntime;
        }
    }
}

/****************************************************************************
*               dospecial
* Effect: parses special (those starting with "!") commands
****************************************************************************/

private void dospecial()
{
    switch (issymbol()) {
      case sym_tempo: 
        dotempo();
        break;
      case sym_rate: 
        dorate();
        break;
      case sym_csec:
        /* adjust dur for inheritance by next note */
        dur = (dur * 1000L) / time_scale;
        time_scale = 1000L;
        break;
      case sym_msec:
        dur = (dur * 100L) / time_scale;
        time_scale = 100L;
        break;
      case sym_seti:
        doset(FALSE);
        break;
      case sym_setv:
        doset(TRUE);
        break;
      case sym_call:
        docall();
        break;
      case sym_ramp:
        doramp();
        break;
      case sym_clock:
        doclock();
        break;
      case sym_def:
        dodef();
        break;
      case sym_end:
        end_flag = TRUE;
        break;
      default: 
        fferror("Special command expected");
    }
    parseend(); /* flush the rest of the line */
}

/****************************************************************************
*               dosymdur
* Effect: parses a duration (^, %, S, I, Q, H, or W) command
****************************************************************************/

private time_type dosymdur()
{
    int i, dotcnt = 0;
    long dotfactor;
    time_type result = 0;

    for (i = 0; i < durtable_len; i++) {
        if (durtable[i].symbol == token[fieldx-1]) {
            /* the shift right is because durs are stored doubled because
             *  otherwise a 64th note would have the value 75/2:  */
            result = precise(durtable[i].value) >> 1;
            break;
        }
    }
    if (i == durtable_len) {
        fieldx--;
        fferror("Duration expected: one of W, H, Q, I, S, %, or ^");
        return 0L;
    }
    while (token[fieldx]) {
        if (token[fieldx] == 'T') {     /* triplet notation */
            result = (result * 2) / 3;  /* lose a bit but avoid scale() */
            fieldx++;
        } 
        else if (token[fieldx] == '.') {    /* dotted notation */
            dotcnt++;
            fieldx++;
        } 
        else if (token[fieldx] == '/') {
            long divisor;
            fieldx++;
            divisor = scanint();
            if (divisor > 0) result = result / divisor;
            else fferror("non-zero integer expected");
        }
        else if (isdigit(token[fieldx])) {    /* numbers are multipliers */
            result = result * scanint();
        } 
        else break;
    }
    dotfactor = 1L;
    for (i=1; i<=dotcnt; i++)
        dotfactor = dotfactor * 2;
    result = (2 * result) - (result / dotfactor);

    return scale(result, 100L, tempo);    /* time in milliseconds */
}

/****************************************************************************
*               dotempo
* Effect: parses a !tempo command
****************************************************************************/

private void dotempo()
{
    linex += scan();
    if (!token[0])
        fferror("Tempo number expected");
    else {
        long oldtempo = tempo;
        tempo = scanint();
        if (token[fieldx])
            fferror("Only digits expected here");
        if (tempo == 0) {
            fieldx = 0;
            fferror("Tempo 100 will be used here");
            tempo = 100L;
        }
        start = thetime;
        /* adjust dur in case it is inherited by next note */
        if (symbolic_dur_flag) {
            dur = (dur * oldtempo);
            dur = dur / tempo;
        }
    }
}

/****************************************************************************
*               dotime
* Effect: parses a time (T) command
* Implementation: see implementation of donextdur()
****************************************************************************/

private void dotime()
{
    if (isdigit(token[fieldx])) {
        thetime = precise(scanint());
        thetime = scale(thetime, (ulong)time_scale, rate);
        if (token[fieldx] )
            fferror("Only digits were expected here");
    } else {
        fieldx++;
        thetime = dodur(); 
    }
    thetime += start;    /* time is relative to start */
}

/****************************************************************************
*               dovoice
* Effect: parse a voice (V) command (the voice is the MIDI channel)
****************************************************************************/

private void dovoice()
{
    if (isdigit(token[fieldx])) {
        voice = (int) scanint();
        if (token[fieldx])
            fferror("V must be followed by digits only");
        if (voice > MAX_CHANNELS) {
                char msg[40];
                sprintf(msg, "number too high, using %d instead", MAX_CHANNELS);
            fferror(msg);
            voice = MAX_CHANNELS;
        } 
        else if (voice < 1) {
            fferror("number too low, using 1 instead");
            voice = 1;
        }
    } 
    else fferror("No digit after V");
}

/****************************************************************************
*               fferror
* Inputs:
*    char *s: an error message string
* Effect:
*    prints the line with the error
*    puts a cursor (^) at the error location
*    prints the error message (s)
* Implementation:
*    this routine prints a carat under the character that
*    was copied into token[fieldx].    E.g. if fieldx = 0, the
*    carat will point to the first character in the field.
****************************************************************************/

private void fferror(s)
  char *s;
{
    gprintf(ERROR, "%3d | %s", lineno, line);
    marker(linex-strlen(token)+fieldx+1+6);
    gprintf(ERROR, "Error: %s.\n", s);
}

/****************************************************************************
*               init
* Effect:
*    initializes the state variables
****************************************************************************/

private void init()
{
    int i;

    end_flag = FALSE;

    /* initial (default) values for all state variables */
    symbolic_dur_flag = TRUE; /* default dur is symbolic */
    for (i = 0; i < nctrl; i++) {
        /* no initial control changes */
        ctrlflag[i] = FALSE;
        ctrlval[i] = 0;
    }

    lineno = 0;
    pitch = seq_dflt_pitch;
    loud = seq_dflt_loud;
    voice = seq_dflt_voice;
    time_scale = 1000L;
    tempo = 100L;
    rate = 100L;
    dur = precise(600); /* default dur is quarter note */
    thetime = precise(0);
    start = thetime;
    ntime = 0L;
    ticksize = 0L;
    artic = 100;
}

/****************************************************************************
*               ins_a_note
* Returns:
*    boolean: TRUE on success, FALSE if not enough memory
* Effect:
*    note events (if any) corresponding to the current line are inserted
* Implementation:
*    if a note on should occur after a note off and doesn't, and the
*    two notes have the same pitch, then the note off can cancel the
*    note on.  to make it unlikely that roundoff will cause this situation,
*    dur is decreased by one half of a clock tick before rounding.
*    also, phase2 gives precedence to note-offs that are simultaneous
*    with note-ons.
****************************************************************************/

private boolean ins_a_note()
{
    long the_dur = (trunc(dur) * artic + 50) / 100;
    int the_pitch = pitch;
    event_type note;
    if (rest_flag) the_pitch = NO_PITCH;
    note = insert_note(the_score, seqround(thetime), lineno, voice,
                       the_pitch, the_dur, loud);
    if (!note) return FALSE;
    return TRUE;    /* success! */
}

/****************************************************************************
*               ins_ctrls
* Returns:
*    boolean: TRUE on success, FALSE if not enough memory
* Effect:
*    control events corresponding to current line are inserted in score
* Implementation:
*    ctrlflag[i] is TRUE if control i was specified in this line, so
*    insert one control change for each ctrlflag[i] that is TRUE
****************************************************************************/

private boolean ins_ctrls()
{
    int i;
    event_type ctrl;

    for (i = 1; i < nctrl; i++) {
        if (ctrlflag[i]) {
            ctrl = insert_ctrl(the_score, seqround(thetime), lineno, i, voice,
                               ctrlval[i]);
            if (!ctrl) return FALSE;
            ctrlflag[i] = FALSE;
            ctrlval[i] = 0;
        }
    }
    return TRUE;    /* success! */
}

/****************************************************************************
*               issymbol
* Outputs: returns symbol number, or -1 if no match
* Assumes: token[1] has the symbol to look up (token[0] == '!')
****************************************************************************/

private int issymbol()
{
    int i, symb_num;
    char *sym;

    for (symb_num = 0; symb_num < sym_n; symb_num++) {
        sym = ssymbols[symb_num];
        i = 1;
        while (TRUE) {
            if (token[i] != *sym) break;
            if (*sym == 0) return symb_num;
            sym++; 
            i++;
        }
    }
    return -1;
}

/****************************************************************************
*               marker
* Inputs:
*    int count: the number of characters to indent
* Effect: 
*    prints a carat (^) at the position specified on file stderr
****************************************************************************/

private void marker(count)
int count;
{
    int i;
    char s[128];
    for (i=0; i<(count-1); s[i++]=' ') /* */ ;
    s[count-1] = '^';
    s[count] = '\0';
    gprintf(ERROR,"%s\n",s);
}

/*****************************************************************
*           parseend
* Effect:
*    parse the note terminator, either ",", ";", EOS or "\n"
*
****************************************************************/

private void parseend()
{
    boolean done = FALSE;
    while (!done) {
        linex += scan1(&line[linex]);
        switch (token[0]) {
        case ',':
            ndurp = TRUE;    /* switch that next time was specified */
            ntime = 0L;
            done = TRUE;
            break;
        case ';':
        case '\n':
        case EOS:
            done = TRUE;
            break;
        case ' ':
        case '\t':
            break;      /* skip over blanks and scan1 again */
        default:
            fferror("Unexpected token");
            linex += scan();  /* flush the token */
            break;
        }
    }
}

/****************************************************************************
*               parsefield
* Effect: looks at first character of token and calls a parsing routine
*
****************************************************************************/

private void parsefield()
{
    fieldx = 1;
    switch (token[0]) {
    case 'T' : 
        dotime(); 
        break;
    case 'U':
    case 'W': 
    case 'H':
    case 'Q':
    case 'S':
    case 'I': 
    case '%':
    case '^':
        dur = dodur(); 
        break;
    case 'R': 
        do_a_rest(); 
        break;
    case 'A':
    case 'B':
    case 'C':
    case 'D':
    case 'E':
    case 'F':
    case 'G': 
        pitch = dopitch(); 
        pitch_flag = TRUE;
        break;
    case 'P': 
        pitch = doabspitch(); 
        pitch_flag = TRUE;
        break;
    case 'L': 
        loud = doloud(); 
        break;
    case 'N': 
        donextdur(); 
        break;
/*    case 'J': 
 *      doctrl(1);
 *      break;
 */
    case 'K': 
        doctrl(PSWITCH_CTRL);
        break;
    case 'M': 
        doctrl(MODWHEEL_CTRL);
        break;
    case 'O': 
        doctrl(TOUCH_CTRL);
        break;
    case 'X': 
        doctrl(VOLUME_CTRL);
        break;
    case 'Y': 
        doctrl(BEND_CTRL);
        break;
    case 'Z':
        doprogram();
        break;
    case 'V': 
        dovoice();
        break;
    case '~':
        domacro();
        break;
    case '*':
        docomment();
        break;
    case '#':
        doartic();
        break;
    default : 
        doerror();
        break;
    }
}

/****************************************************************************
*               parsenote
* Effect: 
*    parses a note line -- control events (if any) and note event (if
*    present) are inserted into score
* Assumes:
*    line contains a string to be parsed
****************************************************************************/

private boolean parsenote()
{
    boolean out_of_memory = FALSE;
    int i;

    ndurp = FALSE;
    rest_flag = FALSE;

    /* this loop reads tokens for a note */
    while (token[0]) {
        parsefield();
        linex += scan();
    }

    parseend(); /* take care of note terminator */

    /*
     * insert ctrl's first so that will come before the note.
     */
    if (ctrlflag[0]) {
        out_of_memory |= !ins_ctrls();
        /* don't reset ctrlflag[0], it's used below */
    }

    /*
     * insert macro's
     */
    for (i = 0; i < macctrlx; i++) {
        event_type ctrl;
        if (macctrldef[i] == NULL) {
            ctrl = insert_macctrl(the_score, seqround(thetime), lineno,
                                  macctrlnum[i], voice, macctrlparmx[i]);
        } else {
            ctrl = insert_macro(the_score, seqround(thetime), lineno,
                        macctrldef[i], voice, macctrlnum[i],
                        &(macctrlparms[macctrlparmx[i]]));
        }
        out_of_memory |= (ctrl == NULL);
    }

    /* insert a note if
         *    (1) a pitch was specified OR
         *    (2) no control was specified and this is not a rest 
         *      (it's a pitch by default)
         *
         * NOTE: program changes during rests are advised since
         *    synthesizers may not be able to process a program
         *    change followed immediately by a note-on.  In fact, this
         *    is why we insert notes whose pitch is NO_PITCH -- so that
         *    the program change can be processed during the rest.
         */
    if (pitch_flag ||
        (!ctrlflag[0] && !rest_flag && (macctrlx == 0))) {
        out_of_memory |= !ins_a_note();
    }

    if (ndurp) thetime += ntime;
    else thetime += dur;

    return out_of_memory;
}


private boolean parseparm(valptr)
  long *valptr;
{
    register char c = token[fieldx];
    if (isdigit(c) || c == '-') {
        *valptr = scansgnint();
        return TRUE;
    } else {
        switch (c) {
          case 'P':
            fieldx++;
            *valptr = doabspitch();
             return TRUE;
          case 'A':
          case 'B':
          case 'C':
          case 'D':
          case 'E':
          case 'F':
          case 'G':
            fieldx++;
            *valptr = dopitch();
            return TRUE;
          case 'U':
          case 'W':
          case 'H':
          case 'Q':
          case 'I':
          case 'S':
          case '%':
          case '^':
            fieldx++;
            *valptr = seqround(dodur());
            return TRUE;
          case 'L':
            fieldx++;
            *valptr = doloud();
            return TRUE;
          case '\'':
            fieldx++;
            *valptr = token[fieldx];
            fieldx++;
            if (token[fieldx] != '\'') {
                fferror("single quote expected");
            }
            fieldx++;
            return TRUE;
          default:
            fferror("Parameter expected");
            return FALSE;
        }
    }
}



/****************************************************************************
*               scale
* Inputs:
*    time_type x
*    int (ulong?) n, d
* Outputs:
*    returns time_type: result of scaling x by n/d
****************************************************************************/

public time_type scale(x, n, d)
  ulong x;
  ulong n, d;
{
    ulong lo = (x & 0xFFFFL) * n;
    ulong hi = (x >> 16) * n;
    ulong res = hi / d;
    lo = (((hi - (res * d)) << 16) + lo + (d >> 1)) / d;
    return (time_type)( (res << 16) + lo );
}

/****************************************************************************
*               scan
* Inputs:
*    char *start: the string to scan
* Outputs:
*    returns int: the index of the next char in start to scan
* Effect: 
*    skips over leading blanks
*    copies characters from start into token, converting to upper case
*    scanning stops on delimiter: one of space, tab, newline, semicolon
****************************************************************************/

private int scan()
{
    char *start = line + linex;
    register char c;
    register int i = 0;
    register int j = 0;
    register int parens = 0;

    while (((c = start[i]) == ' ') || (c == '\t')) i++;

    while ((c = start[i]) != ' ' && c != '\n' && c != '\t' && c != EOS &&
           (c != ',' || token[0] == '~' || parens > 0) && c != ';') {

        if (islower(start[i])) token[j] = toupper(start[i]);
        else token[j] = start[i];
        if (c == '(') parens++;
        else if (c == ')') parens--;
        j++; 
        i++;
    }
    token[j] = '\0';

    fieldx = 0;
    if (parens) fferror("Unbalanced parens");

    return i;
}

/****************************************************************************
*               scan1
* Inputs:
*    char *start: the string to scan
* Outputs:
*    returns int: the index of the next char in start to scan
* Effect: 
*    copies one char from start into token, converting to upper case
****************************************************************************/

private int scan1(start)
char *start;
{
    int i = 0;

    token[0] = *start;
    if (islower(token[0])) token[0] = toupper(token[0]);

    if (!nullstring(token)) {
        token[1] = '\0';
        i = 1;
    }
    fieldx = 0;
    return i;
}

/****************************************************************************
*               scanint
* Outputs:
*    returns long: the scanned integer
* Effect:
*    scans an unsigned long from token, starting at fieldx
*    fieldx is incremented to end of the integer
****************************************************************************/

private long scanint()
{
    long i = 0;
    char c;
    while ((c = token[fieldx])) {
        if (isdigit(c)) {
            i = (i*10) + (c - '0');
            fieldx++;
        } else return i;
    }
    return i;
}

private long scansgnint()
{
    if (token[fieldx] == '-') {
        fieldx++;
        return -scanint();
    } else {
        if (token[fieldx] == '+') {
            fieldx++;
        }
        return scanint();
    }
}


/* scansymb -- scan a symbol from the token */
/**/
private void scansymb(str)
  char *str;
{
    char c;
    while ((c = token[fieldx])) {
        if (isdigit(c) || isalpha(c) || c == '_') {
            *str++ = c;
            fieldx++;
        } else break;
    }
    *str = EOS;
}

/****************************************************************************
*               seq_read
* Inputs:
*    seq_type seq: the sequence to receive the score
*    FILE *fp: input file
* Outputs:
*    none
* Effect: 
*    parses score from input file and builds score data structure
****************************************************************************/

void seq_read(seq, fp)
  seq_type seq;
  FILE *fp;
{
    boolean out_of_memory = FALSE;    /* set when no more memory */
    /* printf("seq_read: chunklist is 0x%x\n", seq->chunklist); */
    the_score = seq;  /* current sequence is a global within this module */
    if (!seq) return;
    init();
    lineno = 0;
        
    /* make sure line is well terminated or scan might run off the end */
    line[linesize - 1] = EOS;
    line[linesize - 2] = '\n';

    /* this loop reads lines */
    while ((fgets(line, linesize - 2, fp) != NULL) && !out_of_memory &&
           !check_aborted() && !end_flag) {
        lineno++;
        linex = 0;
        /* this loop reads notes from a line */
        while ((line[linex] != EOS) && !out_of_memory) {
            /* loop invariant: line[linex] is first char of next note */
            ctrlflag[0] = FALSE;  /* other ctrlflags are reset by ins_ctrls() */
            macctrlx = 0;
            macctrlnextparm = 0;
            pitch_flag = FALSE;
            linex += scan();
            if (!nullstring(token)) {
                if (token[0] == '*') docomment();
                else if (token[0] == '!') dospecial();
                else out_of_memory = parsenote();
            } 
            else parseend();
        }
    }

    if (out_of_memory) {
        gprintf(ERROR, "Out of note memory at line %d,\n", lineno-1);
        gprintf(ERROR, "    the rest of your file will be ignored.\n");
    }

    if (check_aborted()) {
        gprintf(ERROR, "User aborted score input,\n");
        gprintf(ERROR, "    the rest of your file will be ignored.\n");
        if (abort_flag == BREAK_LEVEL) abort_flag = 0;
    }

    /* fclose(fp); -- don't close the file; if you do, Nyquist's garbage
       collector will close Nyquist's copy, and closing the file twice
       in Linux will crash Nyquist */

    gprintf(TRANS, "\nLoaded Adagio file with %ld note(s), %ld ctrl(s).\n\n",
            seq_notecount(the_score), seq_ctrlcount(the_score));
}