/*************************************************
*    The PMW Music Typesetter - 3rd incarnation  *
*************************************************/

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

/* Written by Philip Hazel, starting November 1991 */
/* This file last modified: December 2010 */


/* 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 MaxKeyTimeWidth = 0;                   /* widest final key or time */
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_warnkeytime = FALSE;         /* no warning key or 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. */

if (page_manyrest >= 2)
  {
  pos_bp->multi = page_manyrest;
  page_posptr->xoff = 50*main_stavemagn;
  }

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;

        /* 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;

        /* 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;

        }   /* 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]] > MaxKeyTimeWidth)
                  MaxKeyTimeWidth = timevector[timevector[0]];
                }
              else if (keyvector[0] > 0)
                {
                if (keyvector[keyvector[0]] > MaxKeyTimeWidth)
                  MaxKeyTimeWidth = 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_warnkeytime |= 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_warnkeytime |= 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 left, right, 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; 
            
            left = 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; 
              
              left -= 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) left += 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 */

            right = left + 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;
              left += font_stringwidth(ss, t->font, fontsize);
              }

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

            if ((flags & text_above) != 0)
              {
              if (nextleftO > left) nextleftO = left;
              if (nextrightO < right) nextrightO = right;
              hadolay = TRUE;
              }
            else
              {
              if (nextleftU > left) nextleftU = left;
              if (nextrightU < right) nextrightU = right;
              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 & compute special width */
   
  page_xxwidth += page_postable->xoff;
 
  while (t <= page_posptr && posx_keyfirst <= t->auxid && t->auxid <= posx_timelast)
    {
    if (t->auxid <= posx_keylast) t->xoff -= 3*largestmagn;
      else t->xoff += page_startline->timespace - 4*largestmagn;      
    page_xxwidth += (t++)->xoff;
    }
  page_xxwidth += MaxKeyTimeWidth;  /* for the final item */
   
  /* 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 */
