function [cnv_cal,fh] =FS_apply_calibration(varargin)
% FS_APPLY_CALIBRATION - apply oxygen and conductivity calibration
%	Prepare data tables and a postscript file of figures.
%
% CTD Calibration toolbox.
%
% USAGE:
% [cnv_cal,fh] =FS_apply_calibration(cruiseid, cond_coeff, oxy_coeff)
% 	or
% [cnv_cal,fh] =FS_apply_calibration( ...
%		cruiseid, offset_fit, slope_fit, prcor, oxy_coeff )
%
% INPUT
%	cruiseid	cruise identification name
%       cond_coeff	vector with coefficients from cond_cal.m
%	oxy_coeff	vector with coefficients from oxy_cal.m
%   
% OUTPUT
%	cnv_cal		calibrated CTD data
%          
% DESCRIPTION
%	still to write
% 

% AUTHORS:
%			Carlos Fonseca 
%         UM/CIMAS
%         Derrick Snowden
%         NOAA/AOML/PhOD
%         Tue May 11 11:23:37 EDT 2004
%
% 
% VERSION: 
%	$Revision: 1.25 $
%	$Date: 2008/04/20 20:10:34 $
%	$Id: FS_apply_calibration.m,v 1.25 2008/04/20 20:10:34 duncombe Exp duncombe $
%
% CHANGELOG: 
%   07-Oct-2004, Version 1.0
%		* Initial version. 
%
% Modified by Rigo Garcia in 5/3/2007 to be applied to the CTD in the
% Florida Straits
%
%  2007/12/17  CMDR
%	* read cruise id from the file in the current directory
%	* comments 
%	* use a function for oxygen saturation calculation
% 	* make input lines easier to read (aesthetic adjustment!)
%	* make functions cond_cal and FS_apply_calibration have the same input
%	and output arguments to facilitate cut and paste
%	* make functions oxy_cal and FS_apply_calibration have the same input
%	and output arguments to facilitate cut and paste
%  2008/01/10  CMDR
%	* return the figure handles to facilitate later access to the figures
%	* input cond_coeff structure instead of individual constants
%  2008/01/11 CMDR
%	* use the oxygen saturation function from the seawater toolbox
%  2008/01/15 CMDR
%	* output a line that tells we printed the figures
%  2008/02/18 CMDR
%	* comments and style
%  2008/03/10 CMDR
%	* provide some defaults for staa and stab; vectorize some loops
%  2008/03/14 CMDR
% 	* add fieldname cruiseid to the cnv_cal structure
%  2008/03/15 CMDR
%	* fix mistake with pcor (oxygen) and prcor (conductivity). Sorry!
%	* defaults for sensor 
%  2008/04/14 CMDR
% 	* deleted a lot of code that had been commented out. To see those
% 	deletions, refer to the RCS record.
%	* apply calibrations for the beckman sensor in this module as well,
%	making the appropriate tests.
%	* fix bug (~isempty(blist))
%  2008/04/20 CMDR 
%	* sort to ensure the order for the stations is known. Some cruises
%	generated misnamed data files that end up poorly ordered in the 
%	directories
%

% function [cnv_cal,fh] =FS_apply_calibration(cruiseid, cond_coeff, oxy_coeff)
% function [cnv_cal,fh] =FS_apply_calibration(cruiseid,offset_fit,...
% 	slope_fit,prcor,oxy_coeff)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%% INITIALIZE %%%%%%%%%%%%

flag_message1=0;
flag_message2=0;
flag_conv1=0;
flag_conv2=0;
beckman_flag=0; % initially assume we are using an sbe43 sensor
%
%%%%%%%%% CMDR figure handles
fig_cnt=0;

narg=nargin;
%%%%%%%%%%% CMDR Expecting two different types of call. Differentiate.
%% nargin<3 is a bad call, because we need to see the calib coeffs
if nargin==3,
	cruiseid=varargin{1};
	cond_coeff=varargin{2};
		offset_fit=cond_coeff{2};
		slope_fit=cond_coeff{4};
% CMDR - prcor is for conductivity
		prcor=cond_coeff{5};
 	oxy_coeff=varargin{3};
elseif nargin==5,
        cruiseid=varargin{1};
	offset_fit=varargin{2};
	slope_fit=varargin{3};
% CMDR - pcor is for oxygen
	pcor=varargin{4};
	oxy_coeff=varargin{5};
