/*
 * program pgmtoepm - convert any number of Portable GrayMap to 
 *                    Extented Pixmap Format epm
 *
 * (C) by Oliver Vogel (e-mail: vogel@ikp.uni-koeln.de)
 * April 5th, 1997
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public Licence as by published
 * by the Free Software Foundation; either version 2; or (at your option)
 * any later version
 *
 * This program is distributed in the hope that it will entertaining,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILTY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * $Id: pgmtoepm.c,v 1.1 1999/04/04 11:48:24 xblast Exp $
 * $Log: pgmtoepm.c,v $
 * Revision 1.1  1999/04/04 11:48:24  xblast
 * Initial revision
 *
 */

#include <stdio.h>
#include <stdlib.h>

#ifdef __STDC__
int 
main (int argc, 
      char*argv[])
#else
int
main (argc, argv)
  int argc;
  char *argv[];
#endif
{
  static char magic[256];
  int width, height, maxval;
  int d_width, d_height, d_maxval;
  int i, n_data;
  FILE *fp;
  char dummy;
  char *buf;

  /* check command line args */
  if (argc <= 1) {
    fprintf(stderr, "usage: %s pgmfile [...]\n", argv[0]);
    return 1;
  }

  for (i=1; i<argc; i++) {
    /* open first pgm file */
    if (NULL == (fp = fopen(argv[i],"r") ) ) {
      fprintf(stderr, "%s: failed to open file \"%s\"\n", argv[0], argv[i]);
      return 1;
    }
    /* read header */
    fscanf(fp, "%s %d %d %d%c", magic, &width, &height, &maxval, &dummy);
    /* compare magic word */
    if (0 != strcmp("P5",magic)) {
      fprintf(stderr, "%s: wrong magic word in file \"%s\"\n", argv[0], argv[i]);
      return 1;
    }
    if (i==1) {
      /* set default values */
      d_height = height;
      d_width  = width;
      d_maxval = maxval;
      n_data   = d_width * d_height;
      /* alloc data buffer */
      if (NULL == (buf = malloc(n_data*sizeof(char) ) ) ) {
	fprintf(stderr, "%s: failed to alloc data buffer\n", argv[0]);
	return 1;
      }
      /* write header */
      printf("PX\n");
      printf("%d %d %d %d\n", d_width, d_height, d_maxval, argc-1);
    } else {
      /* compare with default values */
      if ( (d_height != height) || (d_width != width) || (d_maxval != maxval) ) {
	fprintf(stderr, "%s: wrong image dimensions for file \"%s\"\n", 
		argv[0], argv[i]);
	return 1;
      }
    }
    /* copy data */
    if (n_data != fread(buf, sizeof(char), n_data, fp) ) {
      fprintf(stderr, "%s: premature end of file \"%s\"\n", argv[0], argv[1]);
      return 1;
    }
    fwrite (buf, sizeof(char), n_data, stdout);
  }

  return 0;
}
