//final2

#include <fstream.h>
#include <math.h>
#include <list>

#define FPMIN 1.0e-30  // number near the smallest representable floating-point number

void error(char* message);

//----------

template <class T>
class SpecFunc {};  // base class for special functions

//----------

template <class T>
class Gammln : public SpecFunc<T>  // adapted from Numerical Recipes in C
{
public:
	T operator () (T);  // evaluates the natural log of the gamma function
private:
	static const T cof[]; 
};

//----------

template <class T>
T Gammln<T>::operator () (T xx)
{
	T y = xx;
	T x = xx;
	T tmp = x + 5.5;
	tmp -= (x+0.5) * log(tmp);
	T ser = 1.000000000190015;
	for (int j=0;j<=5;j++)
		ser += cof[j] / ++y;
	return -tmp + log(2.5066282746310005*ser/x);
}

template <class T>
const T Gammln<T>::cof[6] = {76.18009172947146,-86.50532032941677,
	24.01409824083091,-1.231739572450155,
	0.1208650973866179e-2,-0.5395239384953e-5};

//----------

template <class T>
class Gammq : public SpecFunc<T>  // adapted from Numerical Recipes in C
{
public:
	class Gser  // nested class used by Gammq
	{
	public:
		Gser() : ITMAX(100),EPS(3.0e-7) {};
		T operator () (T a,T x)  // evaluates by series representation
		{
			T ap = a;
			T del = 1.0 / a;
			T sum = del;
			for (int n;n<=ITMAX;n++)
			{
				++ap;
				del *= x / ap;
				sum += del;
				if (fabs(del) < fabs(sum)*EPS)
					return sum * exp(-x+a*log(x)-gammln(a));
			}
			throw "ITMAX too small in Gser";
		}
	private:
		const int ITMAX;  // maximum number of iterations allowed
		const T EPS;  // relative error
		Gammln<T> gammln;
	};
	class Gcf  // nested class used by Gammq
	{
	public:
		Gcf() : ITMAX(100),EPS(3.0e-1) {};
		T operator () (T a,T x)  // evaluates by continued fraction representation
		{
			T b = x + 1.0 - a;
			T c = 1.0 / FPMIN;
			T d = 1.0 / b;
			T h = d;
			T an,del;
			int i;
			for (i=1;i<=ITMAX;i++)
			{
				an = -i * (i-a);
				b += 2.0;
				d = an*d + b;
				if (fabs(d) < FPMIN)
					d = FPMIN;
				c = b + an/c;
				if (fabs(c) < FPMIN)
					c = FPMIN;
				d = 1.0 / d;
				del = d * c;
				h *= del;
				if (fabs(del-1.0) < EPS)
					break;
			}
			if (i > ITMAX)
				throw "a too large, ITMAX too small in Gcf";
			return exp(-x+a*log(x)-gammln(a))*h;
		}
	private:
		const int ITMAX;  // maximum number of iterations allowed
		const T EPS;  // relative accuracy
		Gammln<T> gammln;
	};
	T operator () (T,T);  // evaluates the incomplete gamma function Q(a,x)
};

//----------

template <class T>
T Gammq<T>::operator () (T a,T x)
{
	try
	{
		if (x < 0.0 || a <= 0.0)
		{
			throw "invalid arguments in Gammq";
		}
		if (x < (a+1.0))
		{
			Gser gser;
			return 1.0 - gser(a,x);
		}
		else
		{
			Gcf gcf;
			return gcf(a,x);
		}
	}
	catch (char* message)
	{
		error(message);
		return 0.0;
	}
}

//----------

template <class T>
class NormDist : public Gammq<T>
{
public:
	T operator () (T);  // calculates the significance of a Z statistic
private:
	Gammq<T> gammq;
};

//----------

template <class T>
T NormDist<T>::operator () (T z)
{
	return gammq(0.5,z*z/2);
}

//----------

template <class T>
class ChiSqrDist : public Gammq<T>
{
public:
	T operator () (T,int);  // calculates the significance of a chi-square statistic
private:
	Gammq<T> gammq;
};

//----------

template <class T>
T ChiSqrDist<T>::operator () (T cs,int df)
{
	return gammq(0.5*df,0.5*cs);
}

//----------

