/* FFNet_Eigen.c */
/* David Weenink, 19981229 */

#include "FFNet_Eigen.h"
#include "Graphics.h"

void FFNet_Eigen_drawIntersection (FFNet me, Eigen eigen, Graphics g, long pcx, long pcy,
    double xmin, double xmax, double ymin, double ymax)
{
    long i, ix = labs (pcx), iy = labs (pcy); double x1, x2, y1, y2;
    long numberOfEigenvalues = eigen -> numberOfEigenvalues;
    long dimension = eigen -> dimension;
    
    if (ix > numberOfEigenvalues ||
    	iy > numberOfEigenvalues || my nInputs != dimension) return;
    Melder_assert (ix > 0 && iy > 0);
    if (xmax <= xmin || ymax <= ymin) Graphics_inqWindow (g, & x1, & x2, & y1, & y2);
    if (xmax <= xmin) { xmin = x1; xmax = x2; }
    if (ymax <= ymin) { ymin = y1; ymax = y2; }
    Graphics_setInner (g);
    Graphics_setWindow (g, xmin, xmax, ymin, ymax);
    for (i=1; i <= my nUnitsInLayer[1]; i++)
    {
		long j, unitOffset = my nInputs + 1;
		double c1 = 0.0, c2 = 0.0, bias = my w[ my wLast[unitOffset+i] ];
		double x[6], y[6], xs[3], ys[3]; int ns = 0;
		for (j=1; j <= my nInputs; j++)
		{
	    	c1 += my w[ my wFirst[unitOffset+i] + j - 1 ] * eigen->eigenvectors[ix][j];
	    	c2 += my w[ my wFirst[unitOffset+i] + j - 1 ] * eigen->eigenvectors[iy][j];
		}
		x[1] = x[2] = x[5] = xmin; x[3] = x[4] = xmax;
		y[1] = y[4] = y[5] = ymin; y[2] = y[3] = ymax;
		for (j=1; j <= 4; j++)
		{
	    	double p1 = c1 * x[j  ] + c2 * y[j  ] + bias;
	    	double p2 = c1 * x[j+1] + c2 * y[j+1] + bias;
	    	double r = fabs (p1) / ( fabs (p1) + fabs (p2));
	    	if (p1*p2 > 0 || r == 0.0) continue;
	    	if (++ns > 2) break;
	    	xs[ns] = x[j] + ( x[j+1] - x[j]) * r;
	    	ys[ns] = y[j] + ( y[j+1] - y[j]) * r;
		}
		if (ns < 2) Melder_casual ("intersection for unit %ld outside range", i);
		else Graphics_line (g, xs[1], ys[1], xs[2], ys[2]);
    }
    Graphics_unsetInner (g);
}

/* End of file FFNet_Eigen.c */
