/* imagepdf.c
 * Copyright (C) 1997-98 Thomas Merz. All rights reserved.
 *
 * Convert TIFF/GIF/JPEG images to PDF
 */

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

#ifdef POSIX
#include <unistd.h>
#endif

#ifdef DOS
#include <process.h>
#endif

#ifdef NeXT
#include <libc.h>	/* for getopt(), optind, optarg */
#endif

#include "pdf.h"

static void
usage(void)
{
    fprintf(stderr, "imagepdf - Convert ");
#ifdef USE_TIFF
    fprintf(stderr, "TIFF/");
#endif
    fprintf(stderr, "GIF/JPEG images to PDF. (C) Thomas Merz 1997\n");
    fprintf(stderr, "usage: imagepdf [options] imagefile(s)\n");
    fprintf(stderr, "Available options:\n");
    fprintf(stderr, "-a         ASCII mode (default: binary)\n");
    fprintf(stderr, "-c         print caption\n");
    fprintf(stderr, "-o <file>  output file\n");

    exit(1);
}

void
main(int argc, char *argv[])
{
    PDF_info	*info;
    FILE	*pdffile = NULL;
    PDF		*p;
    PDF_image	*image;
    int		opt;
    bool	caption = false;
    float	scale;
    
    info		= PDF_get_info();
    info->binary_mode	= true;
    info->Creator       = "imagepdf";

    while ((opt = getopt(argc, argv, "ao:")) != -1)
	switch (opt) {
	    case 'a':
		info->binary_mode = false;
		break;

	    case 'c':
		caption = true;
		break;

	    case 'o':
		if ((pdffile = fopen(optarg, WRITEMODE)) == NULL) {
		    fprintf(stderr, 
		        "Error: cannot open output file %s.\n", optarg);
		    exit(1);
		}
		break;
	}

    if (optind == argc) {
	fprintf(stderr, "Error: no image files given.\n");
	usage();
    }

    if (pdffile == NULL) {
	fprintf(stderr, "Error: no output file given.\n");
	usage();
    }

    p = PDF_open(pdffile, info);

    while (optind++ < argc) {
	fprintf(stderr, "Processing image file %s...\n", argv[optind-1]);

	if ((image = PDF_open_GIF(p, argv[optind-1])) == NULL &&
#ifdef USE_TIFF
	    (image = PDF_open_TIFF(p, argv[optind-1])) == NULL &&
#endif
	    (image = PDF_open_JPEG(p, argv[optind-1])) == NULL) {
		fprintf(stderr,"Error: Couldn't analyze image %s - skipped.\n",
			    argv[optind-1]);
	    continue;
	}

	scale = 1.0;

	PDF_begin_page(p, image->width * scale, image->height * scale);
	
	/* define outline with filename */
	PDF_add_outline(p, image->filename);

	PDF_place_image(p, image, 0.0, 0.0, scale);
	PDF_close_image(p, image);

	PDF_end_page(p);
    }

    PDF_close(p);
    exit(0);
}
