function [cos_phi_mat] = CalcCosPhiMat(A,B)

%	CalcCosPhiMat.m
%
%	This function will calculate the Legendre coefficients

%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk. All Rights Reserved.                     
%                                                                                          
%   THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE        
%   NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO,    
%   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE    
%   OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
%   TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT,       
%   INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE      
%   OR DOCUMENTATION.  



size_A=size(A);

if isempty(B)
	status =-1;
	if size_A(2)~=3
		error('Bad dimension in matrix A');
	end
elseif ~isempty(B)
 	status=1;
 	size_B=size(B);
 	if size_A(2)~=3 | size_B(2)~=3
		error('Bad dimension in matrix A or B')
	end	
end


if status==1
	cos_phi_mat=zeros(size_A(1),size_B(1));
	for i=1:size_A(1)
		for j=1:size_B(1)
			a2=sum(A(i,:).^2); b2=sum(B(j,:).^2); c2=sum((A(i,:)-B(j,:)).^2);
			cos_phi_mat(i,j) = ((a2) + (b2) - (c2)) / (2 * sqrt(a2) * sqrt(b2));
		end
	end
elseif status==-1

	%first calculate the diag elements, phi=0 => cos(phi)=1

	[cos_phi_mat] =eye(size_A(1));

	%second the non diag elements
	
	for i=1:(size_A(1)-1)
		for j=(i+1):size_A(1)
			a2=sum(A(i,:).^2); b2=sum(A(j,:).^2); c2=sum((A(i,:)-A(j,:)).^2);
			cos_phi_mat(i,j) = ((a2) + (b2) - (c2)) / (2 * sqrt(a2) * sqrt(b2));
		end
	end
	
	%	and third make the matrix symmetrical
	
	cos_phi_mat = cos_phi_mat + (ones(size(cos_phi_mat)) - eye(size(cos_phi_mat))).* cos_phi_mat';
							
end

return;
