/*-=-=-=-=-=-=-=-=-=-=-=- RCCL/RCI Notice of Copyright -=-=-=-=-=-=-=-=-=-=-*
 *									    *
 *	Copyright (C) 1987, 1991 by John E. Lloyd and Michael C. Wrinn.	    *
 *									    *
 *	Information on copyright permissions, as well as a complete	    *
 *	disclaimer of warranty, is given in the file COPYRIGHT.		    *
 *									    *
 *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/


#include <stdio.h>
#include <math.h>

#include "../h/fastmath.h"
#include "../h/cputime.h"

#define PI   3.14159265359

#define	COMMAND(s)	(strcmp (key_buf, s) == 0)
#define	COMMANDS(s)	(strncmp (key_buf, s, strlen(s)) == 0)
char key_buf [256];

float atan2_T();

main()
{
	char *keytree, *tree_match_parse(), *tree_match_err_at();

	int numTimes, intervalDivide, angleRange, i, j;
	float theta, X, Y;

	keytree = tree_match_parse("					\
(	exit								\
	test 								\
	 ([ATAN2]						\
	  (%d",&angleRange,",0,,	\"angle range (degrees)\"	\
	   (%d",&numTimes,",0,,		\"number of samples\")))	\
	time 								\
	 ([atan2 ATAN2]						\
	  (%d",&numTimes,",0,,		\"number of iterations\"))	\
	run								\
	 ([ATAN2]						\
	  (%f",&Y,",,,		\"y value\"				\
	   (%f", &X, ",,,	\"x value\")))				\
)",0);
	if (keytree == 0)
	 { printf ("ERROR/Parse error at %.30s\n", tree_match_err_at());
	   exit (-1);
	 }

	do
 	 { tree_match (keytree, "ATAN2 TEST> ", key_buf);

	   if (COMMANDS("test"))
	    { double maxDiff = 0.;
	      double check, theta;
	      float result;
	      int i;

	      if (numTimes < intervalDivide)
	       { printf (
"ERROR/ num iterations should exceed num interval divisions\n");
		 continue;
	       }
	      if (COMMAND("test ATAN2"))
	       { double s, c;
		 for (i = -numTimes/2 ; i <= numTimes/2; i++)
	          {
		    theta = (i * PI * 2 * angleRange) / (numTimes * 180.);
		    s = sin(theta);
		    c = cos(theta);

	 	    result = ATAN2 (s, c);
		    check = atan2 (s, c);
		    if (fabs (result-check) > maxDiff)
		     { maxDiff = fabs(result-check);
		     }
		  }
	       }
	      printf ("Maximum error = %lg\n", maxDiff);
	    }
	   else if (COMMANDS ("time"))
	    { double startTime, stopTime;
	      double result;
	      double theta = 1.2345;
	      register int i;
	      startTime = cputime (User);
	      
	      if (COMMAND ("time atan2"))
	       { double s, c;
		 s = sin (theta);
	 	 c = cos (theta);
	         for (i=numTimes; i>0; i--)
		  { result = atan2 (s, c);
		  }
	       }
	      else if (COMMAND ("time ATAN2"))
	       { double s, c;
		 s = sin (theta);
	 	 c = cos (theta);
	         for (i=numTimes; i>0; i--)
		  { result = ATAN2 (s, c);
		  }
	       }
	      stopTime = cputime (User);
	      printf ("Execution time = %lg micro seconds\n", 
		       (stopTime - startTime) * 1000000. / numTimes);
	    }
	   else if (COMMAND ("run ATAN2"))
	    { printf ("%g\n", 180. / PI * ATAN2 (Y, X));
	    }
	 }
	while (!(COMMAND("exit")));
}