template <class T>
class Betai : public SpecFunc<T>  // adapted from Numerical Recipes in C
{
public:
	class Betacf  // nested class used by Betai
	{
	public:
		Betacf() : MAXIT(100),EPS(3.0e-7) {};
		T operator () (T a,T b,T x)  // evaluates the continued fraction
		{
			T qab = a + b;
			T qap = a + 1.0;
			T qam = a - 1.0;
			T c = 1.0;
			T d = 1.0 - qab*x/qap;
			if (fabs(d) < FPMIN)
				d = FPMIN;
			d = 1.0 / d;
			T h = d;
			T aa,del;
			int m,m2;
			for (m=1;m<=MAXIT;m++)
			{
				m2 = 2 * m;
				aa = m * (b-m) * x / ((qam+m2)*(a+m2));
				d = 1.0 + aa*d;
				if (fabs(d) < FPMIN)
					d = FPMIN;
				c = 1.0 + aa/c;
				if (fabs(c) < FPMIN)
					c = FPMIN;
				d = 1.0/d;
				h *= d * c;
				aa = -(a+m) * (qab+m) * x / ((a+m2)*(qap+m2));
				d = 1.0 + aa*d;
				if (fabs(d) < FPMIN)
					d = FPMIN;
				c = 1.0 + aa/c;
				if (fabs(c) < FPMIN)
					c = FPMIN;
				d = 1.0/d;
				del = d * c;
				h *= del;
				if (fabs(del-1.0) < EPS)
					break;
			}
			if (m > MAXIT)
				throw "a or b too big, or MAXIT too small in Betacf";
			return h;
		};
	private:
		const int MAXIT;  // maximum number of iterations allowed
		const T EPS;  // relative error
	};
	T operator () (T,T,T);  // evalutes the incomplete beta function Ix(a,b)
private:
	Gammln<T> gammln;
	Betacf betacf;
};

//----------

template <class T>
T Betai<T>::operator () (T a,T b,T x)
{
	try
	{
		T bt;
		if (x<0.0 || x>1.0)
			throw "bad x in Betai";
		if (x==0.0 || x==1.0)
			bt = 0.0;
		else
			bt = exp(gammln(a+b)-gammln(a)-gammln(b)+a*log(x)+b*log(1.0-x));
		if (x < (a+1.0)/(a+b+2.0))
			return bt * betacf(a,b,x) / a;
		else
			return 1.0 - bt*betacf(b,a,1.0-x)/b;
	}
	catch (char* message)
	{
		error(message);
		return 0.0;
	}
}

//----------

template <class T>
class TDist : public Betai<T>
{
public:
	T operator () (T,int);  // calculates the significance of a t statistic
private:
	Betai<T> betai;
};

//----------

template <class T>
T TDist<T>::operator () (T t,int df)
{
	return betai(0.5*df,0.5,df/(df + t*t));
}

//----------

template <class T>
class Data  // abstract base class for handling data samples
{
public:
	Data();
	Data(T*,int);
	Data(char*,int);
	virtual ~Data();
	T* sample();  // returns a pointer to the first data element
	T& operator [] (int);  // returns a reference to a data element
	int size();  // returns the number of elements
	T sampmean(); // calculates the sample mean
	T sampvar();  // calculates the sample variance
	virtual T meantest(T) = 0;
	virtual T vartest(T) = 0;
protected:
	T* data;  // pointer to the first data element
	int length;  // number of data elements
};

//----------

template <class T>
Data<T>::Data()
{
	try
	{
		cout << "Enter sample size:" << endl << "? ";
		cin>>length;
		if (length < 1)
			throw "non-positive number of data elements";
		data = new T[length];
		cout << "Enter the data values:" << endl;
		for (int i=0;i<length;i++)
		{
			cout << "? ";
			cin >> data[i];
		}
	}
	catch (char* message)
	{
		error(message);
		data = 0;
		length = 0;
	}
}

template <class T>
Data<T>::Data(T* array,int length):length(length)
{
	try
	{
		if (length < 1)
			throw "non-positive number of data elements";
		data = new T[length];
		for (int i=0;i<length;i++)
			data[i] = array[i];
	}
	catch (char* message)
	{
		error(message);
		data = 0;
		length = 0;
	}
}

