/* outbuff.c -- Support code for outBuff class

   Random access buffer for output in iterpeds() loop of parallel
   MLINK and LINKMAP.  Output from iterations on different processors
   is buffered so it can be written out in the specific order
   intended, as opposed to the order it is produced. */

#include "commondefs.h"

/* outBuff object "constructor".
   Determines the number of calls to iterpeds(), and allocates space
   for an array of strBuffs. */
outBuff* newOutBuff()
{
  int i;
  outBuff* newBuff;

  /* Allocate space for our buffer */
#if PARALLEL
  newBuff = (outBuff*) Tmk_malloc(sizeof(outBuff));
  if (newBuff == NULL)
    Tmk_errexit("MALLOC ERROR - newOutBuff\n");
  newBuff->numIpeds = numIpeds;
  newBuff->ipeds =
    (strBuff**) Tmk_malloc(numIpeds * sizeof(strBuff*));
  if (newBuff->ipeds == NULL)
    Tmk_errexit("MALLOC ERROR - newBuff->ipeds");
#else  /* if PARALLEL */
  newBuff = (outBuff*) malloc(sizeof(outBuff));
  if (newBuff == NULL)
    errExit("couldn't malloc newBuff");
  newBuff->numIpeds = numIpeds;
  newBuff->ipeds =
    (strBuff**) calloc(numIpeds, sizeof(strBuff*));
  if (newBuff->ipeds == NULL)
    errExit("couldn't malloc newBuff->ipeds");
#endif  /* if PARALLEL */
  
  for (i = 0; i < numIpeds; i++)
    newBuff->ipeds[i] = newStrBuff();

  return newBuff;
}


/* initialize outBuffs for all 3 outfiles */
void initOutBuffs()
{
  stdoutBuff = newOutBuff();
  outfileBuff = newOutBuff();
  streamBuff = newOutBuff();

#if PARALLEL
  Tmk_distribute((char*) &stdoutBuff, sizeof(stdoutBuff));
  Tmk_distribute((char*) &outfileBuff, sizeof(outfileBuff));
  Tmk_distribute((char*) &streamBuff, sizeof(streamBuff));
#endif  /* if PARALLEL */
}


/* write an outBuff out to its appropriate file  */
void writeBuff(oBuff, f)
outBuff* oBuff;
FILE* f;
{
  int i;
  for (i = 0; i < numIpeds; i++)
    fprintf(f, oBuff->ipeds[i]->string);
}


/* write all three buffd files out */
void writeOutBuffs()
{
  writeBuff(stdoutBuff, stdout);
  writeBuff(outfileBuff, outfile);
  writeBuff(streamBuff, stream);
}