else,
	disp('   ');
	disp('Bad call to FS_apply_calibration: wrong number of arguments');
	disp('   ');
	disp('USAGE:');
	disp(['[cnv_cal,fh] =FS_apply_calibration(cruiseid, cond_coeff, ' ...
		'oxy_coeff)']);
	disp('      or');
	disp('[cnv_cal,fh] =FS_apply_calibration(cruiseid,offset_fit, ...');
	disp('              slope_fit,prcor,oxy_coeff)');
	disp('   ');
	cnv_cal=[]; fh=[];
	return;
end;
if isempty(cruiseid), cruiseid=getcruiseid; end;
%%%%%%% CMDR end

% Retrieve the necessary preferences for this cruise
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

%%%%%%%%%%%%%%% LOAD DATABASE %%%%%%%%%%%%%%
% Load data from the cruise database
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('cnv_dlp');

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

%%%%%%%%%%%%%%% GET DESIRED ACTIONS %%%%%%%%%%

disp(['**************************************************************' ...
	'******************']);
disp(['This is the program that applies the calibration coefficients ']);
disp(['to the .cnv delooped data.']);
disp(['**************************************************************' ...
	'******************']);

disp(['***************************************************************' ...
	'*****************']);
disp(' 0 = use the primary sensor (DEFAULT)' )
disp(' 1 = use the secondary sensor' )
disp('First for the conductivity sensor:')
pri_sec_c=input(['Do you want apply the calibration to the primary ', ...
	'or to the secondary sensor: ']);
% while (isempty(pri_sec_c)==1 | pri_sec_c<0 | pri_sec_c>1)
while ( pri_sec_c<0 | pri_sec_c>1)
	disp('Please answer 0 (zero) for no or  1(one) for yes ')
	pri_sec_c=input(['Do you want to use the primary ', ...
		'or the secondary sensor: ']);
end;
if isempty(pri_sec_c), pri_sec_c=0; end;

disp('Now, for the oxygen sensor:')
pri_sec_o=input(['Do you want apply the calibration to the primary ', ...
	'or to the secondary sensor: ']);
% while (isempty(pri_sec_o)==1 | pri_sec_o<0 | pri_sec_o>1)
while ( pri_sec_o<0 | pri_sec_o>1)
	disp('Please answer 0 (zero) for no or  1(one) for yes ')
	pri_sec_o=input(['Do you want to use the primary ', ...
		'or the secondary sensor: ']);
end
if isempty(pri_sec_o), pri_sec_o=0; end;

disp(['***********************************************************', ...
	'****************']);
if ~exist('staa'), staa=input('Input first station: '); end;
if ~exist('stab'), stab=input('Input last station: '); end;
if isempty(staa), staa=min([cnv_dlp.station]); end;
if isempty(stab), stab=max([cnv_dlp.station]); end;
%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%% APPLY CALIBRATIONS %%%%%%%%%%%%%%

%max_cnv=max(size(cnv));
%for i=1:max_cnv;
%% count for postscript pages
pscount=-1; 

% we need to be very sure which order the stations are being accessed, so 
% set up aux_stations so that we do not need to rely on any arbitrary order
% that the variable structure might have been created in.
[aux_stations,ind_stns]=sort(vertcat(cnv_load.station));

% vectorize a loop
sta_min_idx=find(staa==aux_stations);
sta_max_idx=find(stab==aux_stations);

%% for each station desired...
for i = ind_stns(sta_min_idx:sta_max_idx).',
    sta=cnv_dlp(i).station;
    disp(['Applying the calibrations to the station ',num2str(sta)]) 
    pscount=pscount+1;
    press_aux=cnv_dlp(i).pressure;
    if pri_sec_c==0,
       cond_aux=cnv_dlp(i).condpri.*10;
       aux_dcdp=gradient(cond_aux);
       temp_aux=cnv_dlp(i).temppri;
       %oxyvolt_aux=cnv_dlp(i).oxvpri;
       %oxyvolt_aux=smooth(press_aux,oxyvolt_aux, 0.02,'loess');
    else
       cond_aux=cnv_dlp(i).condsec.*10;
       aux_dcdp=gradient(cond_aux);
       temp_aux=cnv_dlp(i).tempsec;
       %oxyvolt_aux=cnv_dlp(i).oxvsec;
       %oxyvolt_aux=smooth(press_aux,oxyvolt_aux, 0.02,'loess');
    end; % if pri_sec_c==0 

