/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/

#include "vpf_std.h"
#include "vpf_edge.h"
#include "vpf_table.h"
#include "vpf_file.h"
#include "coordinate_conv.h"
// VPF_EDGE_RECORD

VPF_RECORD_READER_BEGIN(
	edge_record_read, 
	VPF_EDGE_RECORD)

	VPF_READ_FIELD(id)
	VPF_READ_FIELD_MULTI(lft_id)
	VPF_READ_FIELD(start_node)
	VPF_READ_FIELD(end_node)
	VPF_READ_FIELD(right_face)
	VPF_READ_FIELD(left_face)
	VPF_READ_FIELD(right_edge)
	VPF_READ_FIELD(left_edge)
	VPF_READ_FIELD(coordinates)

VPF_RECORD_READER_END()


void edge_record_delete(VPF_EDGE_RECORD *e){
	if(e==0)
		return;
	vpf_list_delete(e->coordinates);
	free(e);
}

void get_max_rect_from_edge(VPF_RECT *ret, const VPF_EDGE_RECORD *edge)
{
	VPF_LIST_ITEM *i;
//	VPF_WGS84_COORDINATE c_;
	for(i=edge->coordinates->head; i; i=i->next){
		VPF_COORDINATE *c = (VPF_COORDINATE *)i->data;
/*
		get_wgs84_from_itrf94(&c_, c);
		if(ret->is_null){
			ret->left = ret->right = c_.longitude;
			ret->top = ret->bottom = c_.latitude;
		}
		else{
			if(ret->left > c_.longitude) 
				ret->left = c_.longitude;
			if(ret->top > c_.latitude) 
				ret->top = c_.latitude;
			if(ret->right < c_.longitude) 
				ret->right = c_.longitude;
			if(ret->bottom < c_.latitude) 
				ret->bottom = c_.latitude;
		}
*/
		if(ret->is_null){
			ret->left = ret->right = c->x;
			ret->top = ret->bottom = c->y;
		}
		else{
			if(ret->left > c->x) 
				ret->left = c->x;
			if(ret->top > c->y) 
				ret->top = c->y;
			if(ret->right < c->x) 
				ret->right = c->x;
			if(ret->bottom < c->y) 
				ret->bottom = c->y;
		}
		
		ret->is_null=FALSE;
	}
}

void get_max_rect_form_edges(VPF_RECT *ret, VPF_LIST *records){
	VPF_LIST_ITEM *i;
	for(i=records->head; i; i=i->next){
		get_max_rect_from_edge(ret, (VPF_EDGE_RECORD *)i->data);
	}
}

VPF_EDGE_RECORD *vpf_table_get_edge(VPF_TABLE *edge_table, LONG id)
{
	VPF_LIST_ITEM *it;
	VPF_EDGE_RECORD *r;
	for(it = edge_table->records->head; it; it=it->next){
		r = (VPF_EDGE_RECORD *)it->data;
		if(r->id == id)
			return r;
	}
	return NULL;
}


BOOL vpf_edge_is_boundary(const VPF_EDGE_RECORD *edge)
{
	if(edge->left_face.ext_id != 0 || edge->right_face.ext_id != 0){
		return TRUE;
	}
	else{
		return FALSE;
	}
}
