# include "dvo.h"
# define CHAR_LINE 104
# define NBLOCK 100

int objload (int argc, char **argv) {
  
  int i, nstar, N, Nout, n, Type, type, NSTAR, Nline, status;
  double *X, *Y;
  FILE *f;
  char *buffer, *line;
  int Ximage, Nimage;
  
  Nimage = -1;
  if (N = get_argument (argc, argv, "-n")) {
    remove_argument (N, &argc, argv);
    Nimage = atof (argv[N]);
    remove_argument (N, &argc, argv);
  }
  if (!GetImage (&Ximage, &Nimage)) return (FALSE);

  Type = 0;
  if (N = get_argument (argc, argv, "-t")) {
    remove_argument (N, &argc, argv);
    Type = atof (argv[N]);
    remove_argument (N, &argc, argv);
  }

  if (argc != 3) {
    fprintf (stderr, "USAGE: load (overlay) <filename>\n");
    return (FALSE);
  }

  if (!SelectOverlay (argv[1], &n)) return (FALSE);

  f = fopen (argv[2], "r");
  if (f == (FILE *) NULL) {
    fprintf (stderr, "ERROR: can't find object file %s\n", argv[2]);
    return (FALSE);
  }

  /* read average values from first line */
  ALLOCATE (line, char, 129);
  scan_line (f, line);

  nstar = 0;
  NSTAR = 1000;
  ALLOCATE (X, double, NSTAR);
  ALLOCATE (Y, double, NSTAR);
  ALLOCATE (buffer, char, CHAR_LINE*NBLOCK);

  /* read in data from obj file */
  while ((Nline = fread (buffer, CHAR_LINE, NBLOCK, f)) > 0) {
    for (i = 0; i < Nline; i++) {
      /* we are now using all entries on the *.obj line */
      status = sscanf (&buffer[i*CHAR_LINE], "%d %lf %lf",  &type, &X[nstar], &Y[nstar]);
      if (Type && (Type != type)) continue;
      nstar ++;
      if (nstar == NSTAR) {
	NSTAR += 1000;
	REALLOCATE (X, double, NSTAR);
	REALLOCATE (Y, double, NSTAR);
      }
    }
  }
  fclose (f);
  free (buffer);

  write (Ximage, "LOAD", 4); /* force Ximage to look for the incoming image */
  sprintf (line, "OVER %9d ", n);
  write (Ximage, line, 16);
  
  ALLOCATE (buffer, char, 66000);
  bzero (buffer, 65536);
  for (Nout = i = 0; i < nstar; i++, Nout++) {
    snprintf (&buffer[Nout*128], 129, "%15s %20.10f %20.10f %20.10f %20.10f ", "BOX", X[i], Y[i], 5.0, 5.0);
    if (Nout == 512) {
      sprintf (line, "NLINES  %7d ", Nout);
      write (Ximage, line, 16);
      write (Ximage, buffer, Nout*128);
      bzero (buffer, 65536);
      Nout = -1;
    }
  }

  if (Nout) {
    sprintf (line, "NLINES  %7d ", Nout);
    write (Ximage, line, 16);
    write (Ximage, buffer, Nout*128);
  }
  sprintf (line, "DONE ");
  write (Ximage, line, 16);

  free (X);
  free (Y);

  free (buffer);
  free (line);

  fprintf (stderr, "loaded %d objects\n", nstar);
  return (TRUE);
}

