%% clean_mission: to assemble and clean AUV mission data.
%% choose to focus on either CTD or AUV control

clear all; load dataCTD;

%%------------------------
%% Time
%%------------------------
mtime = ctdlog(:,time); 

%%------------------------
%% Spatial 
%%------------------------
%% Get spatial data and vehicle orientation.    Note:
%%  yaw is heading
%%  separate time stamps for [ctd], [lat lon], [roll pitch yaw], [depth]
[lat,lon,gpstime,depth,roll,pitch,yaw,navtime] = get_spatial;
%% Lat and lon fixed at last recorded position before mission submergence
startlat = lat(length(lat)); startlon = lon(length(lon));
%% Interpolate depth to ctdtime
cdepth = interp1(navtime,depth,mtime); clear depth
croll = interp1(navtime,roll,mtime); clear roll;
cpitch = interp1(navtime,pitch,mtime); clear pitch;
cyaw = interp1(navtime,yaw,mtime); clear yaw;
%% Create lat vector for pressure calculation
clat = repmat(mean(lat),length(ctdlog),1);
%% Compute pressure (db) from depth
pres = sw_pres(cdepth,clat);		% [db]

%%------------------------
%% Fluorometer and OBS 
%%------------------------
obs=ctdlog(:,OBS); f=ctdlog(:,fluor);

%%-------------------------------------------------------------------------
%% Temperature and Salinity
%% Some temperatures require correction at the temp_frequency level;
%% corrected temperature is then used to compute salinity.
%% Also, the instruments were changed out on the morning of 8/28 before
%%  the day AUV ops.  New coefficients are required for this.
%%-------------------------------------------------------------------------
plot(ctdlog(:,temp_frequency),'.');
% C=input('Correct temperature frequency? (0=no; 1=yes)');
% if C; 
%  [t,s]=fix_CTD; % call fix_temp_frequency, etc.
% else
	t = ctdlog(:,temperature);
	s = salsp(ctdlog(:,conductivity),t,pres);
% end

%%------------------------
%% Oxygen
%%------------------------
disp(['Computing Oxygen']);
oc = ctdlog(:,o2current); ot = ctdlog(:,o2temp); 
%% Get coefficients
o2serial = 368; 	% oxygen sensor serial number
[m,b,k,c,SOc,BOc] = O2_calibration(o2serial);
%% Oxygen
%% Lag time estimate needed 
Olag = [4 0];	% Oxygen measurement lag, required to frame shift T
%% last input is either mll (ml/l) or umolkg (umol/kg)
% if strcmp(option,'control')==1; ounits='mll'; else ounits='umolkg';end
ounits='mll';
o2 = calc_O2(oc,ot,t,s,pres,m,b,k,c,SOc,BOc,mtime,Olag,ounits);

%%------------------------
%% pH
%%------------------------
% Calibration for Sea-Bird SBE-18 Serial Number 180312, 
% from NBS calibration 23, Feb 2000.
pHV = ctdlog(:,pH); off = 2.4738; slp = 4.6399;
ph = calc_pH(pHV, slp, off, t);

%%------------------------
%% Average 
%%------------------------
%% For February AUV missions, ctd horizontal resolution was ~ 3.5 measurements 
%%  per along-track meter, with a temporal resolution of .25 seconds.
%%  This translates to a vehicle speed of ~ 1 m/s
avgint = 2;	% averaging interval, seconds, matches O2 offset
[T,S,pH,O2,F,OBS,time,depth,epochsec,pitch,roll,yaw] = avgCTD(t,s,ph,o2,f,obs,mtime,cdepth,cpitch,croll,cyaw,avgint);

%%------------------------
%% Plot 
%%------------------------
figure(1); clf; giffig_wide
sax = [min(S) max(S)];
fax = [min(F) max(F)]; pHax = [min(pH) max(pH)]; O2ax = [min(O2) max(O2)];
XL = 'mission time';

figure(1); clf; giffig