% if we have a Beckman sensor, cnv_dlp.oxv* do not exist and cnv_dlp.oxc* 
% and cnv_dlp.oxct* do exist; and conversely if we have an SBE43 sensor, 
% then cnv_dlp.oxc* and cnv_dlp.oxct* do not exist and cnv_dlp.oxv* do exist.

if any(isfield(cnv_dlp,{'oxctpri','oxctsec','oxcpri','oxcsec'})),
	% we surely have a beckman sensor; and we want current and temperature
	beckman_flag=1;
    if pri_sec_o==0,
       oxycurr_aux=cnv_dlp(i).oxcpri;
       oxycurrt_aux=cnv_dlp(i).oxctpri;
    else
       oxycurr_aux=cnv_dlp(i).oxcsec;
       oxycurrt_aux=cnv_dlp(i).oxctsec;
    end; % if pri_sec_o==0,
    
else
	% it must be a sbe43 sensor; and we want voltages
	beckman_flag=0;
    if pri_sec_o==0,
       oxyvolt_aux=cnv_dlp(i).oxvpri;
    else
       oxyvolt_aux=cnv_dlp(i).oxvsec;
    end; % if pri_sec_o==0,
end;

    sal_oxy=sw_salt(cond_aux./sw_c3515,temp_aux,press_aux);   

%%
    % correcting the conductivity
    %value for the offset
%% seems to me a whole chunk of code can be replaced by:
    offset_cor=polyval(offset_fit,sta);    

  %value for the slope
%% Seems to me a whole chunk of code can be replaced by:
    slope_cor=polyval(slope_fit,sta);

  % offset correction
  condc=cond_aux+offset_cor;
  % slope_correction
  condc=condc+(slope_cor*(condc));
  % pressure correction
  condc=condc+(polyval(prcor,sta)*(press_aux));  
  sal_aux=sw_salt(condc./sw_c3515,temp_aux,press_aux); 
   
   % correcting the oxygen (oxy fit 3.01 std dev)
   % calculating oxygen saturation
%%%%%%%%%%% CMDR use seawater O2 saturation function
	oxsat=sw_satO2(temp_aux,sal_oxy);
%%%%%%%%%%%

%%%%
   % calibration coefficients for the oxygen sensor
if ~beckman_flag, 	% we are using an SBE43
  Soc=oxy_coeff(1); Voffset=oxy_coeff(2); Boc=oxy_coeff(3); tcor=oxy_coeff(4);
  pcor=oxy_coeff(5); p1=oxy_coeff(6); p2=oxy_coeff(7); gama=oxy_coeff(8);

  stn=repmat(sta,length(oxyvolt_aux),1);
  new_oxy=((Soc.*(oxyvolt_aux+Voffset))+(Boc.*exp(-0.03.*temp_aux))+ ...
	((p1.*stn)+(p2.*(stn.^2)))+ ...
	(gama*press_aux)).*exp(tcor.*temp_aux).*oxsat.*exp(pcor.*press_aux);

else			% we ARE using a Beckman sensor

  % calibration coefficients for the oxygen
  Soc=oxy_coeff(1); wt=oxy_coeff(2); Boc=oxy_coeff(3); tcor=oxy_coeff(4);
  pcor=oxy_coeff(5); tau=oxy_coeff(6); p1=oxy_coeff(7); p2=oxy_coeff(8);
  gama=oxy_coeff(9);

  stn=repmat(sta,length(oxycurr_aux),1);
  docdt_aux=weim(31,'hann',gradient(oxycurr_aux))';
  new_oxy=((Soc.*(oxycurr_aux+(tau.*docdt_aux)))+Boc+(p1.*stn+p2.*stn.^2)+ ...
	(gama.*press_aux)).*exp(tcor.*(temp_aux+ ...
	(wt*(oxycurrt_aux-temp_aux)))).*oxsat.*exp(pcor.*press_aux);

