/**********************************************************************
 
	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	"u_math.h"
#include	"resource.h"
#include	"xlerror.h"

extern SEM res_lock;

void
get_rol_matrix(AFFEN2D * a,
	GB_POINT src,GB_POINT dest,REAL1 rol)
{
double rad;
	rad = rol/180*M_PI;
	a->matrix[0][0] = cos(rad);
	a->matrix[0][1] = -sin(rad);
	a->matrix[1][0] = sin(rad);
	a->matrix[1][1] = cos(rad);
	a->org = p_sub(dest,mp_mul(a->matrix,src));
}

void
set_param_angle(RESOURCE * r,REAL1 rol)
{
MAP_POINT_LIST * p;
MAP_PARAMETER * mp_f,* mp_r;

	mp_f = &r->map.param_forward;
	mp_r = &r->map.param_reverse;
	p = R_NEXT(MAP_POINT_LIST*,&r->map.point_list);

	mp_f->type = MT_ROTATE;
	get_rol_matrix(&mp_f->opt.affen,
			p->src,p->dest,
		       rol);
	mp_f->resolution_rate = 1;
	mp_r->type = MT_ROTATE;
	get_rol_matrix(&mp_r->opt.affen,
			p->dest,p->src,
			-rol);
	mp_r->resolution_rate = 1;
}



XL_SEXP *
angle(XLISP_ENV * e,XL_SEXP * s)
{
RESOURCE * r;
int er;
REAL1 rol;
XL_SEXP * rol_s;
XL_SEXP * ret;

	r = get_resource_ptr(&ret,e,s->h.file,s->h.line);
	if ( r == 0 )
		return ret;
	rol_s = eval(e,get_el(s,1));
	switch ( get_type(rol_s) ) {
	case XLT_ERROR:
		return rol_s;
	case XLT_INTEGER:
		rol = rol_s->integer.data;
		break;
	case XLT_FLOAT:
		rol = rol_s->floating.data;
		break;
	default:
		goto type_missmatch;
	}
	lock_task(res_lock);
	set_param_angle(r,rol);
	set_reload(r);
	unlock_task(res_lock,"angle");
	return 0;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"angle"),
		list(n_get_string("type missmatch"),0));
}
