%spin_analysis.m
%  a routine to analyze our standard spin test to quantify the compass direction bias
% input files include a captured file from the ACM of spin data 
%   (appropriately edited so that only data scans are in the file)
% and a table of scan bounds for each wait interval of the test

infile=input(' Enter the name of the spin test data file ','s');

%if (exist(infile,'file') == 2);

eval(['load ',infile]);

name=infile;
j=find(name=='.');
if length(j)>0;
name=name(1:j-1);
end
j=find(name=='/');
if length(j)>0;
name=name(j(end)+1:end);
end

eval(['x=',name,';']);

aTx=x(:,1);
aTy=x(:,2);
aHx=x(:,3);
aHy=x(:,4);
aHz=x(:,5);

figure(1)
clf
plot(aHx);
hold
plot(aHy,'r');
plot(aHz,'k');
grid
zoom on
xlabel('scan number')
ylabel('compass channel readings')
title('Hx=blue, Hy=read, Hz=black')

figure(2)
clf
plot(aHx,aHy);
xlabel('Hx')
ylabel('Hy')
axis square
grid


disp([' Enter the name of the bounds file ']);
infile=input(' or type none to create one ','s');

if (exist(infile,'file') == 2);

eval(['load ',infile]);
j=find(infile=='.');
eval(['x= ',infile(1:j-1),';']);
truedir=x(:,1);
j1=x(:,2);
j2=x(:,3);

else %bounds file doesn't exist

%manually enter the bounds data here

truedir=[1.5708 0.7854 0 -0.7854 -1.5708 -2.3562 3.1416 2.3562 1.5708 ];         
disp(['for each direction check ']);

for i=1:9
i
truedir(i)
q=input('enter start and stop scans [x y] ');
j1(i)=q(1);
j2(i)=q(2);
end

x=[truedir' j1' j2'];

outfile=input('Enter the name of the new bounds file you wish to create ','s');
eval(['save ',outfile,' x -ascii']);


end %bounds file exists


ahx=aHx(j1(1):j2(end));
ahy=aHy(j1(1):j2(end));

hxbias=(max(ahx)+min(ahx))/2
hybias=(max(ahy)+min(ahy))/2

ahx=ahx-hxbias;
ahy=ahy-hybias;

hxscale=max(ahx)
hyscale=max(ahy)

aHx=(aHx-hxbias)/hxscale;
aHy=(aHy-hybias)/hyscale;


for j=1:9
hx(j)=mean(aHx(j1(j):j2(j)));
hy(j)=mean(aHy(j1(j):j2(j)));
end

testdir=atan2(hx,hy);


diff=truedir(:)-testdir(:);

if(abs(diff(7))>pi)
truedir(7)=truedir(7)-2*pi;
diff=truedir(:)-testdir(:);
end

figure(3)
clf
plot(truedir,'-xb');
hold
grid
plot(testdir,'ro-');
xlabel('test point')
ylabel('Direction   radians');

plot(diff,'k>-');

disp(['Mean(truedir - testdir)']); 
mean(diff)


%else %infile doesn't exist

%disp(['Can find your spin test input file, try again']

%end % infile exists


