function 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;
[aux_stations,ind_stns]=sort(vertcat(cnv_dlp.station));

if ~exist('staa'), staa=input('Input first station: '); end;
if ~exist('stab'), stab=input('Input last station: '); end;
if isempty(staa), staa=min(aux_stations); end;
if isempty(stab), stab=max(aux_stations); end;
 % Choose the sensor to check pri/sec
disp(' 0 = use the primary sensor (DEFAULT)' )
disp(' 1 = use the secondary sensor' )
pri_sec=input('Do you want to use the primary or the secondary sensor: ');
while (isempty(pri_sec)==1 | pri_sec<0 | pri_sec>1)
	disp('Please answer 0 (zero) for no or  1(one) for yes ')
	pri_sec=input('Do you want to use the primary or the secondary sensor: ');
end 




% Assumes stations are in "order" in cnv data array (which they should be
% since they were loaded with a "dir" command that puts things in order.
% And it turns out they may not be in the expected order. So aux_stations 
% has been rearranged (sorted) above so that we know the order.
sta_ini_idx = find(aux_stations==staa);
sta_end_idx = find(aux_stations==stab);    
% trick for replacing bottles
cond_match_ori=cond_match;
idx_sta=find(cond_match.stnnbr>=staa & cond_match.stnnbr<=stab)
% counter 
n=0;
bad_index=[];
for i = ind_stns(sta_ini_idx:sta_end_idx).',
close all
ii=find(cond_match.stnnbr==aux_stations(i) & cond_match.quality1==2);
if pri_sec==0
bottleCTDSal=cond_match.ctdsal1(ii);
bottleTmp=cond_match.ctdtmp1(ii);
ctdsal=cond_match.ctdsal1;
else
bottleCTDSal=cond_match.ctdsal2(ii);
bottleTmp=cond_match.ctdtmp2(ii);
ctdsal=cond_match.ctdsal2;
end
bottleSal=cond_match.btlsal(ii);
bottlePrs=cond_match.ctdprs(ii);
bottleNis=cond_match.niskinbtlpos(ii);

[figTS,figSP,figDeln]=drawplots(cnv_dlp(i),cond_match,idx_sta,pri_sec);

disp(['Working on Station : ',num2str(aux_stations(i))])
YN= input('Do you want check this station? ','s') 
if strcmpi(YN,'y')
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'),
n=n+1;
loop=1;
while loop==1    
        figure(figTS);
         title(['Station ' int2str(cnv_dlp(i).station)  ...
		':  Zoom in on current area of interest, type ' ...
		'''return'' when done']); 
       zoom on
        keyboard
        zoom off
         [x,y]=ginput(1);
         tx=find(abs(bottleSal-x)==min(abs(bottleSal-x)));
         plot(bottleSal(tx),bottleTmp(tx),'rx')
         text(bottleSal(tx),bottleTmp(tx),num2str(bottleNis(tx)))
    out1{1}=['Station', num2str(aux_stations(i))];
    out1{2}=[ '  niskin  ' 'sample  ' ' bottle sal' ' ctd sal ' '   difference'];
     for j=3:2+length(ii)
     out1{j}=sprintf('%2d %3d %2.4f %2.4f %1.5f',cond_match.niskinbtlpos(ii(j-2)),cond_match.sampnbr(ii(j-2)),... 
              cond_match.btlsal(ii(j-2)),ctdsal(ii(j-2)),cond_match.btlsal(ii(j-2))-ctdsal(ii(j-2)));  
      end
 s=textwrap(out1,100);
 h1=msgbox(s,['Station ', num2str(aux_stations(i))]);
 bad_index(n)=ii(tx)
 change_niskin=input( 'Do you want to change the niskin bottle number? ','s');
 if strcmpi(change_niskin,'y'),
  new_niskin=input('Input the new niskin bottle number: ')  
   aux=find(cond_match_ori.niskinbtlpos(ii)==new_niskin);
  if length(aux)>1
      aux=aux(1);
  end
  cond_match.ctdsal1(ii(tx))= cond_match_ori.ctdsal1(ii(aux));
  cond_match.ctdsal2(ii(tx))=cond_match_ori.ctdsal2(ii(aux));
  cond_match.ctdprs(ii(tx))=cond_match_ori.ctdprs(ii(aux));
  cond_match.ctdtmp1(ii(tx))=cond_match_ori.ctdtmp1(ii(aux));
  cond_match.ctdtmp2(ii(tx))=cond_match_ori.ctdtmp2(ii(aux));
  cond_match.ctdcon1(ii(tx))=cond_match_ori.ctdcon1(ii(aux));
  cond_match.ctdcon2(ii(tx))=cond_match_ori.ctdcon2(ii(aux));
  cond_match.niskinbtlpos(ii(tx))=new_niskin;
 else 
  cond_match.quality1(ii(tx))=4;
 end   
  loopy=input( 'Do you want to continue? ','s');     
  if strcmpi(loopy,'y'), 
  close(h1)    
  loop=1;
  figure(figTS);
  axis auto;
  n=n+1;
  else
  loop=0;
  close(h1)
  end
 end
else
	bad_index=bad_index;
end;

disp(['Now we go to the profile.']);
YN=input( 'Do you want to select from the SP profile? ','s');
if strcmpi(YN,'y'),
n=n+1
loop=1;
while loop==1    
        figure(figSP);
        if ~isempty(bad_index)
         plot(cond_match.btlsal(bad_index),cond_match.ctdprs(bad_index),'ro') 
       end
 title(['Station ' int2str(cnv_dlp(i).station)  ...
		':  Zoom in on current area of interest, type ' ...
		'''return'' when done']); 
       zoom on
        keyboard
        zoom off
         [x,y]=ginput(1);
         tx=find(abs(bottleSal-x)==min(abs(bottleSal-x)));
         plot(bottleSal(tx),bottlePrs(tx),'rx')
         text(bottleSal(tx),bottlePrs(tx),num2str(bottleNis(tx)))
    out1{1}=['Station', num2str(aux_stations(i))];
    out1{2}=[ '  niskin  ' 'sample  ' ' bottle sal' ' ctd sal ' '   difference'];
     for j=3:2+length(ii)
     out1{j}=sprintf('%2d %3d %2.4f %2.4f %1.5f',cond_match.niskinbtlpos(ii(j-2)),cond_match.sampnbr(ii(j-2)),... 
              cond_match.btlsal(ii(j-2)),ctdsal(ii(j-2)),cond_match.btlsal(ii(j-2))-ctdsal(ii(j-2)));  
      end
 s=textwrap(out1,100);
 h1=msgbox(s,['Station ', num2str(aux_stations(i))]);
 bad_index(n)=ii(tx)
 change_niskin=input( 'Do you want to change the niskin bottle number? ','s');
 if strcmpi(change_niskin,'y'),
  new_niskin=input('Input the new niskin bottle number: ')  
  aux=find(cond_match_ori.niskinbtlpos(ii)==new_niskin);
  if length(aux)>1
      aux=aux(1);
  end
  cond_match.ctdsal1(ii(tx))= cond_match_ori.ctdsal1(ii(aux));
  cond_match.ctdsal2(ii(tx))=cond_match_ori.ctdsal2(ii(aux));
  cond_match.ctdprs(ii(tx))=cond_match_ori.ctdprs(ii(aux));
  cond_match.ctdtmp1(ii(tx))=cond_match_ori.ctdtmp1(ii(aux));
  cond_match.ctdtmp2(ii(tx))=cond_match_ori.ctdtmp2(ii(aux));
  cond_match.ctdcon1(ii(tx))=cond_match_ori.ctdcon1(ii(aux));
  cond_match.ctdcon2(ii(tx))=cond_match_ori.ctdcon2(ii(aux));
  cond_match.niskinbtlpos(ii(tx))=new_niskin;
else 
  cond_match.quality1(ii(tx))=4;
 end   
  loopy=input( 'Do you want to continue? ','s');
  if strcmpi(loopy,'y'), 
  close(h1)    
  loop=1;
  figure(figTS);
  axis auto;
  n=n+1;
  else
  loop=0;
  close(h1)
  end
 end
else
	bad_index=bad_index;
end;

YN=input( 'Do you want to select from the normalized differences? ','s');
if strcmpi(YN,'y'),
   clear sta
   n=n+1
   loop=1;
   while loop==1    
   figure(figDeln);
   normS=bottleSal-bottleCTDSal; 
   sta(1:length(normS),1)=aux_stations(i); 
    if ~isempty(bad_index)
         plot(cond_match.stnnbr(bad_index),(cond_match.btlsal(bad_index)-ctdsal(bad_index)),'ro') 
    end 
    plot(sta,normS,'k+') 
     title(['Station ' int2str(cnv_dlp(i).station)  ...
		':  Zoom in on current area of interest, type ' ...
		'''return'' when done']); 
       zoom on
        keyboard
        zoom off
         [x,y]=ginput(1);
         tx=find(abs(normS-y)==min(abs(normS-y)));
         plot(sta(tx),normS(tx),'rx')
         text(sta(tx),normS(tx),num2str(bottleNis(tx)))
     clear out1    
     out1{1}=['Station', num2str(aux_stations(i))];
     out1{2}=[ '  niskin  ' 'sample  ' ' bottle sal' ' ctd sal ' '   difference'];
     for j=3:2+length(ii)
     out1{j}=sprintf('%2d %3d %2.4f %2.4f %1.5f',cond_match.niskinbtlpos(ii(j-2)),cond_match.sampnbr(ii(j-2)),... 
              cond_match.btlsal(ii(j-2)),ctdsal(ii(j-2)),cond_match.btlsal(ii(j-2))-ctdsal(ii(j-2)));  
     end
     s=textwrap(out1,100);
     h1=msgbox(s,['Station ', num2str(aux_stations(i))]);
     bad_index(n)=ii(tx)
     change_niskin=input( 'Do you want to change the niskin bottle number? ','s');
     if strcmpi(change_niskin,'y'),
     new_niskin=input('Input the new niskin bottle number: ')  
     aux=find(cond_match_ori.niskinbtlpos(ii)==new_niskin);
     if length(aux)>1
      aux=aux(1);
     end
       cond_match.ctdsal1(ii(tx))= cond_match_ori.ctdsal1(ii(aux));
       cond_match.ctdsal2(ii(tx))=cond_match_ori.ctdsal2(ii(aux));
       cond_match.ctdprs(ii(tx))=cond_match_ori.ctdprs(ii(aux));
       cond_match.ctdtmp1(ii(tx))=cond_match_ori.ctdtmp1(ii(aux));
       cond_match.ctdtmp2(ii(tx))=cond_match_ori.ctdtmp2(ii(aux));
       cond_match.ctdcon1(ii(tx))=cond_match_ori.ctdcon1(ii(aux));
       cond_match.ctdcon2(ii(tx))=cond_match_ori.ctdcon2(ii(aux));
     cond_match.niskinbtlpos(ii(tx))=new_niskin;
     else 
     cond_match.quality1(ii(tx))=4;
     end   
   loopy=input( 'Do you want to continue? ','s');     
   if strcmpi(loopy,'y'),   
   close(h1)
   loop=1;
   figure(figDeln);
   axis auto;
   n=n+1;
   else
   loop=0;
   close(h1)
   end
 end
else
	bad_index=bad_index;
end;
end
end

%%Save the conductivity summary structure.
save(db_file,'cond_match','-append');

%%%%%%%%  CMDR  return more to the original state
more(morestate);
%%%%%%%%

if nargout==0
    assignin('caller','ans',cond_match);
 else
    varargout{1}=cond_match;
end;

return;

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

col='bgrcmkbgrcmk';

figTS=figure;

figSP=figure;

figDeln=figure;

for istn=1:length({ctddat.station}),
	Ibot=find(ctddat(istn).station == botmatch.stnnbr & botmatch.quality1==2);
	Sb=botmatch.btlsal(Ibot);
    Pb=botmatch.ctdprs(Ibot);
	if pri_sec==0
    Tb=botmatch.ctdtmp1(Ibot);
    S=ctddat(istn).salpri;
	T=ctddat(istn).temppri;
    else
    Tb=botmatch.ctdtmp2(Ibot);
    S=ctddat(istn).salsec;
	T=ctddat(istn).tempsec; 
    end
	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;
    
aux=find(botmatch.quality1(idx_sta)==2);
	if pri_sec==0
    Sc=botmatch.ctdsal1(idx_sta(aux));
    else
    Sc=botmatch.ctdsal2(idx_sta(aux));    
    end
    Sb=botmatch.btlsal(idx_sta(aux));
	sta=botmatch.stnnbr(idx_sta(aux));
    d_idx=find(botmatch.ctdprs(idx_sta(aux))>1000);
    Delta=Sb-Sc;
    
    [params,extremes]=boxparams(Delta(~isnan(Delta)));
	ii=find(Delta>=params(5)| Delta<=params(1));
    figure(figDeln);
		nS=Delta;
		I=find(abs(nS)>0.02);
		plot(sta,nS,'.');
        hold on;
        plot(sta(d_idx),nS(d_idx),'r.');
		plot(sta(ii),nS(ii),'ko');
		title('Bottle and CTD difference');
		ylabel('difference (psu)');

return;

