%% clean_mission: to clean AUV mission data.
%% This version is needed for data before day 240 (238 and 239).
%% It includes corrections for the CTD coefficients.
%% After day 239, these corrections were implemented in the AUV.

clear all; 
clf;

%% First compute T and S with correct coefficients
disp(['Calculating T and S with corrected coefficients']);
if (exist('dataN.mat')~=2)
   disp(['Need to run save_as_matN first'])
   save_as_matN;
end%if exist
 load dataN; load dataCTD; CTD_recompute
clear all; load TScorrected;

if (exist('missiondata.m')~=2) % no mission data file in directory
   disp(['No missiondata file... creating one for you to edit']);
   !copy c:\muse\auv\night\mfiles\missiontemplate.m missiondata.m
else 
   disp(['Found missiondata file... hope the values are correct!']);
end%if
%   input('Enter to continue');   
   
load dataCTD;
mtime = ctdlog(:,time); 

%%------------------------
%% Temperature 
%%------------------------
% t = ctdlog(:,temperature);

%%------------------------
%% Fluorometer and OBS 
%%------------------------
%%%
%%% IMPORTANT: for missions <241 (i.e. 237-240) 
%%% the fluor and OBS data streams are swapped.
%%% comment out this line depending on which mission 
%%% you are processing.
%%% Also note that the variable name flour was corrected to fluor for mission 241 and subsequent.

% for missions before 241
% f=ctdlog(:,OBS); obs=ctdlog(:,flour); disp('Swapping OBS and fluor. mission<241');

%% for missions after 241 (inclusive) 
 obs=ctdlog(:,OBS); f=ctdlog(:,fluor); disp('Not swapping OBS and fluor. mission>241');

%%------------------------
%% 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;

load dataN;

posx0 = dataNav(1,mPos_x);
posy0 = dataNav(1,mPos_y);

posx  = dataNav(:,mPos_x) - posx0;
posy  = dataNav(:,mPos_y) - posy0;

cposx = interp1(navtime,posx,mtime);clear posx;
cposy = interp1(navtime,posy,mtime);clear posy;


%% Create lat vector for pressure calculation
clat = repmat(mean(lat),length(ctdlog),1);
%% Compute pressure (db) from depth
pres = sw_pres(cdepth,clat);		% [db]

%%------------------------
%% Salinity
%%------------------------
% disp(['Computing Salinity']); [s] = salsp(ctdlog(:,conductivity),t,pres);
%% median filter salinity to remove spikes
% s=medfilt1(s,5);


%%------------------------
%% Biolume
%%------------------------
load biolume; biotime=biolume(:,time);
%% Interpolate to CTD time
biolum=interp1(biotime,biolume(:,biolum),mtime); clear depth
bioflow=interp1(biotime,biolume(:,flow),mtime); 
biotemp=interp1(biotime,biolume(:,temp),mtime); 

%%------------------------
%% 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 = 1;	% averaging interval, seconds 
disp(['Using average of ' avgint]);
%% make this avgint a menu choice...

[T,S,F,OBS,Biolum,Biotemp,Bioflow,time,depth,epochsec,pitch,roll,yaw,Xpos,Ypos] = aveCTDLL(t,s,f,obs,biolum,biotemp,bioflow,mtime,cdepth,cpitch,croll,cyaw,avgint,cposx,cposy);
plotallP
%%------------------------
%% Subset 
%%------------------------
plotallP;
%%------------------------
%% Endpoints and distance
%%------------------------

%% Plot


%%------------------------
%% Cleanup Options
%%------------------------
showmenu=1;

while showmenu
A=menu('Choices','Crop Time Limit','Excise portion','Filter a Variable','Start Processing Over','Plot path','Save','Save and Quit','Cancel');

if A==1			% Crop based on time limits
 plotallP;
 disp(['Select time subset']); [x y]=ginput(2);
 idx = find(time>=x(1) & time<=x(2));
 T=T(idx); S=S(idx); depth=depth(idx); time=time(idx);
 F=F(idx); OBS=OBS(idx); Biolum=Biolum(idx); Biotemp=Biotemp(idx); Bioflow=Bioflow(idx);
 epochsec=epochsec(idx); roll=roll(idx); pitch=pitch(idx); yaw=yaw(idx);Xpos=Xpos(idx);Ypos=Ypos(idx);
 plotallP;
 
elseif A==2		% Excise portion of a variable	   
   varcell=inputdlg('Which variable (T, S, Biolum, Biotemp, F, OBS)?','EXCISE',1);
   % varname=input('Which variable (T, S, Biolum, Biotemp, F, OBS)?','s');
     varname=varcell{1}
 eval(['wvar=' varname ';']);
   figure(2); clf; set(gcf,'units','pixels','position',[10 100 1000 500]);
   plot(wvar);
   B=1; 
   while B
      C=menu('Excise sections','Choose section','done');
      if C==1
         figure(2); [x y]=ginput(2); x=round(sort(x));
         if x(2)>length(F); x(2)=length(F); end
         if x(1)<1; x(1)=1;end
         wvar(x(1):x(2))=NaN;
      	clf; plot(wvar);
      else
         B=0; eval([varname '=wvar;']); plotallP
      end
   end
   
elseif A==3		% Filter a variable
   varcell=inputdlg('Which variable (T, S, Biolum, Biotemp, F, OBS)?','MEDIAN FILTER',1);
   varname=varcell{1}
   eval(['wvarO=' varname ';']); %% retain original
   wvarf=wvarO; 
 	figure(2); clf; set(gcf,'units','pixels','position',[10 100 1000 500]);
   plot(wvarO);
	B=1; 
   while B
      C=menu('Filter Options','median filter','restore original','save change');
      if C==1	% median filter
         wvarf=medfilt1(wvarf,5);      	
         figure(2); clf; plot(wvarO,'k'); hold on; plot(wvarf,'m');
      elseif C==2;
         wvarf=wvarO;
         figure(2); clf; plot(wvarf,'k');
      else
         B=0; eval([varname '=wvarf;']); plotallP
      end
   end
		           
elseif A==4 	% Start over
   clf;
   clean_menuP;
      
elseif A==5   % yoyo plot
   
   clf
   comet3(Xpos,Ypos,-depth)
   
elseif A==6		% Save
 disp(['Saving to file mission.mat']);
 %% Clear density where T/S has been deleted
 save mission T S F Biolum Biotemp Bioflow OBS epochsec depth startlat startlon roll pitch yaw Xpos Ypos
 disp(['Plotting cleaned mission...']);
 plotallP % check_mission
elseif A==7 %Save and Quit
    disp(['Saving to file mission.mat']);
 %% Clear density where T/S has been deleted
 save mission T S F Biolum Biotemp Bioflow OBS epochsec depth startlat startlon roll pitch yaw Xpos Ypos
 disp(['Plotting cleaned mission...']);
 plotallP % check_mission
 showmenu=0;
 close all;
else				% Keyboard Control
   showmenu=0;
   close all;
end

end

