#include "tree.h"

#define min(a,b) (((a)<(b))?(a):(b))

double edist(coord *a,  /* Returns Euclidean distance from a to b */
	     coord *b)
{
  return sqrt((a->x-b->x)*(a->x-b->x) + (a->y-b->y)*(a->y-b->y));
}

double tdist(coord *a,  /* Returns minimum distance from a to b on a torus */
	     coord *b,
	     double x,  /* The rectangular representation of the torus is */
	     double y)  /* x by y */
{
  double dist1=0;
  double dist2=0;
  double common;  /* Variable used for common sub-expression elimination */

  /* First deal with standard case for x-coordinate and vary y-coord */
  common=(a->x-b->x)*(a->x-b->x);
  dist1=sqrt(common + (a->y-b->y)*(a->y-b->y));
  dist2=sqrt(common + (a->y-b->y+y)*(a->y-b->y+y));
  dist1=min(dist1,dist2);
  dist2=sqrt(common + (a->y-b->y-y)*(a->y-b->y-y));
  dist1=min(dist1,dist2);

  /* Now deal with case x-coord=x-coord+x and vary y-coord */
  common=(a->x-b->x+x)*(a->x-b->x+x);
  dist2=sqrt(common + (a->y-b->y)*(a->y-b->y));
  dist1=min(dist1,dist2);
  dist2=sqrt(common + (a->y-b->y+y)*(a->y-b->y+y));
  dist1=min(dist1,dist2);
  dist2=sqrt(common + (a->y-b->y-y)*(a->y-b->y-y));
  dist1=min(dist1,dist2);

  common=(a->x-b->x-x)*(a->x-b->x-x);
  dist2=sqrt(common + (a->y-b->y)*(a->y-b->y));
  dist1=min(dist1,dist2);
  dist2=sqrt(common + (a->y-b->y+y)*(a->y-b->y+y));
  dist1=min(dist1,dist2);
  dist2=sqrt(common + (a->y-b->y-y)*(a->y-b->y-y));

  return min(dist1,dist2);
}
