
/*
 * 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 <strings.h>
#include <math.h>
#include "stats.h"


void trim_usage ()
{
    fprintf (stderr,"\nusage: trim lower [upper]\n");
    fprintf (stderr," + trim some percentage of data points from the tails\n");
    fprintf (stderr," + if only one number is given it is applied to both");
    fprintf (stderr," tails\n");
    fprintf (stderr," + if the value given is zero the particular tail is");
    fprintf (stderr," left unaltered\n");
    fprintf (stderr,"\n");
}


/* This routine pretty much sucks.  It was easy to write, but is way 
   inefficient.  There are some pointer tricks that we could play that
   would allow us to do this with no copying - but, that might complicate
   the memory allocation / deallocation business.  At the very least we
   should be able to do memory copies in chunks bigger than one double
   at a time.  On the other hand, we have to crunch through to get the
   new totals anyway, so it has not yet been worth fixing to me! 
 */

void do_trim (lower,upper)
short lower, upper;
{
    unsigned long low_chop, up_chop;
    unsigned long i, j;

    low_chop = floor ((lower / 100.0) * num_samples);
    up_chop = num_samples - floor ((upper / 100.0) * num_samples);
    num_samples = up_chop - low_chop;
    total_clear ();
    for (i = low_chop, j = 0; i < up_chop; i++, j++)
    {
	sample [j] = sample [i];
	total_add_sample (sample [j]);
    }
}


void cmd_trim ()
{
    char *lptr, *uptr;
    short lower, upper;
    unsigned short error = FALSE;

    if ((lptr = strtok (NULL," ")) == NULL)
    {
	trim_usage ();
	if (script_file)
	    exit (1);
	return;
    }
    if ((uptr = strtok (NULL," ")) == NULL)
	uptr = lptr;
    lower = atoi (lptr);
    upper = atoi (uptr);
    if ((lower < 0) || (lower > 100))
    {
	fprintf (stderr,"lower trim value %d out of range (0--100)\n", lower);
	error = TRUE;
    }
    if ((upper < 0) || (upper > 100))
    {
	fprintf (stderr,"upper trim value %d out of range (0--100)\n", upper);
	error = TRUE;
    }
    if (error && script_file)
	exit (1);
    else if (error)
	return;
    do_trim (lower,upper);
}
