
#include "comdefs.h"    /* global variables for lattice fields */

int reposition(FILE *f,int nmeas);

/**************************************************
 * Set up the system for one run
 */

FILE * setup_files(int restart, char *name, int nmeas, int mea, int *sync)
{
  e_header h;
  FILE *f;

  if (this_node == 0) {
    if (!restart) {

      h.headerid = E_HEADER_ID;
      h.headersize = sizeof(e_header);

      h.lx = lattice.size[XUP]; h.ly = lattice.size[YUP]; 
      h.lz = lattice.size[ZUP]; h.lt = 1;
#if NDIM == 4
      h.lt = lattice.size[TUP];
#endif

      h.n_float = nmeas;
      h.n_long = h.n_double = h.n_char = 0;

      f = fopen(name,"w+");
      fwrite(&h,sizeof(e_header),1,f);
      *sync = 0;
      return(f);
    } else {

      f = fopen(name,"r+");
      if (f == NULL) { 
	printf(" *** File %s does not exist?\n",name);
	exit(0);
      }
      printf(" - Repositioning %s to position %d\n",name,mea);

      *sync = reposition(f,mea)
      return( f );
    }
  } /* this_node == 0 */
}

/**************************************************
 * this routine repositions the measurement-files
 */

int reposition(FILE *f,int nmeas)
{
  e_header h;
  int length;
  int l,j;
  char *cbuf;

  fread(&h,sizeof(e_header),1,f);
  j = 0;
  length = h.n_double*sizeof(double) +
    h.n_long*sizeof(long) + h.n_float*sizeof(float) +h.n_char*sizeof(char);
  cbuf = (char *)malloc(length);

  while (j<nmeas) {
    fread(cbuf,sizeof(char),length,f);
    fread(&l,sizeof(int),1,f);
    if (l != ++j) {
      printf(" block %d, flag %d\n",j,l);
      halt(" *** sync error in file");
    }
  }
  free(cbuf);

  /* also flush the file - just in case */
  l = ftell(f);
  fflush(f);
  fseek(f,l,SEEK_SET);

  return(j);
}
