#include "tree.h"
#include "dist.h"
#include "t_est.h"
/*#include <stdlib.h>*/

double t_noedge(               /* Calculates T(h) without edge correction */
		coord *points,       /* An array of positions */
		int n,               /* Number of points */
		double a,            /* Length of box in x-direction */
		double b,            /* Length of box in y-direction */
		double h)            /* Parameter of t */
{
  int i,j,k;
  int sum=0;          /* Current estimate of sum part of t estimate */
  double dist;        /* Euclidean distance between two points */
  double dist2;       /* Euclidean distance between two points */
  double dist3;       /* Euclidean distance between two points */

  if(points == NULL)
    return 0.0;

  for(i=n; i>0; --i){
    for(j=i-1; j>0; --j){
      dist=edist(points+i-1,points+j-1);
      if(dist<=h){
	for(k=j-1; k>0; --k){
	  dist2=edist(points+j-1,points+k-1);
	  if(dist2<=h){
	    dist3=edist(points+i-1,points+k-1);
	    if(dist3<=h){
	      sum++;
	    }
	  }
	}
      }
    }
  }

  return (a*b*3/((double) (n*(n-1)*(n-2))))*(double)sum;  /* return est of T */
}

double t_tor(              /* Calculates T(h) on a torus */
	     coord *points,       /* An array of positions */
	     int n,               /* Number of points */
	     double a,            /* Length of box in x-direction */
	     double b,            /* Length of box in y-direction */
	     double h)            /* Parameter of t */
{
  int i,j,k;
  int sum=0;          /* Current estimate of sum part of t estimate */
  double dist;       /* Toroidal Euclidean distance between two points */
  double dist2;       /* Toroidal Euclidean distance between two points */
  double dist3;       /* Toroidal Euclidean distance between two points */

  if(points == NULL)
    return 0.0;

  for(i=n; i>0; --i){
    for(j=i-1; j>0; --j){
      dist=tdist(points+i-1,points+j-1,a,b);
      if(dist<=h){
	for(k=j-1; k>0; --k){
	  dist2=tdist(points+j-1,points+k-1,a,b);
	  if(dist2<=h){
	    dist3=tdist(points+i-1,points+k-1,a,b);
	    if(dist3<=h){
	      sum++;
	    }
	  }
	}
      }
    }
  }

  return (a*b*3/((double) (n*(n-1)*(n-2))))*(double)sum;  /* return est of T */
}