template <class T>
Data<T>::Data(char* file,int length):length(length)
{
	try
	{
		if (length < 1)
			throw "non-positive number of data elements";
		data = new T[length];
		ifstream infile(file,ios::nocreate);
		if (infile.fail())
			throw "file not found";
		for (int i=0;i<length;i++)
		{
			infile >> data[i];
			if (infile.eof())
				throw "insufficient number of data elements in file";
			if (infile.fail())
				throw "failbit or badbit in file";
		}
		infile.close();
	}
	catch (char* message)
	{
		error(message);
		data = 0;
		length = 0;
	}
}

template <class T>
Data<T>::~Data()
{
	delete [] data;
}

template <class T>
T* Data<T>::sample()
{
	return data;
}	

template <class T>
T& Data<T>::operator [] (int i)
{
	try
	{
		if (i<0 || i>=length)
			throw "index out of bounds";
		return data[i];
	}
	catch (char* message)
	{
		error(message);
	}
}

template <class T>
int Data<T>::size()
{
	return length;
}

template <class T>
T Data<T>::sampmean()  // adapted from Numerical Recipes in C
{
	if (length < 1)
	{
		error("non-positive number of data elements, mean undefined");
		return 0.0;
	}
	T s = 0.0;
	for (int j=0;j<length;j++)
		s += data[j];
	return s / length;
}

template <class T>
T Data<T>::sampvar()  // adapted from Numerical Recipes in C
{
	if (length < 2)
	{
		error("sample size less than 2, variance undefined");
		return 0.0;
	}
	T s;
	T ep = 0.0;
	T var = 0.0;	
	for (int j=0;j<length;j++)
	{
		s = data[j] - sampmean();
		ep += s;
		var += s*s;
	}
	return (var - ep*ep/length)/(length-1);
}

//----------

template <class T>
class KnVarData : public Data<T>  // handles samples of known variance
{
public:
	KnVarData();
	KnVarData(T*,int,T);
	KnVarData(char*,int,T);
	T var();  // returns the variance
	virtual T meantest(T);
	virtual T vartest(T);
private:
	T variance;  // true variance
};

// ----------

template <class T>
KnVarData<T>::KnVarData()
{
	cout << "Enter the variance: " << endl << "? ";
	cin >> variance;
	if (variance < 0)
	{
		error("negative variance");
		variance = fabs(variance);
	}
}

template <class T>
KnVarData<T>::KnVarData(T* data,int length,T variance) :
	Data<T>(data,length),variance(variance)
{
	if (variance < 0)
	{
		error("negative variance");
		variance = fabs(variance);
	}
}

template <class T>
KnVarData<T>::KnVarData(char* file,int length,T variance) :
	Data<T>(file,length),variance(variance)
{
	if (variance < 0)
	{
		error("negative variance");
		variance = fabs(variance);
	}
}


template <class T>
T KnVarData<T>::var()
{
	return variance;
}

template <class T>
T KnVarData<T>::meantest(T testmean)
{
	T z = (sampmean()-testmean) / sqrt(variance/length); // computes the Z statistic
	NormDist<T> normdist;
	return normdist(z);
}
template <class T>
T KnVarData<T>::vartest(T testvariance)
{
	return variance==testvariance ? 1 : 0;
}

// ----------

template <class T>
class UnknVarData : public Data<T>  // handles samples of unknown variance
{
public:
	UnknVarData();
	UnknVarData(T*,int);
	UnknVarData(char*,int);
	virtual T meantest(T);
	virtual T vartest(T);
};

// ----------

template <class T>
UnknVarData<T>::UnknVarData() {}

template <class T>
UnknVarData<T>::UnknVarData(T* data,int length) : Data<T>(data,length) {}

template <class T>
UnknVarData<T>::UnknVarData(char* file,int length) : Data<T>(file,length) {}

template <class T>
T UnknVarData<T>::meantest(T testmean)
{
	T t = (sampmean()-testmean) / sqrt(sampvar()/length);  // computes the t statistic
	int df = length - 1;  // degrees of freedom of the t distribution
	TDist<T> tdist;
	return tdist(fabs(t),df);
}

template <class T>
T UnknVarData<T>::vartest(T testvariance)
{
	T cs = (length-1) * sampvar() / testvariance; // computes the chi-square statistic
	int df = length - 1;  // degrees of freedeom of the chi-square distribution
	ChiSqrDist<T> chisqrdist;
	return chisqrdist(cs,df);
}

// ----------

void error(char* message)
{
	cout << endl << "***ERROR: " << message << endl << endl;
	return;
}
