#include "clip.h"

void ClipLine(Point *a, Point *b)
{
  float dx, dy, tE, tL;

  dx = b->x - a->x;
  dy = b->y - a->y;

  if (Zero(dx) && Zero(dy) && PointInside(a)) return;

  tE = 0;
  tL = 1;

  if (ClipT(XMIN - a->x,  dx, &tE, &tL) &&
      ClipT(a->x - XMAX, -dx, &tE, &tL) &&
      ClipT(YMIN - a->y,  dy, &tE, &tL) &&
      ClipT(a->y - YMIN, -dy, &tE, &tL))
    {
      if (tL < 1) {
	b->x = a->x + tL * dx;
	b->y = a->y + tL * dy;
      }
      if (tE > 0) {
	a->x += tE * dx;
	a->y += tE * dy;
      }
    }
}
      

int PointInside(Point *a)
{
  return (a->x >= XMIN && a->x <= XMAX &&
          a->y >= YMIN && a->y <= YMAX);
}


int ClipT(float num, float denom, float *tE, float *tL)
{
  register float t;

  if (Zero(denom)) return (num <= 0);

  t=num/denom;

  if (denom > 0) {
    if (t > *tL) return 0;
    if (t > *tE) *tE = t;
  } else {
    if (t < *tE) return 0;
    if (t < *tL) *tL = t;
  }

  return 1;
}