File: postable.c

package info (click to toggle)
pmw 1%3A4.30-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 6,128 kB
  • sloc: ansic: 26,369; makefile: 337; sh: 255
file content (1672 lines) | stat: -rw-r--r-- 55,196 bytes parent folder | download
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
/*************************************************
*    The PMW Music Typesetter - 3rd incarnation  *
*************************************************/

/* Copyright (c) Philip Hazel, 1991 - 2018 */

/* Written by Philip Hazel, starting November 1991 */
/* This file last modified: May 2018 */


/* This file contains the main code for creating a position table for a bar. It
calls subroutines in possubs.c */


#include "pmwhdr.h"
#include "pagehdr.h"
#include "poshdr.h"




/*************************************************
*      Construct position table for one bar      *
*************************************************/

/* This procedure constructs a list of pairs containing a musical offset (from
the start of the bar), and a horizontal offset (from the first note position).

We first check to see if we are at a place where there are many bars rest for
all the relevant staves. If so, special action is taken later.

We go through each stave in turn, inserting between entries where necessary and
adjusting for minimum note widths. A space item in the input can cause
non-standard spacing.

Suspended staves are not excluded -- as they should only contain whole bar
rests, they won't affect the spacing. If "resume" is encountered, we set the
"notsuspend" bit.

There are several passes, to ensure that the notes on any one stave are not too
close together when accidentals and dots are present. There is yet another pass
to adjust the spacing for any embedded clefs, key signatures, etc.

The yield of the procedure is the horizontal width of the bar (excluding the
bar line). If a key or time signature has been read, then the global
page_xxwidth is set to the width for printing just that much of the bar, for
use at the end of a line.

Argument:   TRUE if mis-matched bar lengths in different staves give an error
            (set FALSE when a bar is re-processed for a large stretch)
Returns:    the width of the bar
*/

