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_dlp');
if isempty(n),
	%error(['cnv_dlp not found. Run deloop.m ']);
	%return;
    cnv_dlp=cnv_load;
end;

[aux_stations,ind_stns]=sort(vertcat(cnv_dlp.station));

disp('****************************************** ')
disp(['The data goes from station ',num2str(min(oxy_match.stnnbr)),' to the station ', ...
	num2str(max(oxy_match.stnnbr)),'.'] ) 
disp('****************************************** ')

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;

% 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
oxy_match_ori=oxy_match;
idx_sta=find(oxy_match.stnnbr>=staa & oxy_match.stnnbr<=stab);
% counter 
n=0;
bad_index=[];
for i = ind_stns(sta_ini_idx:sta_end_idx).',
    
close all
ii=find(oxy_match.stnnbr==aux_stations(i) & oxy_match.quality1==2);    
bottleCTDOxy=oxy_match.oxmmpri(ii);
bottleOxy=oxy_match.btloxy(ii);
bottleTmp=oxy_match.ctdtmp1(ii);
bottlePrs=oxy_match.ctdprs(ii);
bottleNis=oxy_match.niskinbtlpos(ii);
% should ask about which stations to process. meantime, plot them all


[figTO,figOP,figDeln]=oxycheckplots(cnv_dlp(i),oxy_match,idx_sta);
%f3,f2,f1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Figure 1 - T-O plot

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 TO plot.']);
YN=input('Do you want to select from the TO plot? ','s');
if strcmpi(YN,'y'),
n=n+1;
loop=1;
while loop==1    
        figure(figTO);
         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(bottleOxy-x)==min(abs(bottleOxy-x)));
         plot(bottleOxy(tx),bottleTmp(tx),'rx')
         text(bottleOxy(tx),bottleTmp(tx),num2str(bottleNis(tx)))
    out1{1}=['Station', num2str(aux_stations(i))];
    out1{2}=[ '  niskin  ' 'sample  ' ' btl oxy     ' '   ctd oxy ' '    difference'];
     for j=3:2+length(ii)
     out1{j}=sprintf('%2d                %3d       %2.4f       %2.4f       %1.5f',... 
         oxy_match.niskinbtlpos(ii(j-2)),oxy_match.sampnbr(ii(j-2)),... 
              oxy_match.btloxy(ii(j-2)),oxy_match.oxmmpri(ii(j-2)),...
              oxy_match.btloxy(ii(j-2))-oxy_match.oxmmpri(ii(j-2)));  
     end;
 s=textwrap(out1,100);
 h1=msgbox(s,['Station ', num2str(aux_stations(i))]);
 %close(h1) %JH edit
 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(oxy_match_ori.niskinbtlpos(ii)==new_niskin);
  if length(aux)>1
      aux=aux(1);
  end;
  oxy_match.oxmmpri(ii(tx))= oxy_match_ori.oxmmpri(ii(aux));
     oxy_test=oxy_match.oxmmpri;
     if isnan(oxy_test)==0
     oxy_match.oxmmpri(ii(tx))=oxy_match_ori.oxmmpri(ii(aux));
     oxy_match.ctdtmp1(ii(tx))=oxy_match_ori.ctdtmp1(ii(aux));
     oxy_match.ctdcon1(ii(tx))=oxy_match_ori.ctdcon1(ii(aux));
     end;
  oxy_match.ctdprs(ii(tx))=oxy_match_ori.ctdprs(ii(aux));
  oxy_match.ctdtmp1(ii(tx))=oxy_match_ori.ctdtmp1(ii(aux));
  oxy_match.ctdcon1(ii(tx))=oxy_match_ori.ctdcon1(ii(aux));
  oxy_match.niskinbtlpos(ii(tx))=new_niskin;
 else 
  oxy_match.quality1(ii(tx))=4;
 end;   
  loopy=input( 'Do you want to continue? ','s');     
  if strcmpi(loopy,'y'), 
  close(h1)    
  loop=1;
  figure(figTO);
  axis auto;
  n=n+1;
  else
  loop=0;
  close(h1)
  end;
end;
else
	bad_index=bad_index
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Figure 2 - Oxygen v Pressure plot

