clear all

missions = ['2000.056.04/'; '2000.056.05/'; '2000.056.06/'; '2000.056.07/'; '2000.056.09/'];
% missions = ['2000.056.07/'];

plotit = 1;
asciiout = 0;
matout=1; outfile = 'ctd_section';

[N x] = size(missions);

for M = 1:N;
   eval(['cd ../' missions(M,:)]); load ctd; cd ../JR;
   % eval(['load ../' missions(M,:) 'ctd']);
 if M==1;
   o2=O2; s=S; t=T; ph=pH; Depth=depth; time=epochsec; 
  % Roll=roll; Pitch=pitch; Yaw=yaw;
  lat=startlat; lon=startlon; 
 else
  o2=[o2;O2]; s=[s;S]; t=[t;T]; ph=[ph;pH]; Depth=[Depth;depth]; 
  time=[time;epochsec];
  % Roll=[Roll;roll]; Pitch=[Pitch;pitch]; Yaw=[Yaw;yaw];
  lat=[lat;startlat]; lon=[lon;startlon]; 
 end
idx(M) = length(T);	% idx contains endpoint of segment
end

%% pH prediction
% X = [t s o2]; [beta stats] = mlr(X,ph,1); return

%% Hysteresis check
% down = find(diff(depth)>0); up = find(diff(depth)<0);
% figure(1); clf; plot(t(down),depth(down),'r.',t(up),depth(up),'b.');
% set(gca,'Ydir','reverse'); legend('down','up'); return

%% Calculate interpolated lat and lon
%% Add last lat/lon based on next to last 
npt = length(lat); 
 alat = lat(npt) + (lat(npt) - lat(npt-1)); 
 alon = lon(npt) + (lon(npt) - lon(npt-1)); 
 lat=[lat;alat]; lon=[lon;alon];

%% Interpolate lat/lon
for M = 1:N;
 ilat = [linspace(lat(M),lat(M+1),idx(M))]';
 ilon = [linspace(lon(M),lon(M+1),idx(M))]';
 if M==1;
  ILAT = ilat; ILON=ilon;
 else
  ILAT = [ILAT;ilat]; ILON=[ILON;ilon];
 end
end

if plotit
   figure(1); clf; giffig;
 axes('position',[.2 .15 .7 .7]);
 mapaxis =[-122.08 -121.78 36.57 37]; 
 [fillLat,fillLon] = get_landfill(mapaxis);
 fill(fillLon,fillLat,[.5 .5 .5]); axis(mapaxis);
 hold on; plot_iso([200 500 800],mapaxis,'b');
 set(gca,'tickdir','out','fontsize',12,'fontweight','bold');
 llgrid(10);

 plot(ILON,ILAT,'r'); 
 p=plot(lon,lat,'ro'); set(p,'markerfacecolor','r');
 p=plot(alon,alat,'ro'); set(p,'markerfacecolor','r');
 % title('Mission starting points');
 %% M1
 p=plot(-122.03,36.75,'ko'); 
 set(p,'markerfacecolor','k','markersize',8);
 tx=text(-122.03,36.73,'M1'); 
 set(tx,'fontweight','bold','fontsize',15,'color','k');
 
 figure(2); clf; giffig
 plot3(ILAT,ILON,Depth,'r.');
 set(gca,'ydir','reverse','zdir','reverse');
 grid;
end

if matout
   eval(['save ' outfile ' t s o2 ph Depth ILAT ILON time']);
end

if asciiout
odat = [time ILAT ILON Depth t s o2 ph Pitch Roll Yaw];
fid = fopen('auvdive2.asc','w');
fprintf(fid,'%15.3f,%10.6f,%10.6f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f\n',odat');
fclose(fid);
end