end; % if ~beckman_flag,
%%%%

  % saving the variables
  cnv_cal(i).cruiseid=cnv_dlp(i).cruiseid;
  cnv_cal(i).station=cnv_dlp(i).station;
  cnv_cal(i).latitude=cnv_dlp(i).latitude;
  cnv_cal(i).longitude=cnv_dlp(i).longitude;
  cnv_cal(i).gtime=cnv_dlp(i).gtime;
  cnv_cal(i).pressure(:,1)=press_aux;
  cnv_cal(i).depth(:,1)=sw_dpth(press_aux,cnv(i).lat);
  cnv_cal(i).temp(:,1)=temp_aux;
  cnv_cal(i).pottemp(:,1)=sw_ptmp(sal_aux,temp_aux,press_aux,0);
  cnv_cal(i).salt(:,1)=sal_aux;
  cnv_cal(i).cond(:,1)=condc;

  % converting the oxygen to micromol/kg
  oxy_aux=ox_units(new_oxy,sal_oxy,sw_ptmp(sal_oxy,temp_aux,press_aux,0), ...
		'mll2mmk');
  cnv_cal(i).oxyumol(:,1)=oxy_aux;
  cnv_cal(i).oxymll(:,1)=new_oxy;

  % calculating the dynamic height
  svan = sw_svan(sal_aux,temp_aux,press_aux);
  clear dh;
  for k=1:length(svan),
    dh(k)=sum(svan(1:k))*1000;
  end;
  cnv_cal(i).dynheight(:,1)=dh;     

    % calculating sigma-theta
  pden = sw_pden(sal_aux,temp_aux,press_aux,0)-1000;
  cnv_cal(i).sigma0(:,1)=pden; 

 %%%%%%%%% 
  % calculating gamma (neutral density)
  gamma_aux=gamma_n(sal_aux, ...
	t90tot68(temp_aux),press_aux,cnv_dlp(i).longitude,cnv_dlp(i).latitude);
  cnv_cal(i).gamma(:,1)=gamma_aux; 
 %%%%%%%%% 
  %  selecting the bottles of the station

%%%%%%%%%%%%%%% DISPLAY THE RESULTS %%%%%%%%%%%%%%%%

 blist=find(cond_match.stnnbr==sta);
 olist=find(oxy_match.stnnbr==sta);

  %plotting the data
  
  laty=cnv_dlp(i).latitude;
  lonx=cnv_dlp(i).longitude;
  botstr=num2str(floor(cond_match.ctdprs(blist)));
  hr=floor(cnv_dlp(i).gtime(4));
  mn=floor(cnv_dlp(i).gtime(5));
  sc=floor(cnv_dlp(i).gtime(6));
  date0=datenum(cnv_dlp(i).gtime(1),cnv_dlp(i).gtime(2), ...
		cnv_dlp(i).gtime(3),hr,mn,sc);
  dstr=datestr(date0,0);
  dstr0=dstr(1:17);

  latstr0=sprintf('%7.3f',laty);
  lonstr0=sprintf('%7.3f',abs(lonx));

  ctd0=sprintf('%s','Florida Straits R/V FG Walton Smith');
  sname=strcat('CTD',sprintf('%03d',sta));
  ctd4=['Latitude',latstr0, ' N'];
  ctd1=[sprintf('%s','CTD Station ',int2str(sta)),'  (' , sname, ')'];
  ctd5=['Longitude',lonstr0, ' W'];
  ctd3=sprintf('%s',dstr0,' Z');

%%%%%%%%% CMDR figure handles
fig_cnt=fig_cnt+1;
fh(fig_cnt)=figure;
%%%%%%%%%
hl1=plot(cnv_cal(i).pottemp,cnv_cal(i).pressure,'k');
min_y=0;
max_y=max(cnv_cal(i).pressure+100);
axis([0 30 min_y max_y]);
set(gca,'position',[0.1 0.1 0.45 0.8]);
set(hl1,'linewidth',2);
ax1=gca;
grid on;

set(ax1,'XMinorTick','on','ydir','reverse', 'box','on', ...
		'xcolor',get(hl1,'color'))
xlabel('Potential Temperature (Deg. C)');
ylabel('Pressure (dbar)');
text(5,-0.120*max_y,[ctd0],'FontWeight','bold');  %Cruise Number
text(9,-0.09*max_y,[ctd1],'FontWeight','bold');   %CTD Station Number
text(9,-0.03*max_y,[ctd3],'FontWeight','bold');   %Time
text(5,-0.060*max_y,[ctd4],'FontWeight','bold');  %Latitude
text(16,-0.060*max_y,[ctd5],'FontWeight','bold'); %Longitude
hold on


for oo=1:length(blist),
   %bottle pressures
   bhan(oo)=text(30.1,cond_match.ctdprs(blist(oo)),botstr(oo,:),'FontSize',6);
end;

[hl2,ax2] = floatAxisX(cnv_cal(i).salt,cnv_cal(i).pressure,'k', ...
	'Salinity (PSS-78)',[33.7 37.3 min_y max_y]);
