function new_oxy_match=check_bad_oxy(cruiseid)
%CHECK_BAD_OXY - select bottle data points from oxygen data
% 
%USAGE -	new_oxy_match=check_bad_oxy(cruiseid)
%
%EXPLANATION -	Identify points in the data and return a new oxy_match with
%	the bad points in oxy_match.btloxy removed, and the original data
%	points in oxy_match.btloxyall
%
%SEE ALSO -	
%

%PROGRAM - 	MATLAB code by c.m.duncombe rae
%
%CREATED -	2008/02/07
%	$Revision: 1.11 $
%	$Date: 2008/03/23 17:41:26 $
%	$Id: check_bad_oxy.m,v 1.11 2008/03/23 17:41:26 duncombe Exp duncombe $
%
%CHANGELOG -	
%  2008/02/10 CMDR
%	* make a copy of check_bad_salt and edit it to do oxygen
%  2008/02/14 CMDR
%	* check for no points selected
%  2008/03/23 CMDR 
% 	* check differences between bottle and ctd
%
%DISCLAIMER -	No responsibility can be accepted for failure or 
%		incorrect operation of this code. No guarantee, express 
%		or implied, is given. 
%

%
%PROGRAMMING NOTES
% plot a nice TO of the cnv_dlp data and the bottle oxygens (oxy_match)
% use selectpts to choose bad looking bottles
% write a nice table of the chosen points

if nargin==0, cruiseid=getcruiseid; end;
if isempty(cruiseid), cruiseid=getcruiseid; end;

group = group_name(cruiseid);

% cruise_dir is the main calibration data directory 
if ispref(group,'cal_data_dir')
	cruise_dir=getpref(group,'cal_data_dir');
else
	error(['The cal_data_dir preference was not set for cruise: ' ...
		cruiseid '.  Run register_cruise.m']);
end;

db_file = fullfile(cruise_dir,[cruiseid '_db.mat']);
if exist(db_file)==2
	load(db_file);
else
	error(['The cruise data base file was not found on the path.  ' ...
		db_file]);
end;

n=who('oxy_match');
if isempty(n),
	error(['oxy_match not found. Run make_oxy_sum.m ']);
	return;
end;

morestate=get(0,'more');
more off;

% comparing bottle data with ctd data
% ctd data to use is cnv_cal or cnv_dlp or poss cnv_raw
% bottle data is in oxy_match

%%% Hah! above comment applies to conductivity. Oxygen, we do not start with
%%% any good kind of calibration, so we have no good kind of CTD data to try. 
%%% We go straight to calibrated data.

% n=who('cnv_dlp');
% if isempty(n),
% 	error(['cnv_dlp not found. Run deloop.m ']);
% 	return;
% end;

n=who('cnv_cal');
if isempty(n),
	error(['cnv_cal not found. Run through calibration procedure first']);
	return;
end;

bottleCTDOxy=oxy_match.ctdoxy1;
bottleOxy=oxy_match.btloxy;
bottleTmp=oxy_match.ctdtmp1;
bottlePrs=oxy_match.ctdprs;

% should ask about which stations to process. meantime, plot them all

[figTO,figOP,figDel,figDeln]=drawplots(cnv_cal,oxy_match);
disp('Select bottle points');
disp(['We will start with the TO plot.']);
YN=input('Do you want to select from the TO plot? ','s');
if strcmpi(YN,'y'),
        figure(figTO);
	Indts=selectpts(bottleOxy,bottleTmp);
else
	Indts=[];
end;

disp(['Now we go to the profile.']);
YN=input( 'Do you want to select from the OP profile? ','s');
if strcmpi(YN,'y'),
	figure(figOP);
	% we have some pts chosen already, plot them here
	hold on; plot(bottleOxy(Indts),bottlePrs(Indts),'k+');
	Indsp=selectpts(bottleOxy,bottlePrs);
else
	Indsp=[]; 
end;

% combine Indts and Indsp
Ind=sort([Indts; Indsp]);
if ~isempty(Ind), Ind=[Ind(1); Ind(find(diff(Ind))+1)]; else Ind=[]; end;

YN=input( 'Do you want to select from the normalized differences? ','s');
if strcmpi(YN,'y'),
	normO=normaliz(bottleOxy-bottleCTDOxy);
	I=[1:length(normO)].';
	figure(figDeln);
	hold on; plot(I(Ind),normO(Ind),'k+');
	Inddel=selectpts(I,normO);
else
	Inddel=[];
end;


%% get all the points, removing duplicates
% size(Indts)
% size( Indsp)
I=sort([Ind; Inddel]);
if ~isempty(I), bad_idx=[I(1); I(find(diff(I))+1)]; else bad_idx=[]; end;

new_oxy_match=oxy_match;
new_oxy_match.btloxyall=new_oxy_match.btloxy;
new_oxy_match.btloxy(bad_idx)=bad_idx.*NaN;

%% and plot
disp(	['We are done. This is what your data looks like with ' ...
	'the selected points removed.']);
figure;
	[figTOn,figOPn,figDeln]=drawplots(cnv_cal,new_oxy_match);

% write the table of points chosen: station, niskin, depth, etc

tabl=[];

Names={ 'stnnbr', 'sampnbr', 'btlnbr', 'niskinbtlpos', 'ctdprs', ...
	'btloxy', 'ctdoxy1' };

for i=1:length(Names),
	tabl=[tabl, oxy_match.(Names{i})(bad_idx)];
end;

form=[reshape(['%g\t'].'*ones(1,length(Names)-1),1,[]),'%g\n'];

disp( ...
sprintf('\nStn\tSmpBNo\tNskBNo\tNskPos\tCTDPrs\tBtlOxy\tCTDOxy'));
disp(sprintf(form,tabl.'));

return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function drawplots
%%%%%%%%%%%%%%%%%%%%
function [figTO,figOP,figDel,figDeln]=drawplots(ctddat,botmatch)

col='bgrcmkbgrcmk';
figTO=figure;
figOP=figure;
figDeln=figure;
figDel=figure;

for istn=1:length({ctddat.station}),
	Ibot=find(ctddat(istn).station == botmatch.stnnbr);
	Sb=botmatch.btloxy(Ibot);
	Tb=botmatch.ctdtmp1(Ibot);
	Pb=botmatch.ctdprs(Ibot);
	S=ctddat(istn).oxymll;
	T=ctddat(istn).temp;
	P=ctddat(istn).pressure;
	figure(figTO);
		plot(S,T,col(istn)); 
		hold on;
		plot(Sb,Tb,[col(istn) 'x']);
		title('TO PLot');
		xlabel('Oxygen');
		ylabel('Temperature');
	figure(figOP);
		plot(S,P,col(istn));
		set(gca,'ydir','reverse');
		hold on;
		plot(Sb,Pb,[col(istn) 'x']);
		title('Oxygen Profile');
		xlabel('Oxygen');
		ylabel('Pressure');
end;
	Sc=botmatch.ctdoxy1;
	Sb=botmatch.btloxy;
	Delta=Sb-Sc;
	figure(figDeln);
		nS=normaliz(Delta);
		I=find(abs(nS)>2);
		plot(nS,'.');
		hold on;
		plot(I,nS(I),'ro');
		title('Bottle and CTD difference');
		ylabel('normalized difference (units of Std Dev)');

	figure(figDel);
		[params,extremes]=boxparams(Delta(~isnan(Delta)));
		boxplotter1(params,extremes,'Bottle Oxygen - CTD Oxygen');

return;