disp(['Now we go to the profile.']);
YN=input( 'Do you want to select from the OP profile? ','s');
if strcmpi(YN,'y'),
n=n+1
loop=1;
while loop==1    
        figure(figOP);
        if ~isempty(bad_index)
         plot(oxy_match.btloxy(bad_index),oxy_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(bottleOxy-x)==min(abs(bottleOxy-x)));
         plot(bottleOxy(tx),bottlePrs(tx),'rx')
         text(bottleOxy(tx),bottlePrs(tx),num2str(bottleNis(tx)))
    out1{1}=['Station', num2str(aux_stations(i))];
    out1{2}=[ '  niskin  ' 'sample  ' ' btl oxy     ' '   ctd oxy ' '    difference'];
     for j=3:2+length(ii)
     out1{j}=sprintf('%2d                %3d       %2.4f       %2.4f       %1.5f',...
         oxy_match.niskinbtlpos(ii(j-2)),oxy_match.sampnbr(ii(j-2)),... 
              oxy_match.btloxy(ii(j-2)),oxy_match.oxmmpri(ii(j-2)),...
              oxy_match.btloxy(ii(j-2))-oxy_match.oxmmpri(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(oxy_match_ori.niskinbtlpos(ii)==new_niskin);
  if length(aux)>1
      aux=aux(1);
  end;
  oxy_match.oxmmpri(ii(tx))= oxy_match_ori.oxmmpri(ii(aux));
    oxy_test=oxy_match.oxmmpri;
     if isnan(oxy_test)==0
     oxy_match.oxmmpri(ii(tx))=oxy_match_ori.oxmmpri(ii(aux));
     oxy_match.ctdtmp1(ii(tx))=oxy_match_ori.ctdtmp1(ii(aux));
     oxy_match.ctdcon1(ii(tx))=oxy_match_ori.ctdcon1(ii(aux));
     end;
  oxy_match.ctdprs(ii(tx))=oxy_match_ori.ctdprs(ii(aux));
  oxy_match.ctdtmp1(ii(tx))=oxy_match_ori.ctdtmp1(ii(aux));
  oxy_match.ctdcon1(ii(tx))=oxy_match_ori.ctdcon1(ii(aux));
  oxy_match.niskinbtlpos(ii(tx))=new_niskin;
else 
  oxy_match.quality1(ii(tx))=4;
 end;   
  loopy=input( 'Do you want to continue? ','s');
  if strcmpi(loopy,'y'), 
  close(h1)    
  loop=1;
  figure(figTO);
  axis auto;
  n=n+1;
  else
  loop=0;
  close(h1)
  end;
end;
else
	bad_index=bad_index
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Figure 3 - Plot of Bottle differences v Station number
if 0,
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=bottleOxy-bottleCTDOxy; 
   sta(1:length(normS),1)=aux_stations(i); 
    if ~isempty(bad_index)
         plot(oxy_match.stnnbr(bad_index),(oxy_match.btloxy(bad_index)-oxy_match.oxmmpri(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  ' ' btl oxy     ' '   ctd oxy ' '    difference'];
     for j=3:2+length(ii)
     out1{j}=sprintf('%2d                %3d       %2.4f       %2.4f       %1.5f',...
         oxy_match.niskinbtlpos(ii(j-2)),oxy_match.sampnbr(ii(j-2)),... 
              oxy_match.btloxy(ii(j-2)),oxy_match.oxmmpri(ii(j-2)),...
              oxy_match.btloxy(ii(j-2))-oxy_match.oxmmpri(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(oxy_match_ori.niskinbtlpos(ii)==new_niskin);
     if length(aux)>1
      aux=aux(1);
     end;
     oxy_match.oxmmpri(ii(tx))= oxy_match_ori.oxmmpri(ii(aux));
     oxy_test=oxy_match.oxmmpri;
     if isnan(oxy_test)==0
     oxy_match.oxmmpri(ii(tx))=oxy_match_ori.oxmmpri(ii(aux));
     oxy_match.ctdcon1(ii(tx))=oxy_match_ori.ctdcon1(ii(aux));
     oxy_match.ctdtmp1(ii(tx))=oxy_match_ori.ctdtmp1(ii(aux));
     end;
     oxy_match.ctdprs(ii(tx))=oxy_match_ori.ctdprs(ii(aux));
     oxy_match.ctdtmp1(ii(tx))=oxy_match_ori.ctdtmp1(ii(aux));
     oxy_match.ctdcon1(ii(tx))=oxy_match_ori.ctdcon1(ii(aux));
     oxy_match.niskinbtlpos(ii(tx))=new_niskin;
     else 
     oxy_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; %btl oxy station check
end; %if 0
end; % if check y

end; % station check for loop

oxy_match.quality2=oxy_match.quality1;

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

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

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

close all;

return;


