/*-----------------------------fpc.c: fast pixel tracing-----------------------------------
return the intersection length of one ray with the pixel
*from and *to it the two end-points of the ray, defined by the pixel-reference,
i.e., the left-lower coner of the pixel is the reference origin.
Author: T. Li, Aug 17, 2004
-------------------------------------------------------------------------------------------*/
#include <math.h>
#include <stdio.h>
#define EPS           1.E-6
#define SWAP(x,y,dum) (dum)=(x), (x)=(y), (y)=(dum)
double fpc2d(double *from, double *to)
{
#define D 2
	double	totlen, lmin, lmax;
	double	dx[D];
	double	k[D];  /** to trace more accurately **/
	double	dum0, dum1, dum;
	double	length;
	int		i;
/** setup **/
	for (i=0; i<D; i++)		dx[i] = to[i] - from[i];
	for (i=0, totlen=0.; i<D; i++) totlen += dx[i]*dx[i];
	totlen = sqrt(totlen);
	if (totlen < EPS) return 0;
/**calculation**/
	lmin = 0.;
	lmax = totlen;
	for (i=0; i<D; i++) 
	{
		if (dx[i])
		{
			k[i] = totlen/dx[i];
			dum0 = k[i] * (-from[i]);
			dum1 = k[i] * (1.0-from[i]);
      // printf("dum: %f, %f\n", dum0, dum1);
			if (dum0 > dum1) SWAP(dum0, dum1, dum);
			if (lmin<dum0) lmin = dum0;
			if (lmax>dum1) lmax = dum1;
		}
		else if (from[i]<=0.0 || from[i]>=1.0) return 0.;
	}
	length=lmax-lmin;
	if (length<0) return 0;
	else return length;
}
