function P=calctrm(S1,S2,w);
%CALCTRM calculate the transform parameters to align two shapes
%  P = CALCTRM(S1,S2,W) calculates the translation, scale and rotation
%  to align shape S2 with S1. W is a set of weights giving the 
%  relative stability of each data point.
%
%  See also  PDMBUILD APPLYTRM
%
%
% Barry-John Theobald, b.theobald@uea.ac.uk
% School of Information Systems, University of East Anglia,
% Norwich, NR4 7TJ, UK
%
% Version 1.0

% HISTORY:
%     21/11/2002 - 1.0 - Initial revision
if(nargin < 3)
	error('Must define two examples shapes and a set of weights');
end
% Must be column vectors
S1 = S1(:);
S2 = S2(:);
N = size(S1,1);
% Get the (x,y) coords
x1 = S1(1:2:N);
y1 = S1(2:2:N);
x2 = S2(1:2:N);
y2 = S2(2:2:N);
% Compute transform parameters
X1 = sum(w.*x1);
Y1 = sum(w.*y1);
X2 = sum(w.*x2);
Y2 = sum(w.*y2);
C1 = sum(w.*(x1.*x2 + y1.*y2));
C2 = sum(w.*(x2.*y1 - x1.*y2));
W = sum(w);
Z = sum(w.*(x2.^2+y2.^2));
% Set up matrices for alignment
T=[ X2   -Y2   W   0
    Y2    X2   0   W
     Z     0  X2  Y2
     0     Z -Y2  X2 ];

A=[ X1; Y1; C1; C2];
% Tranformation matrix of the form [ax; ay; tx; ty]
%P=T\A;  
P = pinv(T)*A;






