# include "addstar.h"
# define D_NSTARS 1000
# define BYTES_STAR 66
# define BLOCK 1000

Stars *rtext (FILE *f, unsigned int *nstars) {

  int j, N, Nextra, Ninstar, Nskip, Nbytes, nbytes;
  int done;
  char *buffer, *c, *c2;
  double tmp;
  Stars *stars;
  
  /* load in stars by blocks of 1000 */
  N = 0;
  ALLOCATE (buffer, char, (BLOCK*BYTES_STAR) + 1);
  buffer[BLOCK*BYTES_STAR] = 0;
  Nextra = 0;

  ALLOCATE (stars, Stars, *nstars);

  while (N < *nstars) {
    /* load next data block */
    Nbytes = BYTES_STAR * BLOCK - Nextra;
    nbytes = fread (&buffer[Nextra], 1, Nbytes, f);
    if (nbytes == 0) {
      *nstars = N;
      return (stars);
    }
    nbytes += Nextra;

    /* check line-by-line integrity */
    c = buffer;
    done = FALSE;
    while ((c < buffer + nbytes) && (!done)) { 
      for (c2 = c; *c2 == '\n'; c2++);
      if (c2 > c) { /* extra return chars */
	memmove (c, c2, (int)(buffer + nbytes - c2));
	Nskip = c2 - c;
	nbytes -= Nskip;
	bzero (buffer + nbytes, Nskip);
	if (VERBOSE) fprintf (stderr, "deleted %d extra return chars\n", Nskip);
      }
      c2 = strchr (c, '\n');
      if (c2 == (char *) NULL) {
	done = TRUE;	
	continue;
      }
      c2++;
      if ((c2 - c) != BYTES_STAR) { /* bad line, delete it */
	memmove (c, c2, (int)(buffer + nbytes - c2));
	Nskip = c2 - c;
	nbytes -= Nskip;
	bzero (buffer + nbytes, Nskip);
	if (VERBOSE) fprintf (stderr, "deleted line, %d extra chars\n", Nskip);
      } else {
	c = c2;
      }
    }

    /* extract data for stars */
    Ninstar = nbytes / BYTES_STAR;
    Nextra = nbytes % BYTES_STAR;
    for (j = 0; (j < Ninstar) && (N < *nstars); j++, N++) {
      dparse (&stars[N].X,  1, &buffer[j*BYTES_STAR]);
      dparse (&stars[N].Y,  2, &buffer[j*BYTES_STAR]);
      dparse (&stars[N].M,  3, &buffer[j*BYTES_STAR]);

      /* cmp files carry dM in millimags */
      dparse (&tmp, 4, &buffer[j*BYTES_STAR]);
      stars[N].dM = 0.001*tmp;

      dparse (&tmp,         5, &buffer[j*BYTES_STAR]);
      stars[N].dophot = tmp;

      dparse (&stars[N].Mgal, 7, &buffer[j*BYTES_STAR]);
      dparse (&stars[N].Map,  8, &buffer[j*BYTES_STAR]);
      dparse (&stars[N].fx,   9, &buffer[j*BYTES_STAR]);
      dparse (&stars[N].fy,  10, &buffer[j*BYTES_STAR]);
      dparse (&stars[N].df,  11, &buffer[j*BYTES_STAR]);
    }
  }
  *nstars = N;
  return (stars);
}