subplot(411); plot(time,depth,'k'); ylabel('depth'); set(gca,'Ydir','reverse');
xl=get(gca,'xlim'); set(gca,'box','off','YaxisLocation','left','tickdir','out'); 
hold on
P = get(gca,'position'); axes('position',P);
plot(time,pitch,'c'); hold on; plot(xl,[0 0],'k--');
set(gca,'YaxisLocation','right','Ycolor','c','box','off','tickdir','out');
ylabel('Pitch'); set(gca,'color','none','Ylim',[min(pitch) max(pitch)]);
set(gca,'xlim',xl);

subplot(412); 
plot(time,T,'r'); set(gca,'ylim',[min(T) max(T)]);
ylabel('temperature');
set(gca,'Ycolor','r','box','off','YaxisLocation','left','tickdir','out');
set(gca,'xlim',xl);
P = get(gca,'position'); axes('position',P);
plot(time,S,'b'); set(gca,'YaxisLocation','right','Ycolor','b','box','off');
set(gca,'Ylim',sax); ylabel('salinity'); set(gca,'color','none','tickdir','out');
set(gca,'xlim',xl);

subplot(413); plot(time,pH,'k'); ylabel('pH'); hold on; set(gca,'Ylim',pHax); 
set(gca,'box','off','YaxisLocation','left','tickdir','out'); set(gca,'xlim',xl);
P = get(gca,'position'); axes('position',P);
plot(time,O2,'m'); ylabel('Oxygen (ml/l)'); set(gca,'Ylim',O2ax); 
set(gca,'xlim',xl,'color','none','Yaxislocation','right','Ycolor','m','box','off','tickdir','out');

subplot(414), plot(time,F,'g'); 
set(gca,'YaxisLocation','left','Ycolor','g','box','off','tickdir','out');
set(gca,'Ylim',fax); ylabel('fluorometer (volts)'); 
set(gca,'xlim',xl); hold on;
P = get(gca,'position'); axes('position',P)
plot(time,OBS,'r'); ylabel('OBS');
xlabel(XL); 
set(gca,'box','off','xlim',xl,'color','none','Yaxislocation','right','Ycolor','r','tickdir','out');

%%------------------------
%% Endpoints and distance
%%------------------------
missiondata

%%------------------------
%% Subset 
%%------------------------
showmenu=1;

while showmenu
A=menu('Options','Crop Time Limit','Excise portion','Median Filter','Start Over','Save');
if A==1
 disp(['Select time subset']); figure(1); [x y]=ginput(2);
 idx = find(time>=x(1) & time<=x(2));
 T=T(idx); S=S(idx); pH=pH(idx); O2=O2(idx); depth=depth(idx); time=time(idx);
 F=F(idx); OBS=OBS(idx);
 epochsec=epochsec(idx); roll=roll(idx); pitch=pitch(idx); yaw=yaw(idx);
elseif A==2
   varname=input('Which variable (T, S, pH, O2, F, OBS)?','s');
   eval(['wvar=' varname ';']);
   figure(2); clf; set(gcf,'units','pixels','location',[10 100 1000 500]);
   plot(wvar);
   B=1; 
   while B
      C=menu('Excise sections','Choose section','done');
      if C==1
         [x y]=ginput(2); x=round(sort(x));
      	wvar(x(1):x(2))=NaN;
      	clf; plot(wvar);
      else
         B=0; eval([varname '=wvar=;']);
      end
   end
elseif A==3
      varname=input('Which variable (T, S, pH, O2, F, OBS)?','s');
      eval(['wvar=' varname ';']); wvarf=medfilt(wvar,11);
elseif A==4; 
		clean_mission
elseif A==5
 disp(['Saving to file ctd.mat']);
 save ctd T S pH O2 F OBS epochsec depth startlat startlon roll pitch yaw missionID surveydate ep dist
 disp(['Plotting cleaned mission...']);
 showmenu=0;
 check_mission
end

end