/* pdfgraph.c
 * Copyright (C) 1997-98 Thomas Merz. All rights reserved.
 *
 * A micro language for drawing PDF graphics
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.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, "pdfgraph - draw PDF graph. (C) Thomas Merz 1997-98\n");
    fprintf(stderr, "usage: pdfgraph [options] [datafile]\n");
    fprintf(stderr, "Available options:\n");
    fprintf(stderr, "-b 		binary mode (default: ASCII)\n");
    fprintf(stderr, "-o filename	PDF output file name\n");

    exit(1);
}

#define BUFLEN 512

void
main(int argc, char *argv[])
{
    PDF_info	*info;
    char	buf[BUFLEN], *cmd;
    FILE	*pdffile = NULL, *datafile = stdin;
    PDF		*p;
    int		opt;
    float	page_width = 595, page_height = 842;
    float	x, y, gray;
    float	red, green, blue;

    info		= PDF_get_info();
    info->Title		= "stdin";
    info->Creator       = "pdfgraph";
    info->binary_mode	= false;

    while ((opt = getopt(argc, argv, "bo:")) != -1)
	switch (opt) {
	    case 'b':
		info->binary_mode = true;
		break;
		
	    case 'o':
		pdffile = fopen(optarg, WRITEMODE);
		if (pdffile == NULL) {
		    fprintf(stderr, 
			    "Error: cannot open output file %s.\n", optarg);
		    usage();
		}
		break;

	    case '?':
	    default:
		usage();
	}

    if (pdffile == (FILE *) NULL)
	usage();

    if (optind < argc) {
	info->Title	= argv[optind];
	if ((datafile = fopen(argv[optind], READMODE)) == NULL) {
	    fprintf(stderr, "Error: cannot open data file %s.\n",argv[optind]);
	    exit(1);
	}
    } else
	usage();

    p = PDF_open(pdffile, info);

    PDF_begin_page(p, page_width, page_height);

    while ((cmd = fgets(buf, BUFLEN, datafile)) != NULL) {
	switch (cmd[0]) {
	case 'M':
	    if (sscanf(buf+1, "%f %f", &x, &y) != 2) {
		fprintf(stderr, "Error in line: %s", buf);
		continue;
	    }
	    PDF_moveto(p, x, y);
	    break;

	case 'L':
	    if (sscanf(buf+1, "%f %f", &x, &y) != 2) {
		fprintf(stderr, "Error in line: %s", buf);
		continue;
	    }
	    PDF_lineto(p, x, y);
	    break;

	case 'S':
	    PDF_stroke(p);
	    break;

	case 'f':
	    PDF_fill(p);
	    break;

	case 'F':
	    PDF_fill_stroke(p);
	    break;

	case 'g':
	    if (sscanf(buf+1, "%f", &gray) != 1) {
		fprintf(stderr, "Error in line: %s", buf);
		continue;
	    }
	    PDF_setgray(p, gray);
	    break;

	case 'C':
	    if (sscanf(buf+1, "%f %f %f", &red, &green, &blue) != 3) {
		fprintf(stderr, "Error in line: %s", buf);
		continue;
	    }
	    PDF_setrgbcolor(p, red, green, blue);
	    break;

	case '%':
	default:
	    break;;
	}
    }

    PDF_end_page(p);
    PDF_close(p);

    fclose(datafile);
    exit(0);
}