%set(ax2,'ydir','reverse');
set(ax2,'ydir','reverse','ylim',[min_y max_y],'xlim',[33.7 37.3]);
set(hl2,'linewidth',0.5);

[hl3,ax3] = floatAxisX(cnv_cal(i).oxyumol,cnv_cal(i).pressure,'k-.', ...
	'Oxygen (umol/kg)',[75 280 min_y max_y]);
%set(ax3,'ydir','reverse');
set(ax3,'ydir','reverse','ylim',[min_y max_y],'xlim',[75 280]);
set(hl3,'linewidth',2,'color',[0.4 0.4 0.4]);

[h14,ax4] = floatAxisX(cnv_cal(i).sigma0,cnv_cal(i).pressure,'k--', ...
	'Sigma-Theta (kg/m3)',[22 28 min_y max_y]);
%set(ax4,'ydir','reverse');
set(ax4,'ydir','reverse','ylim',[min_y max_y],'xlim',[22 28]);
set(h14,'linewidth',0.5);

tax=subplot('position',[.45 .22 .08 .01]);
tpx=[0:.01:1];
tpy=ones(size(tpx)).*.5;
ttp=plot(tpx,tpy,'k');
%set(ttp,'markersize',2);
set(ttp,'linewidth',2);
set(gca,'xtick',[],'xcolor','w');
set(gca,'ytick',[],'ycolor','w');
set(tax,'xcolor','w','box','off','visible','off');
set(tax,'ycolor','w','box','off');

sax=subplot('position',[.45 .17 .08 .01]);
tts=plot([0 1],[.5 .5],'k');
set(tts,'linewidth',0.5);
set(gca,'xtick',[],'xcolor','w');
set(gca,'ytick',[],'ycolor','w');
set(sax,'xcolor','w');
set(sax,'ycolor','w','box','off','visible','off');

oax=subplot('position',[.45 .12 .08 .01]);
tto=plot([0 1],[.5 .5],'k-.');
%set(tto,'markersize',2);
set(tto,'linewidth',2,'color',[0.4 0.4 0.4]);
set(gca,'xtick',[],'xcolor','w');
set(gca,'ytick',[],'ycolor','w');
set(oax,'xcolor','w');
set(oax,'ycolor','w','box','off','visible','off');

sgax=subplot('position',[.45 .07 .08 .01]);
plot([0 1],[.5 .5],'k--');
set(gca,'xtick',[],'xcolor','w');
set(gca,'ytick',[],'ycolor','w');
set(sgax,'xcolor','w','box','off');
set(sgax,'ycolor','w','visible','off');

ts=subplot('position',[.67 .70 .22 .22]);
plot(cnv_cal(i).salt,cnv_cal(i).pottemp,'k');
xlabel('Salinity (PSS-78)');ylabel('Potential Temperature (deg C)');
grid on
hold on
plot(cond_match.btlsal(blist),sw_ptmp(cond_match.btlsal(blist), ...
	cond_match.ctdtmp1(blist),cond_match.ctdprs(blist),0),'k.');
set(ts,'xlim',[33.7 37.3],'ylim',[0 30]);

to=subplot('position',[.67 .41 .22 .22]);
plot(cnv_cal(i).oxyumol,cnv_cal(i).pottemp,'k');
xlabel('Oxygen (umol/kg)');ylabel('Potential Temperature (deg C)');
grid on;
hold on;
oxy_bottle=ox_units(oxy_match.btloxy(olist),oxy_match.ctdsal1(olist), ...
	sw_ptmp(oxy_match.ctdsal1(olist),oxy_match.ctdtmp1(olist), ...
	oxy_match.ctdprs(olist),0),'mll2mmk');
plot(oxy_bottle,sw_ptmp(oxy_match.ctdsal1(olist),oxy_match.ctdtmp1(olist), ...
	oxy_match.ctdprs(olist),0),'k.');
set(to,'xlim',[75 280],'ylim',[0 30]);
so=subplot('position',[.67 .12 .22 .22]);
plot(cnv_cal(i).oxyumol,cnv_cal(i).salt,'k');
xlabel('Oxygen (umol/kg)');ylabel('Salinity (PSS-78)');
grid on
hold on
% converting the oxygen to micromol/kg
oxy_bottle_aux=ox_units(oxy_match.btloxy(olist),oxy_match.ctdsal1(olist), ...
	sw_ptmp(oxy_match.ctdsal1(olist),oxy_match.ctdtmp1(olist), ...
	oxy_match.ctdprs(olist),0),'mll2mmk');
