
/*
 * 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 "stats.h"


void print_cdf (where,comp)
FILE *where;
unsigned short comp;
{
    unsigned short first = TRUE;
    unsigned long i;
    double yval;
    double prevy;

    if (where == NULL)
	return;
    prevy = comp ? 1.0 : 0.0;
    for (i = 0; i < num_samples; i++)
    {
        yval = ((double)i + 1.0) / (double)num_samples;
        if (comp)
            yval = 1.0 - yval;
        if (first && 
            (((i + 1) == num_samples) || (sample [i] != sample [i + 1])))
        {
	    fprintf (where,"%f %f\n", sample [i], prevy);
	    fprintf (where,"%f %f\n", sample [i], yval);
        }
        else if (first ||
                 ((i + 1) == num_samples) ||
                 (((i + 1) < num_samples) && (sample [i] != sample [i + 1])))
        {
            fprintf (where,"%f %f\n", sample [i], 
                     (first && (sample [i] == sample [i + 1])) ? prevy : yval);
            first = first ? FALSE : TRUE; 
        }
        prevy = yval;
    }
}


void do_cdf (comp)
unsigned short comp;
{
    FILE *ofp;
    char *outfile;
    unsigned short flag = 0;

    if ((outfile = strtok (NULL," ")) != NULL)
    {
	if ((ofp = fopen (outfile,"w")) == NULL)
	{
	    fprintf (stderr,"cannot open file: %s\n", outfile);
	    if (script_file)
		exit (1);
	    return;
	}
	flag = 1;
    }
    else
	ofp = stdout;
    print_cdf (ofp,comp);
    if (flag)
	fclose (ofp);
}


void cmd_cdf ()
{
    do_cdf (FALSE);
}


void cmd_ccdf ()
{
    do_cdf (TRUE);
}
