/* "boxify", is a simple filter for cleaning up quite general CIF
             and make it readable for "WOL"
   Copyright (C) 1990 Tor Sverre Lande
   Author's address: bassen@ifi.uio.no

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (any version).

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */

/***************************************************\
* 						    *
*  This program reads a file of polygons with MBB   *
*  sorted on low-y and generates trapesoids. 	    *
* 						    *
\***************************************************/

#include <stdio.h>

#include "trapes.h"

#include "poly.h"

long id=0;
int trapescount=0;
int currentmin=0;

struct polygon *unread;	/* pointer to next polygon to read */

trapes(pl,resa,resb,Xoffset,Yoffset)
struct polygon *pl; /* sorted list of polygons*/
int resa,resb;
long Xoffset,Yoffset;
{
	struct edge p1,p2;
	struct edge_head edges;/* list of actual edges sorted on yl*/
	struct edge_head active;	/* pointer to list of edges 
					intersectioned by currenty */
	int err;
	
	double altitude=0.0,currenty=0.0,findnext();

	id = trapescount = currentmin = 0;
	
	edges.first=NULL; edges.last=NULL;
	active.first=NULL; active.last=NULL;
	
		/* At least 1 polygon */

	unread = pl;

    while ((edges.first != NULL ) || (active.first != NULL ) || (unread != NULL))
    {
    	/* if active-list empty update currenty */
    	if (active.first == NULL) 
	{
	    if (edges.first==NULL)
	    {
		if ((err=makeedges(&edges))<0)
		{
			fprintf(stderr,"***trapes:Somthing wrong in makeedges\n");
			return(err);
		}
		unread=NULL;
	    }
	    if (edges.first != NULL) currenty=edges.first->yl;
	}
	/* updates active-list sorted on x */
#ifdef TDEBUG
fprintf(stderr,"updates active-list currenty:%f\n",currenty);
#endif
	if (updateactive(&active,&edges,currenty)<0) 
	{
		fprintf(stderr,"***trapes:Somthing wrong in updateactive\n");
		exit(-1);
	}
	/* find next altitude */
	altitude = findnext(&active,&edges,currenty,resa,resb,Xoffset,Yoffset);
	/* do mating and generate trapezoides */
	mates(&active,currenty,altitude,resa,resb,Xoffset,Yoffset);
	/* remove edges with y_max>altitude */
	delete_under(&active,altitude);
	/* update currenty */
	currenty=altitude;
    }
}