%
for t=1:length(blist),
  aux_samples=find(oxy_match.btlnbr(olist)==cond_match.btlnbr(blist(t)));
  if isempty(aux_samples)==1,
    aux_sample(t)=NaN;   
  else
    aux_sample(t)=aux_samples(1);
  end;
end;
if isempty(blist)~=1
  aux_plot=find(isnan(aux_sample)==0);
  plot(oxy_bottle_aux(aux_sample(aux_plot)),  ...
	cond_match.btlsal(blist(aux_plot)),'k.');
end
set(so,'xlim',[75 280],'ylim',[33.7 37.3]);
orient tall

%%%%%%%%%%%%%%% OUTPUT TABLE %%%%%%%%%%%%%%%%%
%creating table for specific pressures
ctda=['Latitude',latstr0, 'N'];
ctdb=[sprintf('%s','CTD Station ',int2str(sta)),' (' , sname, ')'];
ctdc=['Longitude',lonstr0, 'W'];
ctdd=sprintf('%s',dstr0,'Z');

p=[sprintf('%s\t','Pressure','Temp90','PoTemp90', ...
	'Salinity','Oxygen','DynHt','SigT')];
pp=[sprintf('%s\t','dbar','Deg C','Deg C', ...
	'PSS-78','umol/kg','m3/kg-1','kg/m3')];

% table depths
table=[1 10:10:30 50 75 100 125 150 200 250 300:100:1500 1750 2000:500:6000];

% print a data table to a file
fid=fopen(['FS_',sprintf('%03d',sta),'.tab'],'w');
fprintf(fid,'Florida Straits R/V FG Walton Smith');
fprintf(fid,'%s',' ',ctdb,' ',ctda,' ',ctdc,' ',ctdd);
fprintf(fid,'\n');
fprintf(fid,p);
fprintf(fid,'\n');
fprintf(fid,pp);
fprintf(fid,'\n');

for j=1:length(table),
   for k=1:length(cnv_cal(i).pressure),
      if(table(j)==cnv_cal(i).pressure(k)),
         fprintf(fid,'%5.0f\t%8.3f\t%8.3f\t%8.3f\t%6.1f\t%8.3f\t%8.3f\n', ...
		cnv_cal(i).pressure(k),cnv_cal(i).temp(k), ...
		cnv_cal(i).pottemp(k),cnv_cal(i).salt(k), ...
		cnv_cal(i).oxyumol(k),cnv_cal(i).dynheight(k), ...
		cnv_cal(i).sigma0(k));
      end; % if(table
   end; % for k=
end; % for j=
fprintf(fid,'\n');

% saving in the table
for t=1:length(blist),
  aux_samples=find(oxy_match.btlnbr(olist)==cond_match.btlnbr(blist(t)));
  if isempty(aux_samples)==1,
    oxy_save(t)=NaN;
  else
    oxy_save(t)=oxy_bottle(aux_samples(1));
  end;
end;

if ~isempty(blist),
  dd=[cond_match.ctdprs(blist),cond_match.ctdprs(blist), ...
	cond_match.ctdtmp1(blist),sw_ptmp(cond_match.btlsal(blist), ...
	cond_match.ctdtmp1(blist),cond_match.ctdprs(blist),0),...
        cond_match.btlsal(blist),oxy_save'];
  bp=[sprintf('%s\t','Pressure','Niskin','Temp90','PoTemp90', ...
	'Salinity','Oxygen')];
  bpp=[sprintf('%s\t','dbar','  ','Deg C','Deg C','PSS-78','umol/kg')];
  fprintf(fid,bp);
  fprintf(fid,'\n');
  fprintf(fid,bpp);
  fprintf(fid,'\n');
  fprintf(fid,'%5.0f\t%5.0f\t%8.3f\t%8.3f\t%8.3f\t%8.1f\n',dd');
end;
fclose(fid);

% print to postscript file cal_ctd.ps
orient tall
if pscount==0,
    print -dps cal_ctd.ps;
 else
    print -dps -append cal_ctd.ps;
 end;
% close all
%
%%%%%%%%% CMDR
disp(['The figures have been printed to cal_ctd.ps']);

clear aux_sample
clear oxy_save
end
% Save the calibrated data structure.
save(db_file,'cnv_cal','-append');

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

return;

