
/* Copyright (c) 1995 Greg Klanderman and 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 notice and this
 * paragraph.  This software is made available AS IS, and MIT
 * disclaims all warranties, express or implied.
 */

static char rcsid[] = "bin-gregk/strm2imgs.c";

/*   Greg Klanderman    Spring 1995
     
     this program takes a stream of images and writes each to a file
*/

#include <stdio.h>

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


static char *USAGE =
  "\n%s:  Write stream of images to files.\n"
  "\n"
  "Arguments are:\n"
  "   -base file:           Specify the output file name, eg. `foo%%03d.pgm'\n"
  "   -from  l:             Specify the first output image index, default 0.\n"
  "   -by  i:               Specify the index increment, default 1.\n"
  "   -num  n:              Specify the maximum number of images, default all of them.\n"
  "\n\n";


#define BASE 	"b.ase"
#define LOW     "f.rom"
#define INC     "by"
#define NUM     "n.um"


static CLINIT clinit[] = {{BASE,  1,  1, NULL,    0},
			  {LOW,   1,  1, cl_int,  0},
			  {INC,   1,  1, cl_int,  0},
			  {NUM,   1,  1, cl_int,  0},
			  {NULL,  0,  0, NULL,    0}};


static char *depend[] = {BASE, NULL};


int main(int argc, char **argv, char **envp)
{
  AnyImage img;
  int low, num, inc, i, n;
  char *base, *fn;
  String newdoc;
  

  if (cl_init(argc, argv, envp, clinit, depend, USAGE, CL_NORESTRICT))  /* parse args */
    return 0;

  base = cl_arg1(BASE);
  low  = cl_opt(LOW) ? atoi(cl_arg1(LOW)) : 0;
  inc  = cl_opt(INC) ? atoi(cl_arg1(INC)) : 1;
  num  = cl_opt(NUM) ? atoi(cl_arg1(NUM)) : 0xffffff;

  fn = (char *) malloc(strlen(base) + 100);

  if (fn == NULL) {
    fprintf(stderr, "STRM2IMGS: Out of memory\n");
    return -1;
  }
  
  for (n = 0, i = low; (n < num)  &&  (img = imLoadF(IMAGE_ANY, stdin)); i += inc) {
    sprintf(fn, base, i);

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

    if (imSave(img, fn)) {
      fprintf(stderr, "STRM2IMGS: Error saving to \"%s\"\n", fn);
      return -1;
    }
  
    imFree(img);
  }
  
  return 0;
}



