% mt_calibrate - Set spatial calibration of melody triangle system.
%
% mt_calibrate ::
%    mt_system       ~'system to calibrate',
%    I:[[1,E]->[3]]  ~'list triangle corners being updated',
%    P:[[3,E]]       ~'X-Y coordinates of the E corners being updated'
% -> mt_system       ~'calibrated system'.

function Sys=mt_calibrate(Sys,I,PI)
	
	if nargin>2, Sys.refpoints(:,I) = PI; end
	P  = Sys.refpoints;
	disp('\nCalibrating for triangle vertices at:'); disp(P);
	p0 = P(:,1);
	Sys.map = info_map_fn(p0,inv(P(:,2:3)-repmat(p0,1,2)));
end

function f=info_map_fn(p0,M)
	f=@(p)clip_tri(M*(p-p0));
end

function x=clip_tri(x)
	if x(2)<0
		x(2)=0;
		if x(1)<0, x(1)=0;
		elseif x(1)>1, x(1)=1;
		end
	elseif x(1)<0
		x(1)=0;
		if x(2)<0, x(2)=1;
		elseif x(2)>1, x(2)=1;
		end
	else
		d = [1,1]*x - 1;
		if d>0
			x = x - d/2;
			if x(1)<0, x=[0;1];
			elseif x(2)<0, x=[1;0];
			end
		end
	end
end