int
page_makepostable(BOOL lengthwarn)
{
posstr *outptr;
workposstr *left;

int i;
int doublebar = FALSE;
int restbar = TRUE;
int firstrestbar = TRUE;
int barnumber = page_barnumber;
int forcenewline = b_End;
int endbarmoff = BIGNUMBER;
int MaxKeyWidth = 0;                       /* widest final key signature */
int MaxTimeWidth = 0;                      /* widest final time signature */
int Oldlastendwide = page_lastendwide;     /* previous bar's value */
int Oldlastenddouble = page_lastenddouble; /* this for double bar */
int ulaymap[STAVE_BITVEC_SIZE];            /* map underlay staves */
int largestmagn = 0;

mac_initstave(ulaymap, 0);

pos_bp = curmovt->posvector + page_barnumber;

pos_bp->multi = 1;                    /* not multibar rest */
pos_bp->posxRL = -posx_RLleft;        /* default order for time/key/repeat */
pos_bp->barnoforce = 0;               /* no forced bar number */
pos_bp->barnoX = 0;                   /* no bar number movement */
pos_bp->barnoY = 0;

page_lastendwide = FALSE;         /* flag wide bar line (e.g. repeat) */
page_lastenddouble = FALSE;       /* this for double barline (not wide) */
page_manyrest = 0;                /* not many bars rest */
page_xxwidth = 0;                 /* key and/or time change width */
page_warnkey = FALSE;             /* no warning key read */
page_warntime = FALSE;            /* no warning time read */

/* Set up initial position table entry for the barline. */

page_postable->moff = BIGNUMBER;
page_postable->xoff = 0;
page_postable->space = 0;
mac_initstave(page_postable->stemup, 0);
mac_initstave(page_postable->stemdown, 0);
page_postable->auxid = 0;

page_posptr = page_postable;      /* last entry */

/* First we check for whole-bar rests in all the relevant staves, and count the
number of successive such bars if any are found. Key and and time changes and
newline/page and a number of other non-printing items are allowed in the first
rest bar. So is printed text. A clef change is allowed at the start of the
first bar (to allow multiple rests at the start of a piece); otherwise a clef
causes the bar to be treated as the last rest bar. */

while (barnumber <= curmovt->barcount)
  {
  int rrepeatORclefORdbar = FALSE;

  /* Scan all the relevant staves */

  for (page_stave = 0; page_stave <= page_lastwanted; page_stave++)
    {
    if (mac_teststave(curmovt->staves, page_stave))
      {
      bstr *p = ((curmovt->stavetable)[page_stave])->barindex[barnumber];
      if (p != NULL)
        {
        int type = p->type;
        BOOL hadnote = FALSE;

        while (type != b_End && restbar)
          {
          switch(type)
            {
            case b_Jump:
            p = (bstr *)(((b_Jumpstr *)p)->next);
            break;

            case b_note:
            if (((b_notestr *)p)->spitch != 0 ||
               (((b_notestr *)p)->flags & nf_centre) == 0)
                 restbar = FALSE;
            hadnote = TRUE;
            break;

            case b_comma:
            case b_caesura:  case b_nbar:
            case b_slur:     case b_endslur:
            case b_dotbar:   case b_hairpin:
            case b_reset:    case b_tick:
            case b_ornament: case b_nopack:
            restbar = FALSE;
            break;

            case b_dbar:
            rrepeatORclefORdbar = TRUE;
            break;

            case b_ibar:
            break;

            case b_clef:
            if (firstrestbar)
              {
              if (hadnote) restbar = FALSE;
              }
            else
              {
              if (!hadnote) restbar = FALSE;
                else rrepeatORclefORdbar = TRUE;
              }
            break;

            case b_rrepeat:
            rrepeatORclefORdbar = TRUE;
            break;

            default:
            if (!firstrestbar) restbar = FALSE;
            break;
            }

          p = (bstr *)((uschar *)p + length_table[type]);
          type = p->type;
          }
        }
      }
    }

  /* All the staves have been scanned, or a non-rest was found */

  if (!restbar) break;
  page_manyrest++;
  firstrestbar = FALSE;
  if (rrepeatORclefORdbar) break;    /*  allow rrepeat or clef or double bar in last bar */
  barnumber++;
  }

/* Now set about constructing the position table. We scan the staves several
times in order to do this. The first scan establishes the entries for the
notes; horizontal offsets are set for the first staff, and any notes on
subsequent staves that are past the last notes on the staves above. Other notes
are interpolated pro rata at this stage. During this pass we also deal with
non-note items that don't affect the spacing, but must be noted for other parts
of the code. We also record any [space] settings for implemention right at the
end.

If we are handling a sequence of rest bars, we must process the last bar as
well as the first, in case there are clefs at the end of the last bar. It isn't
straightforward to write this as any kind of a loop, so we resort to the
dreaded GOTO for simplicity. */

barnumber = page_barnumber;

REPEATFIRSTSCAN:

for (page_stave = 0; page_stave <= page_lastwanted; page_stave++)
  {
  if (mac_teststave(curmovt->staves, page_stave))
    {
    int extraspace = 0;           /* value of [space] */
    int extraspace_set = FALSE;   /* TRUE if [space] encountered */
    int notjustrest = FALSE;      /* TRUE if non-whole-bar-rest read */
    int MaxMoff = 0;              /* for resets */

    bstr *p = ((curmovt->stavetable)[page_stave])->barindex[barnumber];

    /* If there is any data in the bar, scan it */

    if (p != NULL)
      {
      int type = p->type;
      int moff = 0;                      /* musical offset */
      int moffdelta;                     /* delta from n*hdsq */
      int auxitem = FALSE;               /* last item was aux */
      workposstr *pp = page_postable;    /* position in page_postable */
      mac_setstavesize(page_stave);      /* relative size of this stave */

      if (main_stavemagn > largestmagn) largestmagn = main_stavemagn;

      /* Loop for all items in the bar */

      while (type != b_End)
        {
        switch(type)
          {
          case b_Jump:
          p = (bstr *)(((b_Jumpstr *)p)->next);
          break;

          /* Deal with items that are notes, ignoring grace notes
          in this pass */

          case b_note:
          if (((b_notestr *)p)->length)
            {
            b_notestr *note = (b_notestr *)p;

            int length = note->length;
            int flags = note->flags;
            int notetype = note->notetype;
            int pitch = note->spitch;
            int upflags[STAVE_BITVEC_SIZE];
            int downflags[STAVE_BITVEC_SIZE];

            mac_initstave(upflags, 0);
            mac_initstave(downflags, 0);

            if (pitch != 0 || (flags & nf_centre) == 0) notjustrest = TRUE;

            /* Set stem direction flags for fine spacing adjustment, but only
            if there really is an actual stem. */

            if (pitch != 0 && notetype >= minim)
              {
              if ((flags & nf_stemup) != 0) mac_setstave(upflags, page_stave);
                else mac_setstave(downflags, page_stave);
              }

            /* Scan up position table to this musical offset; until one stave's
            data has been read, the barline has a musical offset of "infinity".
            */

            while (pp < page_posptr && pp->moff < moff) pp++;

            /* If we have matched at the barline, we are on a stave with a bar
            that is longer than any on any previous staves. We reset the
            barline moff to "infinity". */

            if (pp->moff <= moff && pp == page_posptr)
              pp->moff = BIGNUMBER;

            /* If we are at an previously-existing entry, do nothing.
            Otherwise, move up the existing entries in the table and and insert
            a new entry. Note that that the moving up leaves the correct xoff
            value in the "new" entry, and it is the field in the *next* entry
            that must be updated. */

            if (pp->moff != moff)
              {
              workposstr *q;
              for (q = page_posptr; q >= pp; q--) q[1] = q[0];

              pp->moff = moff;
              pp->space = 0;
              pp->auxid = 0;

              /* If we are at the end of the bar, and the bar length is unset,
              set the horizontal offset to be appropriate to this note type.
              (Note that page_posptr is temporarily pointing one before the
              barline entry here.) */

              if (pp == page_posptr && (page_posptr + 1)->moff == BIGNUMBER)
                {
                (page_posptr + 1)->xoff = pos_notewidth(length);
                }

              /* If we are not at the end of the bar, or if the bar length has
              already been set, set the horizontal offset pro rata pro tem, and
              adjust the next value to compensate for what has been taken off.
              */

              else
                {
                workposstr *prev = pp - 1;
                workposstr *next = pp + 1;
                pp->xoff = mac_muldiv(next->xoff, moff - prev->moff,
                  next->moff - prev->moff);
                next->xoff -= pp->xoff;
                }

              /* Move pointer to include one more entry */

              page_posptr++;
              }

            /* Or in the stem flags and save extra space value if greater than
            what is there. */

            for (i = 0; i < STAVE_BITVEC_SIZE; i++)
              {
              pp->stemup[i] |= upflags[i];
              pp->stemdown[i] |= downflags[i];
              }

            if (extraspace_set)
              {
              if (extraspace >= 0)
                {
                if (extraspace > pp->space) pp->space = extraspace;
                }
              else if (extraspace < pp->space) pp->space = extraspace;
              extraspace = 0;
              extraspace_set = FALSE;
              }

            /* Adjust the musical offset for the next note, and set the flag
            saying last item was not an aux item. */

            moff += length;
            auxitem = FALSE;
            }

          else auxitem = TRUE;  /* Grace notes are aux items */
          break;

          /* Deal with non-note items. We deal with those that are noted for
          external action in this pass, and also with [space]. Those that have
          auxiliary positions must be noted, in order to cause a bar length
          check to happen. */

          case b_dbar:
          doublebar = page_lastenddouble = TRUE;
          break;

          /* It is convenient to handle the bar number forcing item here, when
          we have the relevant block available. */

          case b_barnum:
            {
            b_barnumstr *bn = (b_barnumstr *)p;
            if (!bn->flag) pos_bp->barnoforce = 255; else  /* suppress */
              {
              pos_bp->barnoforce = 1;     /* force bar number */
              pos_bp->barnoX = bn->x;
              pos_bp->barnoY = bn->y;
              }
            }
          break;

          case b_space:
            {
            b_spacestr *bs = (b_spacestr *)p;
            if (bs->relative) extraspace += (bs->value * main_stavemagn)/1000;
              else extraspace += bs->value;
            }
          extraspace_set = TRUE;
          break;

          case b_ns:
            {
            b_nsstr *bn = (b_nsstr *)p;
            for (i = 0; i < 8; i++)
              page_nextdata->notespacing[i] += bn->ns[i];
            }
          break;

          case b_nsm:
            {
            int v = ((b_nsmstr *)p)->value;
            for (i = 0; i < 8; i++)
              page_nextdata->notespacing[i] =
                mac_muldiv(page_nextdata->notespacing[i], v, 1000);
            }
          break;

          case b_ens:
          memcpy(page_nextdata->notespacing, curmovt->notespacing,
            8*sizeof(int));
          break;

          case b_newline:
          case b_newpage:
          if (!page_startlinebar) forcenewline = type;
          break;

          case b_resume:
          if (mac_testNstave(page_accepteddata->notsuspend, page_stave))
              mac_setstave(page_nextdata->notsuspend, page_stave);
          break;

          case b_reset:
          if (MaxMoff < moff)
            {
            MaxMoff = moff;
            page_posptr->moff = moff;
            }
          moff = 0;
          pp = page_postable;
          break;

          /* Changes of stave name affect the available width for the system,
          and so must be handled here. However, we needn't (mustn't) process
          them when restretching to get even widths. */

          case b_name:             /* change of stave name */
          if (page_layout_stretchn == 1 && page_layout_stretchd == 1)
            {
            int n = ((b_namestr *)p)->n;
            snamestr *s = ((curmovt->stavetable)[page_stave])->stave_name;
            while (--n > 0 && s != NULL) s = s->next;

            /* Get fresh store if unchanged in this bar */

            if (page_accepteddata->stavenames == page_nextdata->stavenames)
              page_nextdata->stavenames =
                store_copy(page_accepteddata->stavenames);
            page_nextdata->stavenames[page_stave] = s;
            }
          break;

          case b_text:             /* remember underlay staves */
          if ((((b_textstr *)p)->flags & text_ul) != 0)
            mac_setstave(ulaymap, page_stave);
          break;

          case b_clef: case b_time:  case b_key:
          case b_tick: case b_comma: case b_dotbar:
          case b_caesura:
          if (moff > 0) auxitem = TRUE;
          break;

          default:
          if (type >= b_baditem) error_moan(57, type);
          break;
          }

        /* Move on to next item */

        p = (bstr *)((uschar *)p + length_table[type]);
        type = p->type;
        }

      /* We are now at the end of the bar; set the current offset to the
      maximum encountered at [reset]s and handle any rounding problems caused
      by tuplets. */

      if (moff < MaxMoff) moff = MaxMoff;

      /* If the current length differs from a multiple of hemidemisemiquavers
      by only a small amount, round it. This can happen when note lengths are
      divided by non-factors for tuplets. For example, in 5/8 time, if one of
      the quavers in {5-/6 g-g-g-g-g-g-} is turned into a hemidemisemiquaver,
      the bar ends up off by 1. */

      moffdelta = moff % len_hdsquaver;
      if (moffdelta <= TUPLET_ROUND) moff -= moffdelta;
        else if (len_hdsquaver - moffdelta <= TUPLET_ROUND)
          moff += len_hdsquaver - moffdelta;

      /* Deal with a [space] value */

      if (extraspace_set)
        {
        if (extraspace >= 0)
          {
          if (extraspace > page_posptr->space) page_posptr->space = extraspace;
          }
        else
          if (extraspace < page_posptr->space) page_posptr->space = extraspace;
        }

      /* If this bar was not a whole bar rest, or if it ended with something
      that is positioned relative to the bar line, check that it has the same
      length as those above it. For the first stave, endbarmoff will equal
      BIGNUMBER. If the lengths differ, keep the largest. Generate a warning
      the first time we measure the bar (when lengthwarn will be TRUE), if the
      length is less than the length of rest bars above, or not equal to note
      bars above. */

      if (notjustrest || auxitem)
        {
        if (endbarmoff == BIGNUMBER) endbarmoff = 0; else
          {
          if (moff != endbarmoff && lengthwarn)
            error_moan(58, barnumber, page_stave, barnumber,
              barnumber, endbarmoff, barnumber, page_stave, moff);
          }

        if (moff > endbarmoff) endbarmoff = moff;
        page_posptr->moff = endbarmoff;
        }

      /* For a whole bar rest, we set the moff in the final entry if it is not
      set (i.e. if this is stave 1), so that subsequent staves space correctly.
      However, whole bar rests are not checked against other bars for length.
      This makes it easy to handle odd cases by using R!, though it does miss
      the occasional warning that might have been nice. */

      else
        {
        if (page_posptr->moff == BIGNUMBER) page_posptr->moff = moff;
        }
      }    /* Block for processing a stave's data */
    }      /* Skip for skipped staves */
  }        /* End of per-stave loop */

/* The previous loop has to be repeated iff page_manyrest is greater than one,
in order to process the final bar of a repeat sequence. This just isn't easy to
code as a standard loop. */

if (page_manyrest >= 2 && barnumber == page_barnumber)
  {
  barnumber += page_manyrest - 1;
  goto REPEATFIRSTSCAN;
  }

/* If the bar contained no notes in all staves the final musical offset and
spacing will not have been set. We need to set them in order to cope  with
other items, e.g. text or caesurae, at the end of the bar. */

if (page_posptr->moff == BIGNUMBER)
  {
  page_posptr->moff = 0;
  page_posptr->xoff = page_nextdata->notespacing[semibreve];
  }

/* Debugging: print out the basic position table */

if (main_tracepos == (-1) || main_tracepos == page_barnumber)
  {
  workposstr *t;
  debug_printf("-------------------------\n");
  debug_printf("BAR %b BASIC POSITIONS:\n", page_barnumber);
  for (t = page_postable; t <= page_posptr; t++)
    debug_printf("%6d %6d\n", t->moff, t->xoff);
  }


/* We have now constructed the basic position table for the bar. However, some
gaps may be unacceptably narrow. We now do a series of repeat scans of the
notes, gradually adjusting the spacing. */


/* The first scan adjusts for note length only, applying minimum distances that
will ensure that notes do not overprint. This pass is concerned with space to
the *right* of each note only -- this includes inverted notes when the stem is
up. Space to the *left* is dealt with in subsequent passes.

If this is a multiple rest bar we don't need to go through the whole
rigmarole. The length of such bars is fixed. */

if (page_manyrest >= 2)
  {
  int ii = (curmovt->codemultirests && page_manyrest < 9)? page_manyrest : 0;
  page_posptr->xoff = longrest_barwidths[ii]*main_stavemagn;
  pos_bp->multi = page_manyrest;
  }

else for (page_stave = 0; page_stave <= page_lastwanted; page_stave++)
  {
  if (mac_teststave(curmovt->staves, page_stave))
    {
    bstr *p = ((curmovt->stavetable)[page_stave])->barindex[page_barnumber];

    /* If there is any data in the bar, scan it */

    if (p != NULL)
      {
      workposstr *prev = page_postable;    /* previous page_postable entry */

      BOOL beambreak2 = FALSE; /* secondary beambreak detected */

      int length = 0, flags = 0;
      int minwidth = 7250;    /* basic minimum width for notes */
      int type = p->type;
      int moff = 0;                      /* musical offset */

      int barspace =
        ((page_barnumber == curmovt->barcount) && !curmovt->unfinished)?
          11000 : 7400;

      mac_setstavesize(page_stave);

      /* Loop for all items in the bar, including the end item, since its space
      value applies to the previous note. We must do the same as bar end for a
      [reset] which is at the bar end! */

      for (;;)
        {
        int nextlength = 0;

        /* If we are at the end of the bar, set an appropriate minimum distance
        for the final note, else reset the standard. */

        minwidth = (type == b_End)? barspace : 7250;

        /* Deal with items that are notes, and also the final barline, but skip
        over grace notes for now. */

        if (type == b_End ||
           (type == b_note && (nextlength = ((b_notestr *)p)->length) != 0) ||
           (type == b_reset && moff == page_posptr->moff))
          {

          /* Spacing checks start at the second position - note that the
          variable length contains the length of the *previous* note, and the
          flags are also those of the previous note at this point. */

          if (moff != 0)
            {
            workposstr *t = prev;
            int extra;
            int n = 0;
            int width = 0;
            int wantedwidth = pos_notewidth(length);

            minwidth = pos_typewidth(minwidth, length, flags);
            if (wantedwidth < minwidth) wantedwidth = minwidth;

            /* Insert a small amount of space after a secondary beam break,
            to avoid an optical illusion. */

            if (beambreak2)
              wantedwidth += mac_muldiv(1300, main_stavemagn, 1000);
            beambreak2 = FALSE;

            /* Scan up position table to this musical offset, accumulating
            horizontal widths. */

            while (t < page_posptr && t->moff < moff)
              {
              n++;
              t++;
              width += t->xoff;
              }

            /* If the width is insufficient, distribute the additional space
            amongst all the positions between the previous note on this stave
            and this note. Currently just divide it evenly, but we may need to
            improve on that one day. The wanted width is multiplied by the
            layout stretch factor - this is unity for the first measuring, but
            greater when re-laying-out for wide stretches. */

            extra = mac_muldiv(wantedwidth, page_layout_stretchn,
              page_layout_stretchd) - width;

            if (extra > 0)
              {
              int x = extra/n;
              workposstr *pp = prev + 1;

              while (pp <= t)
                {
                (pp++)->xoff += x;
                extra -= x;
                if (extra < x) x = extra;
                }
              }

            /* Save previous page_postable pointer */

            prev = t;
            }

          /* Terminate loop if we have processed the end item */

          if (type == b_End) break;

          /* Else if this was an end-of-bar [reset], reset the musical offset
          and previous pointer. No need to reset length & flags, as the first
          note doesn't use them. */

          else if (type == b_reset)
            {
            moff = 0;
            prev = page_postable;
            }

          /* Adjust the musical offset, and point to next item, saving the
          length of this item, and other relevant parameters. */

          else
            {
            length = nextlength;
            flags = ((b_notestr *)p)->flags;
            moff += length;
            }
          }

        /* Deal with relevant non-note items */

        else switch (type)
          {
          case b_Jump:
          p = (bstr *)(((b_Jumpstr *)p)->next);
          break;

          case b_reset:  /* not end-of-bar reset */
          moff = 0;
          prev = page_postable;
          break;

          case b_beambreak2:
          beambreak2 = TRUE;
          break;

          case b_dbar:
          barspace = 10000;
          break;

          case b_ebar:
          barspace = 13000;
          break;

          /* For a chord, collect the invert and dotting flags for subsequent
          processing. */

          case b_chord:        /* 2nd and subsequent notes */
            {
            b_chordstr *pc = (b_chordstr *)p;
            flags |= pc->flags & (nf_dotted + nf_invert);
            }
          break;
          }

        /* Move on to next item */

        p = (bstr *)((uschar *)p + length_table[type]);
        type = p->type;
        }   /* End of item on stave loop */
      }     /* Block for processing a stave's data */
    }
  }         /* End of per-stave loop */


/* Debugging: print out the note-spaced position table */

if (main_tracepos == (-1) || main_tracepos == page_barnumber)
  {
  workposstr *t;
  debug_printf("BAR %b NOTE-SPACED POSITIONS:\n", page_barnumber);
  for (t = page_postable; t <= page_posptr; t++)
    debug_printf("%6d %6d\n", t->moff, t->xoff);
  }


/* Now we do a scan for adjacent up and down stems. We can make an adjustment
with confidence only if all staves require it; otherwise it looks silly. Other
cases may need manual adjustment. This scan can be done on the page_postable
only, using the flag bits already set up. Take care not to shorten distance
below the absolute minimum! */

for (left = page_postable; left < page_posptr - 1; left++)
  {
  workposstr *right = left + 1;

  if (!mac_anystave(left->stemup) && !mac_anystave(right->stemdown) &&
       mac_anystave(left->stemdown) &&
       mac_samestave(left->stemdown, right->stemup))
    { if (right->xoff >= 11000) right->xoff -= 1000; }

  else if (!mac_anystave(left->stemdown) && !mac_anystave(right->stemup) &&
           mac_anystave(left->stemup) && mac_samestave(left->stemup, right->stemdown))
    right->xoff += 1000;
  }



/* Debugging: print out the new spacings */

if (main_tracepos == (-1) || main_tracepos == page_barnumber)
  {
  workposstr *t;
  debug_printf("BAR %b NOTE-SPACED/STEMMED POSITIONS:\n", page_barnumber);
  for (t = page_postable; t <= page_posptr; t++)
    debug_printf("%6d %6d\n", t->moff, t->xoff);
  }


/* Now we do a pass to insert space for things to the left of notes, like
accidentals, clefs, caesuras, etc. We have to scan through to each note before
handling them, as they come in a fixed (well, almost fixed) order. Use a word
of flag bits to remember those that have a width associated with them, and also
if anything at all has been encountered. If the bar starts with an lrepeat on
the barline, a flag gets set so that we can add space afterwards. */

pos_barstartrepeat = FALSE;

/* If we are handling a sequence of rest bars, we must process the last bar as
well as the first, in case there are clefs at the end of the last bar. It isn't
straightforward to write this as any kind of a loop, so we resort to the
dreaded GOTO for simplicity. */

barnumber = page_barnumber;

REPEATSPACESCAN:

for (page_stave = 0; page_stave <= page_lastwanted; page_stave++)
  {
  if (mac_teststave(curmovt->staves, page_stave))
    {
    bstr *p = ((curmovt->stavetable)[page_stave])->barindex[barnumber];

    /* If there is any data in the bar, scan it */

    if (p != NULL)
      {
      workposstr *previous = NULL;

      BOOL arp_read = FALSE;
      BOOL spread_read = FALSE;

      int type = p->type;
      int moff = 0;                       /* musical offset */
      int xflags = 0;                     /* flags for encountered items */
      int prevlength = -1;                /* length of previous note */
      int prevflags = 0;                  /* flags on previous note/chord */
      int ensured = 0;

      int gracevector[posx_maxgrace + 1];
      int timevector[posx_maxtime + 1];
      int keyvector[posx_maxkey + 1];

      gracevector[0] = 0;                 /* count of gracenotes */
      timevector[0] = 0;                  /* count of time signatures */
      keyvector[0] = 0;                   /* count of key signatures */

      mac_setstavesize(page_stave);       /* relative size of this stave */

      /* Loop for all items in the bar */

      while (type != b_End)
        {
        b_notestr *note;
        int length;

        switch(type)
          {
          case b_Jump:
          p = (bstr *)(((b_Jumpstr *)p)->next);
          break;


          /* Deal with notes */

          case b_note:
          note = (b_notestr *)p;
          length = note->length;

          /* Count gracenotes and note something has been encountered */

          if (length == 0)
            {
            fontsizestr *fontsizes = curmovt->fontsizes;
            int gracecount = gracevector[0] + 1;
            if (gracecount > posx_maxgrace) gracecount = posx_maxgrace;
            gracevector[gracecount] = mac_muldiv(note->accleft,
              fontsizes->fontsize_grace, fontsizes->fontsize_music);
            gracevector[0] = gracecount;
            xflags |= xf_grace;
            }

          /* A real note -- first collect data for accidentals, then if
          anything precedes the note, call a routine to do most of the work.
          Always update the moff and save the note item for use next time. */

          else
            {
            int thisflags = 0;
            int accleft = 0;

            /* Collect the maximum accidental width for a chord, and also check
            for inverted notes. Update the p pointer to point to the last note
            of the chord, to save scanning it again. */

            do
              {
              int a = note->accleft;
              if ((thisflags & (nf_invert | nf_stemup)) == nf_invert &&
                a < 4500) a = 4500;
              if (accleft < a) accleft = a;
              thisflags |= note->flags;
              p = (bstr *)note;
              mac_advancechord(note);
              }
            while (note->type == b_chord);

            /* Having got the accidental width, we need to add a teeny bit
            more space on the left. */

            if (accleft > 0) accleft += 600;

            /* Breves get their left bars printed to the left of the actual
            note position. We can treat this as a little bit of extra
            accidental space. The distance is in fact 2.3 points, but because
            things to the left get at least 11 points (as opposed to 7 points
            for notes only) we just need to ensure that something is inserted
            if there are no other accidentals. BUT, at the start of a bar,
            accidentals are shifted left, so in that case, leave a bit more. */

            if (length >= len_breve && accleft == 0)
              accleft = (moff == 0)? 3000 : 250;

            /* Extra space is needed for arpeggio or spread marks. This too can
            be treated as extra accidental space. */

            if (arp_read) { accleft += 6000; arp_read = FALSE; }
            if (spread_read) { accleft += 6000; spread_read = FALSE; }

            /* If accidental space is needed, or if there are other things to
            the left of the note, we call a separate procedure to do the work.
            This is also called at end of bar for the last space. */

            if (xflags != 0 || accleft != 0)
              {
              /* Arrange to keep the widest final key/time for warning bars */
              if (timevector[0] > 0)
                {
                if (timevector[timevector[0]] > MaxTimeWidth)
                  MaxTimeWidth = timevector[timevector[0]];
                }
              if (keyvector[0] > 0)
                {
                if (keyvector[keyvector[0]] > MaxKeyWidth)
                  MaxKeyWidth = keyvector[keyvector[0]];
                }

              /* Now do the insertion work */

              previous = pos_insertextras(moff, xflags, accleft, keyvector,
                timevector, gracevector, previous, prevlength, prevflags);

              /* Reset all the flags for the next note */

              xflags = 0;
              timevector[0] = 0;
              keyvector[0] = 0;
              gracevector[0] = 0;
              }

            /* If there are no extras on this note, just get previous
            up-to-date. */

            else
              {
              if (previous == NULL) previous = page_postable;
              while (previous->moff < moff) previous++;
              }

            /* Handle any ensured value for this note (which previous is now
            pointing at) */

            if (ensured > 0)
              {
              int between = 0;
              if (prevlength > 0)
                {
                workposstr *last = previous - 1;
                while (last->moff > moff - prevlength)
                  { between += last->xoff; last--; }
                }

              if (previous->xoff + between < ensured)
                { previous->xoff = ensured - between; ensured = 0; }
              }

            /* Remember previous note's length and its flags */

            prevlength = length;
            prevflags = thisflags;
            moff += length;
            }
          break;

          case b_ensure:
          ensured = (main_stavemagn * ((b_ensurestr *)p)->value)/1000;
          break;

          /* Deal with non-note items. Clefs, keys, and times at the starts
          of lines will be marked for suppression. */

          case b_reset:
          moff = 0;
          previous = NULL;
          prevlength = -1;
          prevflags = 0;
          break;

          case b_lrepeat:
          xflags |= xf_lrepeat;

          /* If this repeat follows a key or time signature not at the start of
          a bar, move its position so that it prints after them, i.e. in the
          same order as in the input. */

          if ((xflags & xf_keytime) != 0 || page_startchangetime)
            pos_bp->posxRL = -posx_RLright;
          break;

          case b_rrepeat: xflags |= xf_rrepeat; break;
          case b_comma:   xflags |= xf_comma;   break;
          case b_tick:    xflags |= xf_tick;    break;
          case b_caesura: xflags |= xf_caesura; break;
          case b_dotbar:  xflags |= xf_dotbar;  break;

          /* Clefs are the one thing that are allowed at the end of a multiple
          repeat bar. Fudge the spacing. Update the working copy for use with
          special key signatures. */

          case b_clef:
          if (!((b_clefstr *)p)->suppress)
            {
            xflags |= xf_clef;
            if (barnumber != page_barnumber && moff != 0)
              page_posptr->xoff += 15*main_stavemagn;
            page_sysclef[page_stave] = ((b_clefstr *)p)->trueclef;
            }
          break;

          case b_setclef:
          page_sysclef[page_stave] = ((b_setclefstr *)p)->value;
          break;

          case b_key:
            {
            b_keystr *k = (b_keystr *)p;
            if (!k->suppress)
              {
              int keycount = keyvector[0] + 1;
              if (keycount > posx_maxkey) keycount = posx_maxkey;
              xflags |= xf_keytime;
              keyvector[keycount] = (page_startlinebar? 0 : 4000) +
                misc_keywidth(k->key, page_sysclef[page_stave]);
              keyvector[0] = keycount;
              if (mac_teststave(page_accepteddata->notsuspend, page_stave))
                page_warnkey |= k->warn;
              }
            }
          break;

          case b_time:
            {
            b_timestr *t = (b_timestr *)p;
            if (!t->suppress)
              {
              int timecount = timevector[0] + 1;
              if (timecount > posx_maxtime) timecount = posx_maxtime;
              timevector[timecount] = misc_timewidth(t->time) + 5000;
              timevector[0] = timecount;
              xflags |= xf_keytime;
              if (curmovt->showtime &&
                mac_teststave(page_accepteddata->notsuspend, page_stave))
                  page_warntime |= t->warn;
              }
            }
          break;

          case b_ornament:
            {
            b_ornamentstr *o = (b_ornamentstr *)p;
            if (o->ornament == or_arp ||
                o->ornament == or_arpu ||
                o->ornament == or_arpd) arp_read = TRUE;
              else if (o->ornament == or_spread) spread_read = TRUE;
            }
          break;
          }

        /* Move on to next item */

        p = (bstr *)((uschar *)p + length_table[type]);
        type = p->type;
        }

      /* Process for auxiliaries at the end of the bar */

      if (xflags != 0) pos_insertextras(moff, xflags, 0, keyvector, timevector,
        gracevector, previous, prevlength, prevflags);

      /* Handle [ensure] at end of bar */

      if (ensured > 0)
        {
        int between = 0;
        if (prevlength > 0)
          {
          workposstr *last = page_posptr - 1;
          while (last->moff > moff - prevlength)
            { between += last->xoff; last--; }
          }

        if (page_posptr->xoff + between < ensured)
          page_posptr->xoff = ensured - between;
        }
      }
    }    /* Block for processing a stave's data */
  }      /* End of per-stave loop */

/* The previous loop has to be repeated iff page_manyrest is greater than one,
in order to process the final bar of a repeat sequence. This just isn't easy to
code as a standard loop. */

if (page_manyrest >= 2 && barnumber == page_barnumber)
  {
  barnumber += page_manyrest - 1;
  goto REPEATSPACESCAN;
  }

/* Add a bit of space if the bar is not the first on a line, and starts with a
left repeat. */

if (pos_barstartrepeat)
  {
  page_postable->xoff += 6500;       /* extra space at start bar */
  page_xxwidth -= 6500;              /* but not for xxwidth */
  }

/* Debugging: print out the postable yet again */

if (main_tracepos == (-1) || main_tracepos == page_barnumber)
  {
  workposstr *t;
  debug_printf("BAR %b ALL-IN POSITIONS:\n", page_barnumber);
  for (t = page_postable; t <= page_posptr; t++)
    debug_printf("%6d %6d\n", t->moff, t->xoff);
  }


/* If enabled, we now do a scan to check that any underlaid text is not going
to overprint. Assume all is well at the start and end of a bar -- we have to,
since we don't do inter-bar spacing. Underlay and overlay are handled
separately, but for multiple verses the widest syllable is taken. */

if (curmovt->spreadunderlay)
  {
  BOOL spreadsome = FALSE;

  for (page_stave = 1; page_stave <= page_lastwanted; page_stave++)
    if (mac_teststave(ulaymap, page_stave))

    {
    bstr *p = ((curmovt->stavetable)[page_stave])->barindex[page_barnumber];

    /* If there is any data in the bar, scan it */

    if (p != NULL)
      {
      workposstr *previousO = page_postable;
      workposstr *previousU = page_postable;
      BOOL hadulay = FALSE;
      BOOL hadolay = FALSE;

      int nextleftU = 0;
      int nextleftO = 0;
      int nextrightU = 0;
      int nextrightO = 0;
      int lastrightU = 0;
      int lastrightO = 0;

      int type = p->type;
      int moff = 0;

      mac_setstavesize(page_stave);

      /* Loop for all items in the bar */

      while (type != b_End)
        {
        if (type == b_Jump)
          {
          p = (bstr *)(((b_Jumpstr *)p)->next);
          }

        /* Deal with items that are notes. (No need to look at subsequent
        notes of a chord.) */

        else if (type == b_note)
          {
          b_notestr *pp = (b_notestr *)p;
          int length = pp->length;

          /* Ignore grace notes and notes with no {und,ov}erlay>. We have to
          process underlay and overlay entirely separately. */

          if (hadulay && length > 0)
            {
            workposstr *this = previousU;

            while (this->moff < moff) this++;

            /* Do nothing at bar start */

            if (moff > 0)
              {
              int avail = 0;
              workposstr *t = previousU + 1;

              while (t <= this) avail += (t++)->xoff;
              avail -= lastrightU - nextleftU;
              if (avail < 0)
                {
                workposstr *tt = previousU + 1;
                while (tt->moff < moff + posx_max) tt++;
                tt->xoff -= avail;
                spreadsome = TRUE;
                }
              }

            lastrightU = nextrightU;
            nextleftU = nextrightU = 0;
            hadulay = FALSE;
            previousU = this;
            }


          /* Similar code for overlay */

          if (hadolay && length > 0)
            {
            workposstr *this = previousO;
            while (this->moff < moff) this++;

            /* Do nothing at bar start */

            if (moff > 0)
              {
              int avail = 0;
              workposstr *t = previousO + 1;

              while (t <= this) avail += (t++)->xoff;
              avail -= lastrightO - nextleftO;
              if (avail < 0)
                {
                workposstr *tt = previousO + 1;
                while (tt->moff < moff + posx_max) tt++;
                tt->xoff -= avail;
                spreadsome = TRUE;
                }
              }

            lastrightO = nextrightO;
            nextleftO = nextrightO = 0;
            hadolay = FALSE;
            previousO = this;
            }

          moff += length;
          }

        /* Deal with text items - only interested in underlay, and then only in
        syllables which aren't just "=". */

        else if (type == b_text)
          {
          b_textstr *t = (b_textstr *)p;
          int flags = t->flags;

          if ((flags & text_ul) != 0 &&
              (t->ulen != 1 || t->string[0] != '='))
            {
            int w = 0;
            int leftx, rightx, j;
            int fontsize = mac_muldiv(main_stavemagn,
              ((curmovt->fontsizes)->fontsize_text)[t->size], 1000);
            int *matrix = ((curmovt->fontsizes)->fontmatrix_text)[t->size];
            BOOL same = TRUE;

            uschar ss[256];
            uschar *pp = t->string;
            uschar *qq = ss;
            uschar *cc = ss;

            leftx = t->x;

            if (matrix != NULL) memcpy(font_transform, matrix, 4*sizeof(int));

            /* Have to check through and mirror the stuff done for centring. */

            i = 0;
            for (j = 0; j < 2; j++)
              {
              int k;
              for (; i < t->ulen && *pp != '^'; i++)
                {
                if (*pp == '\\')
                  {
                  int dummy1, dummy2, len;
                  uschar *rr = pp;
                  uschar dummy3[80];
                  pp = string_escape(pp+1, dummy3, &dummy1, &dummy2);
                  len = pp - rr;
                  Ustrncpy(qq, rr, len);
                  qq += len;
                  i += len - 1;
                  }
                else if (*pp == '#') { *qq++ = ' '; pp++; } else *qq++ = *pp++;
                }
              *qq = 0;

              if (i >= t->ulen || j == 1) break;

              for (k = i+1; k < t->ulen; k++) if ((t->string)[k] == '^') break;
              if (k >= t->ulen) break;

              leftx -= string_width(ss, t->font, fontsize);
              cc = qq;
              pp++;
              i++;
              }

            /* Centre if underlay style 0 or if covering one note only or if
            explicitly requested via ^. */

            if (curmovt->underlaystyle == 0 ||
                 (*pp != '=' && (*pp != '-' || pp[1] != '=')))
              {
              w = string_width(cc, t->font, fontsize);
              if (w != 0) leftx += 3*main_stavemagn - w/2;

              if (*pp == '^')
                {
                same = FALSE;
                pp++;
                for (i++; i < t->ulen; i++)
                  {
                  if (*pp == '\\')
                    {
                    int dummy1, dummy2, len;
                    uschar *rr = pp;
                    uschar dummy3[80];
                    pp = string_escape(pp+1, dummy3, &dummy1, &dummy2);
                    len = pp - rr;
                    Ustrncpy(qq, rr, len);
                    qq += len;
                    i += len - 1;
                    }
                  else if (*pp == '#') { *qq++ = ' '; pp++; }
                    else *qq++ = *pp++;
                  }
                *qq = 0;
                }
              }
            else same = FALSE;

            /* Cut off trailing spaces, but not if they were originally
            # characters. */

            pp = t->string + t->ulen;
            while (qq > ss && qq[-1] == ' ' && pp[-1] != '#')
              {
              qq--;
              pp--;
              same = FALSE;
              }
            *qq = 0;

            /* Fontsize/4 is the space to the next syllable */

            rightx = leftx + fontsize/4 +
              (same? w : string_width(ss, t->font, fontsize));

            /* Correct for leading spaces, but not if they were originally
            # characters. */

            if (*ss == ' ')
              {
              pp = t->string;
              qq = ss;
              while (*pp++ != '#' && *qq++ == ' ');  /* Test order matters */
              *qq = 0;
              leftx += font_stringwidth(ss, t->font, fontsize);
              }

            /* Keep maximum for verses, separately for under- and overlay */

            if ((flags & text_above) != 0)
              {
              if (nextleftO > leftx) nextleftO = leftx;
              if (nextrightO < rightx) nextrightO = rightx;
              hadolay = TRUE;
              }
            else
              {
              if (nextleftU > leftx) nextleftU = leftx;
              if (nextrightU < rightx) nextrightU = rightx;
              hadulay = TRUE;
              }

            font_reset();
            }
          }

        /* Deal with resets */

        else if (type == b_reset)
          {
          previousO = page_postable;
          previousU = page_postable;
          hadulay = FALSE;
          hadolay = FALSE;

          nextleftU = 0;
          nextleftO = 0;
          nextrightU = 0;
          nextrightO = 0;
          lastrightU = 0;
          lastrightO = 0;
          moff = 0;
          }

        /* Move on to next item */

        p = (bstr *)((uschar *)p + length_table[type]);
        type = p->type;
        }
      }    /* Block for processing a stave's data */
    }      /* End of per-stave loop */


  if (spreadsome && (main_tracepos == (-1) || main_tracepos == page_barnumber))
    {
    workposstr *t;
    debug_printf("BAR %b UNDERLAY SPREAD POSITIONS:\n", page_barnumber);
    for (t = page_postable; t <= page_posptr; t++)
      debug_printf("%6d %6d\n", t->moff, t->xoff);
    }
  }


/* End of passes through the data. Do some final adjustments. */


/* If the bar ends with a double bar line, allow space for it */

if (doublebar) page_posptr->xoff += 1600;
  else if (page_barnumber >= curmovt->barcount && !curmovt->unfinished)
    page_posptr->xoff += 2000;

/* If the bar starts with an accidental position, we can reduce the initial
starting position to be nearer the bar line. */

if (!page_startlinebar && page_postable->auxid == posx_acc &&
  page_barlinewidth > 3000)
  {
  int notepos = page_postable->xoff + (page_postable+1)->xoff;
  if (notepos > page_barlinewidth - 3000)
    notepos = page_barlinewidth - 3000;
  page_postable->xoff -= notepos;
  }

/* If the bar starts with a clef, we can reduce the initial starting position
to be nearer the bar line. This does not happen in conventional music, but is
possible after an incipit and other special cases. We also add space after the
clef if the next thing is a note. Finally, include the startline spacing
parameters for the clef and any following signatures. */

if (page_postable->auxid == posx_clef && !page_startlinebar)
  {
  workposstr *t = page_postable;
  if (page_barlinewidth > 2000)
    {
    int adjust = page_barlinewidth - 2000;
    page_postable->xoff -= adjust;
    if (page_postable[1].auxid == 0) page_postable[1].xoff += adjust;
    }

  page_postable->xoff += page_startline->clefspace;

  while (++t <= page_posptr && posx_keyfirst <= t->auxid && t->auxid <= posx_timelast)
    {
    if (t->auxid <= posx_keylast) t->xoff += page_startline->keyspace;
      else t->xoff += page_startline->timespace - 4*largestmagn;
    }

  /***  This would make the spacing as at line start, but stretching makes it
  look bad. If ever the stretching is changed so as not to move the first note
  when it follows other things, instate this, and the same below.

  if (t <= page_posptr) t->xoff += 3*largestmagn + page_startline->notespace;
  ***/
  }

/* If the bar starts with key and/or time signatures, we can reduce the initial
starting position to be nearer the bar line (provided the barlinewidth is large
enough), and reduce any gaps between them. However, we must increase the
position if the previous bar ended with a wide barline, or if a double barline
is going to be generated for a key signature.

The keyspace and timespace values are inserted before the first signature,
depending on the type.

We must also set the special width used for printing warning bars at the ends
of lines. At the start of a line, we make the reduction for any signature,
since the presence of an entry indicates a second signature. */

else if (page_postable->auxid == posx_keyfirst ||
         page_postable->auxid == posx_timefirst)
  {
  workposstr *t = page_postable + (page_startlinebar? 0:1);

  page_postable->xoff += (page_postable->auxid == posx_keyfirst)?
    curmovt->keyspacing : curmovt->timespacing;

  /* Move back start for wide enough barline spacing */

  if (page_barlinewidth > 3000)
    page_postable->xoff += 3000 - page_barlinewidth;

  /* Move forward start if wide bar line */

  if (Oldlastendwide ||
      (page_postable->auxid == posx_keyfirst && curmovt->keydoublebar &&
       !Oldlastenddouble))
    page_postable->xoff += 2000;

  /* Handle multiple signatures and compute the special width. */

  page_xxwidth += page_postable->xoff;

  for (; t <= page_posptr && 
         t->auxid >= posx_keyfirst &&
         t->auxid <= posx_timelast; t++)
    {
    if (t->auxid <= posx_keylast)
      {
      t->xoff -= 3*largestmagn;
      if (page_warnkey) page_xxwidth += t->xoff; 
      }
    else
      {
      t->xoff += page_startline->timespace - 4*largestmagn;
      if (page_warntime) page_xxwidth += t->xoff; 
      }
    }

  /* Add in space for the final item. MaxTimeWidth has extra space added to it 
  which seems to be too much in the case when a key signature could have been 
  present, but was suppressed by [nowarn]. In that case (only), we reduce the 
  value. This is a fudge because I don't want to mess with the rest of the code 
  when adding the independent [nowarn] facility. */

  if (!page_warnkey && MaxKeyWidth > 0) MaxTimeWidth -= 8000;
  
  page_xxwidth += (page_warnkey && page_warntime)?
    ((MaxKeyWidth > MaxTimeWidth)? MaxKeyWidth:MaxTimeWidth) :
    (page_warnkey? MaxKeyWidth : MaxTimeWidth); 
    
  /* Add notespace to midline bars */

  /***  This would make the spacing as at line start, but stretching makes it
  look bad. If ever the stretching is changed so as not to move the first note
  when it follows other things, instate this.

  if (!page_startlinebar && t <= page_posptr)
    t->xoff += 3*largestmagn + page_startline->notespace;
  ****/

  /* If the keys+times are followed by a repeat, bring it nearer too, and if
  the thing following that is an accidental, it can come nearer. Also if a time
  (but not key) signature is followed by an accidental, close the gap slightly.
  */

  if (t <= page_posptr)
    {
    if (t->auxid == posx_RLright)
      {
      (t++)->xoff -= 2000;
      if (t <= page_posptr && t->auxid == posx_acc) t->xoff -= 2000;
      }
    else if (posx_timefirst <= (t-1)->auxid && (t-1)->auxid <= posx_timelast &&
      t->auxid == posx_acc) t->xoff -= 2000;
    }
  }

/* We now have to check up on grace notes preceding notes with accidentals. If
the grace notes are on staves that do not have accidentals, we do not need to
leave more space between the grace notes and the accidentals. This copes with
several common cases, but it does not do the complete job. */

for (left = page_postable; left < page_posptr; left++)
  {
  workposstr *right = left + 1;
  if (right->auxid == posx_acc && left->auxid >= posx_gracefirst &&
    left->auxid <= posx_gracelast &&
      (left->posstaves & right->posstaves) == 0)
        {
        right->xoff -= (right+1)->xoff;
        if (right->xoff < 0) right->xoff = 0;
        }
  }

/* So far we have been working with offsets between the notes, but the final
result must have offsets from the start of the bar. At the same time we can
incorporate the values of any [space] directives. */

page_postable->xoff += page_postable->space;
for (left = page_postable + 1; left <= page_posptr; left++)
  left->xoff += left->space + (left-1)->xoff;


/* Debugging output */

if (main_tracepos == (-1) || main_tracepos == page_barnumber)
  {
  workposstr *t;
  debug_printf("BAR %b FINAL POSITIONS:\n", page_barnumber);
  debug_printf("%6d %6d %6d\n", page_postable->moff, 0, page_postable->xoff);
  for (t = page_postable + 1; t <= page_posptr; t++)
    debug_printf("%6d %6d %6d\n", t->moff, t->xoff - (t-1)->xoff, t->xoff);
  if (forcenewline != b_End) debug_printf("!! Newline forced !!\n");
  }


/* Now copy the retained data - (moff, xoff) pairs - into a vector which is
attached to the bar's data structure. */

left = page_postable;
pos_bp->count = page_posptr - page_postable + 1;
outptr = pos_bp->vector = store_Xget(pos_bp->count * sizeof(posstr));

while (left <= page_posptr)
  {
  outptr->moff = left->moff;
  (outptr++)->xoff = (left++)->xoff;
  }

/* Normally, return the width of the bar, up to the bar line; if a new line or
page is being forced, return a large number. */

if (forcenewline == b_End) return page_posptr->xoff; else
  {
  if (forcenewline == b_newpage) page_newpagewanted = TRUE;
  return 10000000;
  }
}

/* End of postable.c */