/*
 NAME
 	crect.m - source code for CRect class
 VERSION
 	$Id$
 CHANGELOG
 	$Log$
 */

#include <coconut/crect.h>
#include <coconut/cerror.h>

@implementation CRect

- init
{
	return [self initRect: 0 and: 0 and: 0 and: 0] ;
}

- initRect: (position_t) left and: (position_t) top
    and:(dimension_t) width and: (dimension_t) height
{
	id result ;
	if((result = [super init]) != nil){
		[self set: left and: top and: width and: height] ;
	}
	return result ;
}

- (void) dealloc
{
	return [super dealloc] ;
}

- set: (position_t) left and: (position_t) top
    and:(dimension_t) width and:(dimension_t) height
{
	rect_left = left ; rect_top = top ;
	rect_width = width ; rect_height = height ;
	return nil ;
}

- setCorner: (position_t) left and: (position_t) top
{
	rect_left = left ; rect_top = top ;
	return nil ;
}

- setSize: (dimension_t) width and: (dimension_t) height
{
	rect_width = width ; rect_height = height ;
	return nil ;
}

- setLeft: (position_t) l
{
	rect_left = l ;
	return nil ;
}

- setTop: (position_t) t
{
	rect_top = t ;
	return nil ;
}

- setRight: (position_t) r
{
	rect_width = r - rect_left ;
	return nil ;
}

- setBottom: (position_t) b
{
	rect_height = b - rect_top ;
	return nil ;
}

- (position_t) left
{
	return rect_left ;
}

- (position_t) top
{
	return rect_top ;
}

- (position_t) right
{
	return rect_left + rect_width ;
}

- (position_t) bottom
{
	return rect_top + rect_height ;
}

- (dimension_t) width
{
	return rect_width ;
}

- (dimension_t) height
{
	return rect_height ;
}

- copy: (id <PRect>) src 
{	
	rect_left = [src left] ; rect_top = [src top] ;
	rect_width = [src width] ; rect_height = [src height] ;
	return nil ;
}

- move: (position_t) dh and: (position_t) dv
{
	rect_left += dh ; rect_top += dv ; 
	return nil ;
}

- grow: (position_t) dh and: (position_t) dv
{
	rect_left -= dh ; rect_top -= dv ; 
	rect_width += dh * 2 ; rect_height += dv * 2 ;
	return nil ;
}

- (id <PError>) union: (id <PRect>) src
{
	position_t	srcleft, srcright, srctop, srcbottom ;
	position_t	thisright, thisbottom ;

	thisright = rect_left + rect_width ;
	thisbottom = rect_top + rect_height ;
	srcleft = [src left] ; srctop = [src top] ;
	srcright = [src right] ; srcbottom = [src bottom] ;

	rect_left = MAX(rect_left, srcleft) ;
	rect_top = MAX(rect_top, srctop) ;
	thisright = MIN(thisright, srcright) ;
	thisbottom = MIN(thisbottom, srcbottom) ;

	rect_width = thisright - rect_left ;
	rect_height = thisbottom - rect_top ;

	return rect_left <= thisright && rect_top <= thisbottom ? 
	  nil : [CError not_exist] ;
}

@end

