

/* Copyright (c) 1995 Greg Klanderman & MIT.  All Rights Reserved.
 *
 * Use, reproduction and preparation of derivative works of this software is
 * permitted.  Any copy of this software or of any derivative work must
 * include both the above copyright notices of Greg Klanderman & MIT and this
 * paragraph.  This software is made available AS IS, and MIT
 * disclaims all warranties, express or implied.
 */


#include <stdio.h>
#include <math.h>

#include "clarg.h"
#include "image.h"
#include "string-support.h"


static char *USAGE =
  "\n%s:  Image Downsample (no filtering)\n"
  "\n"
  "Arguments are:\n"
  "   -input  file:        Specify the input file name (PFM)\n"
  "   -output file:        Specify the output file name (PBM or PFM)\n"
  "   -down dx [dy]:       Specify the downsampling factors (default 2, or 1 if -dt specified))\n"
  "   -dt dt:              Downsample in time by factor dt (default 1)\n"
  "\n"
  "If no input file is specified, input is from stdin, and if no output file\n"
  "is specified, output is to stdout.\n\n";

#define INPUT    "i.nput"
#define OUTPUT   "o.utput"
#define DOWN     "d.own"
#define DOWNT    "dt"

static CLINIT clinit[] = {{INPUT,    1, 1, NULL,    0},
			  {OUTPUT,   1, 1, NULL,    0},
			  {DOWN,     1, 2, cl_int,  0},
			  {DOWNT,    1, 1, cl_int,  0},
			  {NULL,     1, 1, NULL,    0}};

static char *depend[] = {"!(UNNAMED && "INPUT")", NULL};


int main(int argc, char **argv, char **envp)
{
  AnyImage img, out;
  int imno;
  char *infile, *outfile;
  String msg = NULLSTRING;
  int downx, downy, downt;
  

  if (cl_init(argc, argv, envp, clinit, depend, USAGE, CL_NORESTRICT))
    return 0;

  infile   = (cl_opt(INPUT)
	      ? cl_arg1(INPUT)
	      : cl_opt(CL_UNNAMED) ? cl_arg1(CL_UNNAMED) : NULL);
  outfile  = cl_opt(OUTPUT) ? cl_arg1(OUTPUT) : NULL;
  downx    = cl_opt(DOWN) ? atoi(cl_arg1(DOWN)) : (cl_opt(DOWNT) ? 1 : 2);
  downy    = (cl_opt(DOWN) && cl_numarg(DOWN) == 2) ? atoi(cl_arg2(DOWN)) : downx;
  downt    = cl_opt(DOWNT) ? atoi(cl_arg1(DOWNT)) : 1;

  imno = 0;                                  /* read in image(s) */
  while ((imno == 0 || infile == NULL) &&
         (img = imLoad(IMAGE_ANY, infile))) {

    if (imno % downt == 0) {
      out = imDown(img, downx, downy);

      imDocString(out) = strNewComment(argc, argv, envp, imDocString(img), NULLSTRING);

      msg = strPrintF(NULL, "\n >>\n >>     Downsampling:  x:%d, y:%d, t:%d",
                      downx, downy, downt);
      strCat(imDocString(out), msg);
      strFree(msg);

      if (imSave(out, outfile)) {
        fprintf(stderr, "DOWNSAMPLE: Unable to save image\n");
      }

      imFree(out);
    }

    imFree(img);
    imno++;
  }  

  if (imno == 0) {                          
    fprintf(stderr, "DOWNSAMPLE: Error reading input\n");
    return 0;
  }

  return 0;
}


