function new_cond_match=check_bad_salt(cruiseid)
%CHECK_BAD_SALT - select bottle data points from salinity data
% 
%USAGE -	new_cond_match=check_bad_salt(cruiseid)
%
%EXPLANATION -	Identify points in the data and return a new cond_match with
%	the bad points in cond_match.btlsal removed, and the original data
%	points in cond_match.btlsalall
%
%SEE ALSO -	
%

%PROGRAM - 	MATLAB code by c.m.duncombe rae
%
%CREATED -	2008/02/07
%	$Revision: 1.15 $
%	$Date: 2008/04/12 18:32:43 $
%	$Id: check_bad_salt.m,v 1.15 2008/04/12 18:32:43 duncombe Exp duncombe $
%
%CHANGELOG -	
%  2008/02/14 CMDR
%	* check for no points selected
%  2008/03/11 CMDR
%	* debugging - fix missing end
%  2008/03/22 CMDR
%	* boxparams barfs on NaNs: fixt
%  2008/03/23 CMDR 
%	* one drawplots call appeared to be incorrect, returning the 
%	wrong output args. fixt.
%  2008/03/29 CMDR
%	* provide some statistics on the points chosen
%  2008/04/12 CMDR 
% 	* rearrange order in output table
%

%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 TS of the cnv_dlp data and the bottle salinities (cond_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('cond_match');
if isempty(n),
	error(['cond_match not found. Run make_cond_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 cond_match

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

bottleCTDSal=cond_match.ctdsal1;
bottleSal=cond_match.btlsal;
bottleTmp=cond_match.ctdtmp1;
bottlePrs=cond_match.ctdprs;

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

[figTS,figSP,figDel,figDeln]=drawplots(cnv_dlp,cond_match);
disp('Select bottle points');
disp(['We will start with the TS plot.']);
YN=input('Do you want to select from the TS plot? ','s');
if strcmpi(YN,'y'),
        figure(figTS);
	Indts=selectpts(bottleSal,bottleTmp);
else
	Indts=[];
end;

disp(['Now we go to the profile.']);
YN=input( 'Do you want to select from the SP profile? ','s');
if strcmpi(YN,'y'),
	figure(figSP);
	hold on; plot(bottleSal(Indts),bottlePrs(Indts),'k+');
	Indsp=selectpts(bottleSal,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'),
	normS=normaliz(bottleSal-bottleCTDSal);
	I=[1:length(normS)].';
	figure(figDeln);
	hold on; plot(I(Ind),normS(Ind),'k+');
	Inddel=selectpts(I,normS);
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_cond_match=cond_match;
new_cond_match.btlsalall=new_cond_match.btlsal;
new_cond_match.btlsal(bad_idx)=bad_idx.*NaN;

%% and plot
disp(	['We are done. This is what your data looks like with ' ...
	'the selected points removed.']);
figure;
	[figTSn,figSPn,figDel,figDeln]=drawplots(cnv_dlp,new_cond_match);

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

tabl=[];

Names={ 'stnnbr', 'btlnbr', 'niskinbtlpos', 'sampnbr', 'ctdprs', ...
	'btlsal', 'ctdsal1' };

for i=1:length(Names),
	tabfile=(['tabl=[tabl, cond_match.',Names{i},'(bad_idx)];']);
    eval(tabfile);
end;

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

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

percentbad=100.*length(bad_idx)./length(bottlePrs);
disp([num2str(length(bad_idx)) ' points chosen out of ' ...
	 num2str(length(bottlePrs)) '(' num2str(percentbad) '%)']);
disp(' ');

return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function drawplots
%%%%%%%%%%%%%%%%%%%%
function [figTS,figSP,figDel,figDeln]=drawplots(ctddat,botmatch)

col='bgrcmkbgrcmk';

figTS=figure;

figSP=figure;

figDeln=figure;
figDel=figure;

for istn=1:length({ctddat.station}),
	Ibot=find(ctddat(istn).station == botmatch.stnnbr);
	Sb=botmatch.btlsal(Ibot);
	Tb=botmatch.ctdtmp1(Ibot);
	Pb=botmatch.ctdprs(Ibot);
	S=ctddat(istn).salpri;
	T=ctddat(istn).temppri;
	P=ctddat(istn).pressure;

	figure(figTS);
		plot(S,T,col(istn)); 
		hold on;
		plot(Sb,Tb,[col(istn) 'x']);
		title('TS Plot');
		xlabel('Salinity');
		ylabel('Temperature');

	figure(figSP);
		plot(S,P,col(istn));
		set(gca,'ydir','reverse');
		hold on;
		plot(Sb,Pb,[col(istn) 'x']);
		title('Salinity Profile');
		xlabel('Salinity');
		ylabel('Pressure');

end;
	Sc=botmatch.ctdsal1;
	Sb=botmatch.btlsal;
	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 Salinity - CTD Salinity');

return;

