
/*
 * Copyright (c) 2001 BBNT Solutions LLC
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for any purpose is hereby granted without
 * fee, provided that the above copyright notice and this permission
 * appear in all copies and in supporting documentation, and that the
 * name of BBN Technologies not be used in advertising or publicity
 * pertaining to distribution of the software without specific,
 * written prior permission.  BBN makes no representations about the
 * suitability of this software for any purposes.  It is provided "AS
 * IS" without express or implied warranties.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"

#define FALSE           0
#define TRUE            1

FILE *ofp = NULL;
unsigned short ratio = FALSE;
unsigned short dump_data_too = FALSE;
unsigned short initial = FALSE;
double initial_val;


void usage (progname)
char *progname;
{
    fprintf (stderr,"usage: %s ", progname);
    fprintf (stderr,"[-d] [-r] [i X] [-o outfile] [- | input_file(s)]\n");
    exit (1);
}


void dump_version ()
{
    fprintf (stdout,"\ndumpdiff v%s\n", VERSION);
    fprintf (stdout,"Mark Allman (mallman@icir.org)\n\n");
    exit (0);
}


void dump_diff (val)
double val;
{
    static unsigned short first = TRUE;
    static double lastv;
    double diff;

    if (first)
    {
        first = FALSE;
        if (initial)
            lastv = initial_val;
        else
        {
            lastv = val;
            return;
        }
    }
    if (ratio)
    {
        if ((lastv == 0) || (val == 0))
            diff = 0;
        else
            diff = val / lastv;
    }
    else
        diff = val - lastv;
    if (dump_data_too)
        fprintf (ofp,"%f ", val);
    fprintf (ofp,"%f\n",diff);
    lastv = val;
}


int main (argc,argv)
int argc;
char *argv [];
{
    int i;

    set_process_func (dump_diff);
    if (argc == 1)
	usage (argv [0]);
    for (i = 1; i < argc; i++)
	if (!strcmp (argv [i],"-h"))
	    usage (argv [0]);
	else if (!strcmp (argv [i],"-v") || !strcmp (argv [i],"--version"))
	    dump_version ();
	else if (!strcmp (argv [i],"-r"))
	    ratio = TRUE;
        else if (!strcmp (argv [i],"-d"))
            dump_data_too = TRUE;
        else if (!strcmp (argv [i],"-i") && ((i + 1) < argc))
        {
            initial = TRUE;
            initial_val = atof (argv [i + 1]);
        }
	else if (!strcmp (argv [i],"-o"))
	{
	    if (((i + 1) >= argc) || (ofp != NULL))
		usage (argv [0]);
	    if ((ofp = fopen (argv [i + 1],"w")) == NULL)
	    {
		fprintf (stderr,"could not open file %s for writing\n",
			 argv [i + 1]);
		exit (1);
	    }
	}
    if (ofp == NULL)
	ofp = stdout;
    for (i = 1; i < argc; i++)
    {
	if (!strcmp (argv [i],"-r") || !strcmp (argv [i],"-d"))
	    continue;
	if (!strcmp (argv [i],"-o") || !strcmp (argv [i],"-i"))
	{
	    i++;
	    continue;
	}
        process_file (argv [i]);
    }
    fclose (ofp);
    exit (0);
}
