global dist teta d2  filename

if ( ~exist('dist') ),
	cd D:\LAZA\DICKST~1
	path(path, 'D:\LAZA\DICKST~1');
%	cd G:\DICKST~1
%	path(path, 'G:\DICKST~1');
	% [dist,k,h,w] = dLoadData('tx108.out');
	disp('Loading data ...');
	filename = 'tx102';
	eval(['load ' filename]);
	more off
	dTeta;		% Calculating goodness of the signal
	dDelBad;	% Removing bad signals from the matrices
end; %if ( ~exist('dist') )

n = size(dist,2);
x = zeros(n,k); y = zeros(n,k); z = zeros(n,k); 
R = sqrt(1/3)*mean(mean( dist(1:n,1:n) ));

d = dPlane(dist,1);
tt= dPlane(teta,1);
[x1,y1,z1] = dRandPoints( n, R );
[x1,y1,z1,e1] = dMinSimple( x1,y1,z1, d, tt );
[x2,y2,z2] = dRandPoints( n, R );
[x2,y2,z2,e2] = dMinSimple( x2,y2,z2, d, tt );
if (e2 < e1 ), x1=x2; y1=y2; z1=z2; e1=e2; end;
[x2,y2,z2] = dRandPoints( n, R );
[x2,y2,z2,e1] = dMinSimple( x2,y2,z2, d, tt );
if (e2 < e1 ), x1=x2; y1=y2; z1=z2; e1=e2; end;
clear x2 y2 z2 R e1 e2

disp('Calculating points coordinates');
tic;
CounterLimit = 0; ZeroCounter = 0;
tmax = 60;
for t = 1:tmax,
	d = dPlane(dist,t);
	tt= dPlane(teta,t);
	[x1,y1,z1,e,counter] = ...
		dMinSimple( x1,y1,z1, d , tt./(1+d), 0.5 );
CounterLimit = CounterLimit + (counter==20); ZeroCounter = ZeroCounter+(counter==0);
	x(1:n,t) = x1;
	y(1:n,t) = y1;
	z(1:n,t) = z1;
%    if( rem(k-1,100) == 0),
	disp(sprintf('%d/%d  e = %f, n = %d ',t,k, e, counter));
%    end; %if
end; %for
toc;
disp('Calculating distances between new points...');
d2 = dDistances(x,y,z);

disp('Filtering cartesian coordinates');
[num,den] = butter(3, 0.3);
for i = 1:n,
	x(i,:) = filtfilt(num,den,dSpikeElim(x(i,:)));
	y(i,:) = filtfilt(num,den,dSpikeElim(y(i,:)));
	z(i,:) = filtfilt(num,den,dSpikeElim(z(i,:)));
end;
disp('Done');
toc

% save dtxyz dist teta x y z n k  
clear R tmax cnt x1 y1 z1 counter den num t tt

txyz = zeros(length(x),3*n+1);
txyz(:,1) = (1:length(x))'/200;  % 200Hz time stamp
txyz(:,2:3:3*n) = 1/40*x';
txyz(:,3:3:3*n) = 1/40*y';
txyz(:,4:3:3*n+1) = 1/40*z';
% eval(['save -ascii ' filename  'xyz.txt txyz ']);

