#include "moss.h"

char *me;

void
usage() {
  /*               0    1        2       3        4        5    ... */
  fprintf(stderr, 
	  "usage: %s <imgOut> <points> <which> <img0In> <img1In> ... \n", me);
  exit(1);
}

int
main(int argc, char *argv[]) {
  char *imgStr, *pStr, *whichStr, *outStr;
  FILE *file;
  Nrrd **imgs, *out, *points;
  int i, which, numImgs;

  me = argv[0];
  if (!(argc >= 6))
    usage();
  outStr = argv[1];
  pStr = argv[2];
  whichStr = argv[3];
  numImgs = argc - 4;

  /* get the correspondance points */
  if (!(file = fopen(pStr, "r"))) {
    fprintf(stderr, "%s: couldn't open points \"%s\" for reading\n", 
	    me, pStr);
    usage();
  }
  if (!(points = nrrdNewRead(file))) {
    fprintf(stderr, "%s: trouble reading points \"%s\":\n%s", 
	    me, pStr, biffGet(NRRD));
    usage();
  }
  fclose(file);

  /* which image is the reference?
     (the other image will be reprojected into this one's plane) */
  if (1 != sscanf(whichStr, "%d", &which)) {
    fprintf(stderr, "%s: couldn't parse \"%s\" as int\n", me, whichStr);
    usage();
  }

  /* get input images */
  imgs = (Nrrd **)malloc(numImgs*sizeof(Nrrd*));
  for (i=0; i<=numImgs-1; i++) {
    imgStr = argv[4+i];
    if (!(file = fopen(imgStr, "r"))) {
      fprintf(stderr, "%s: couldn't open image#%d \"%s\" for reading\n", 
	      me, i, imgStr);
      usage();
    }
    if (!(imgs[i] = nrrdNewRead(file))) {
      fprintf(stderr, "%s: trouble reading image#%d \"%s\":\n%s", 
	      me, i, imgStr, biffGet(NRRD));
      usage();
    }
    fclose(file);
  }

  /* can we open the output file */
  if (!(file = fopen(outStr, "w"))) {
    fprintf(stderr, "%s: couldn't open output \"%s\" for writing\n",
	    me, outStr);
    usage();
  }

  /* do the deed */
  if (!(out = mossDoit(imgs, numImgs, which, points))) {
    fprintf(stderr, "%s: trouble computing the mosaic:\n%s", 
	    me, biffGet(MOSS));
    exit(1);
  }

  /* save the output */
  out->encoding = nrrdEncodingRaw;
  if (nrrdWritePNM(file, out)) {
    fprintf(stderr, "%s: trouble writing output \"%s\":\n%s", 
	    me, outStr, biffGet(NRRD));
    exit(1);
  }
  fclose(file);

  /* we're done */
  for (i=0; i<=numImgs-1; i++) {
    nrrdNuke(imgs[i]);
  }
  free(imgs);
  nrrdNuke(points);
  exit(0);
}



