function color3d(mT,X,Y,Z,fn);
%Syntax: color3d(T,X,Y,Z,filename)
%
%Converts a triangular mesh to Color3D.
% T is nx3 matrix with vertex indices for n triangles (smallest index is 1)
% X is mx1 matrix containing the x coordinates of m vertices
%     Y and Z analog
% filename is a string for the target output (example: 'C:\color3d\data\house')
%
%The output consists of four files. In the example:
% - C:\color3d\data\house.cv      each vertex position with color
% - C:\color3d\data\house.ind     triangle indices (start from 0)
% - C:\color3d\data\house.hap     haptic information for each triangle
% - C:\color3d\data\house.vt      triangle list adjacent to each vertex
%
%Note that the vertices should be scaled within the range [-50 50] in each dimension.
%Initially the color is uniformly random distributed. Modify the source at line 22 for changes.

V=[X Y Z];
T=mT-1;

CV=[rand(size(V'));V']; %here the color is set to random ***

D1=V(mT(:,1),:)-V(mT(:,3),:);
D2=V(mT(:,2),:)-V(mT(:,3),:);
C=cross(D1,D2,2);       %this might not be accessible for older MATLAB versions than 6.5
nC=1./sqrt(sum(C.*C,2));
N=C.*nC(:,[1 1 1]);
nV=size(V,1);
nT=size(T,1);
fprintf('# vertices : %i\n',nV);
fprintf('# triangles: %i\n',nT);
tA=zeros(nT,3,3); %nT xyz span+N
tA(:,:,1)=D1;
tA(:,:,2)=D2;
tA(:,:,3)=N;
tA=permute(tA,[2 3 1]);

tB=zeros(3,5,nT);
for c1=1:nT; tB(:,1:3,c1)=inv(tA(:,:,c1)); end;
tB(:,4,:)=V(mT(:,3),:)';
tB(:,5,:)=N';

xisave(size(CV),CV,'float',[fn '.cv']);
xisave(size(T'),T','uint',[fn '.ind']);
xisave(size(tB),tB,'float',[fn '.hap']);
%return;
nV=size(V,1);
iV=zeros(nV,1);
TV=zeros(nV,40);
mL=0;
for c1=1:nT;
	for c2=mT(c1,:);
		iV(c2)=iV(c2)+1;
		TV(c2,iV(c2))=c1;
	end;
end;
mI=max(iV);
TT=zeros(nV,mI);

disp('Please be patient  (for 23T vertices the');
disp('last export step takes about 2 minutes).');
for c1=1:nV;			 %curr vertex!
	for c2=1:iV(c1); %loop adj triangles
		tr=TV(c1,c2);  %single triangle index = ST
		v12=setdiff(mT(tr,:),c1); %two verticees of ST 
		%if length(v12)~=2; error('nono'); end;
		t1=TV(v12(1),1:iV(v12(1))); %triangles at vert # 1
		t2=TV(v12(2),1:iV(v12(2))); %triangles at vert # 2
		ct=intersect(t1,t2); %common triangles at edge (your data is a little broken if not always length(ct)==2) ...
		dt=setdiff(ct,tr);   %... export is possible anyways (haptics might be corrupt at these places)
		if ~length(dt);
			disp('hole detected!');
		else
			TT(c1,c2)=dt(1);
		end;
	end;
end;

for c1=1:nV; TV(c1,iV(c1)+(1:iV(c1)))=TT(c1,1:iV(c1)); end;
TV=TV(:,1:mI*2)'-1;
xisave(size(TV),TV,'int',[fn '.vt']);
disp('...done.');
return;

function s=xisave(sA,A,typ,fn)
	fid=fopen(fn,'wb');
	fwrite(fid,length(sA),'int'); %ndims
	fwrite(fid,sA,'int');					%size[]
	fwrite(fid,A,typ);						%array[]
	fclose(fid);
s=['<<' typ ' [' num2str(sA) '] @' fn];
return