function [data2woce]=make_bottle_file(cruiseid,offset_fit,slope_fit,prcor,oxy_coeff)
% MAKE_BOTTLE_FILE - create WOCE format file
%
% CTD Calibration toolbox.
%
% USAGE:
%	[data2aoml]=make_bottle_file(cruiseid, ...
% 		offset_fit,slope_fit,prcor,oxy_coeff);
%
% INPUT: cruiseid: Cruise identification name.
% 
% OUTPUT: .... 
%          
% DESCRIPTION: Apply oxygen and conductivity calibration to the
%	cond_match and oxy_match files and save the calibrated data in WOCE
%	format.

% AUTHORS:
%			Carlos Fonseca 
%         UM/CIMAS
%         Derrick Snowden
%         NOAA/AOML/PhOD
%         Tue May 11 11:23:37 EDT 2004
%
% 
% VERSION: 
%	$Revision: 1.8 $
%	$Date: 2008/02/19 01:19:14 $
%	$Id: make_bottle_file.m,v 1.8 2008/02/19 01:19:14 duncombe Exp duncombe $
%
% CHANGELOG: 
%   07-Oct-2004, Version 1.0
%		* Initial version. 
%  2007/12/17 - CMDR
%	* read cruise id from the file in the current directory
%	* use a function for oxygen saturation calculation
% 	* make input lines easier to read (aesthetic adjustment!)
%  2008/01/11 CMDR
%	* use the oxygen saturation function from the seawater toolbox
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%% CMDR read cruiseid if we can
if nargin==0, cruiseid=getcruiseid; end;
if isempty(cruiseid), cruiseid=getcruiseid; 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 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('btl');

if isempty(n)==1
	error('btl not found.');
	return;
end
disp('**************************************************************************************')
disp('This is the program that applies the calibration coefficients to the btl files.')
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)
	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
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)
	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
disp('***************************************************************************')
staa=input('Input first station: ');
stab=input('Input last station: ');
%%%%%%%%%%%%%%%%%%%%
%Initial header info for the file
%
fid1=fopen('abaco2001_btl.csv','w');
fprintf(fid1,'BOTTLE,%4i%02i%02iPHODAOMLCAF \r',btl(1).gtime(1),btl(1).gtime(2),btl(1).gtime(3));
fprintf(fid1,'#code: make_woce_bottle_file.m \r');
fprintf(fid1,'#original CTD file: cond_match and oxy_match in ab01_db.mat - created 10/29/06  \r');
fprintf(fid1,'#depth estimated from CTD depth + 20 meters \r');
fprintf(fid1,'EXPOCODE,SECT_ID,STNNBR,CASTNO,SAMPNO,BTLNBR,BTLNBR_FLAG_W,DATE,TIME,LATITUDE,LONGITUDE,DEPTH,CTDPRS,CTDTMP,CTDSAL,CTDSAL_FLAG_W,SALNTY,SALNTY_FLAG_W,CTDOXY,CTDOXY_FLAG_W,OXYGEN,OXYGEN_FLAG_W \r');
fprintf(fid1,',,,,,,,,,,,,DBARs,ITS-90,PSS-78,,PSS-78,,UMOL/KG,,UMOL/KG,, \r');

for i=staa:1:stab;
    sta=i;
    blist=find(cond_match.stnnbr==sta);
    olist=find(oxy_match.stnnbr==sta);
    disp(['Applying the calibrations to the station ',num2str(sta)]) 
    press_aux=cond_match.ctdprs(blist);
    if pri_sec_c==0
     cond_aux=cond_match.ctdcon1(blist);
     temp_aux=cond_match.ctdtmp1(blist);
   else
     cond_aux=cond_match.ctdcon2(blist);;
     temp_aux=cond_match.ctdtmp2(blist);
   end
   % Aplying the correction for the conductivity
   %value for the offset
  if length(offset_fit)==1;
  offset_cor=offset_fit;
  elseif length(offset_fit)==2;
  offset_cor=polyval(offset_fit,sta);    
  elseif length(offset_fit)==3;    
  offset_cor=polyval(offset_fit,sta); 
  elseif length(offset_fit)==4;    
  offset_cor=polyval(offset_fit,sta);   
  end
  %value for the slope
  if length(slope_fit)==1;
  slope_cor=slope_fit;    
  elseif length(slope_fit)==2
  slope_cor=polyval(slope_fit,sta);    
  elseif length(slope_fit)==3    
  slope_cor=polyval(slope_fit,sta);
  elseif length(slope_fit)==4    
  slope_cor=polyval(slope_fit,sta);   
  end
  %value for pcor
  if length(prcor)==1;
  prcor=prcor;    
  elseif length(prcor)==2
  prcor=polyval(prcor,sta);  
  end
  % offset correction
  condc=cond_aux+offset_cor;
  % slope_correction
  condc=condc+(slope_cor*(condc));
  % pressure correction
  condc=condc+(prcor*(press_aux));     
  sal_aux=sw_salt(condc/sw_c3515,temp_aux,press_aux); 
  
  % Now the oxygen samples:
  if isempty(olist)==0
  press_aux_o2=oxy_match.ctdprs(olist);
  if pri_sec_o==0
         temp_aux_o2=oxy_match.ctdtmp1(olist);
          cond_aux_o2=oxy_match.ctdcon1(olist);
         oxycurr_aux=oxy_match.ctdoxc1(olist);
         oxycurrt_aux=oxy_match.ctdoxct1(olist);
         docdt_aux=oxy_match.ctddocdt1(olist);
  else  
          temp_aux_o2=oxy_match.ctdtmp2(olist);
         cond_aux_o2=oxy_match.ctdcon2(olist);
         oxycurr_aux=oxy_match.ctdoxc2(olist);
         oxycurrt_aux=oxy_match.ctdoxct2(olist);
         docdt_aux=oxy_match.ctddocdt2(olist);
  end
  
   sal_oxy=sw_salt(cond_aux_o2/sw_c3515,temp_aux_o2,press_aux_o2);  
  
   % correcting the oxygen 
   % calculating oxygen saturation
%%%%%%%%%%% CMDR use seawater O2 saturation function
	oxsat=sw_satO2(temp_aux_o2,sal_oxy);
%%%%%%%%%%%
   % 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);
  new_oxy=((Soc.*(oxycurr_aux+(tau.*docdt_aux)))+Boc+(p1.*stn+p2.*stn.^2)+(gama.*press_aux_o2)).*exp(tcor.*(temp_aux_o2+(wt*(oxycurrt_aux-temp_aux_o2)))).*oxsat.*exp(pcor.*press_aux_o2);
  oxy_ctd=ox_units(new_oxy,sal_oxy,sw_ptmp(sal_oxy,temp_aux_o2,press_aux_o2,0),'mll2mmk');
  %%%%%
  oxy_bottle_aux=ox_units(oxy_match.btloxy(olist),oxy_match.ctdsal2(olist),sw_ptmp(oxy_match.ctdsal2(olist),oxy_match.ctdtmp2(olist),oxy_match.ctdprs(olist),0),'mll2mmk');
  %matching salinity samples and oxygen samples
  end 
  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)=-999.0;   
   oxy_save_btl(t)=-999.0;
   quality_oxy_ctd(t)=9;
   quality_oxy_btl(t)=9;
   else
   oxy_save(t)=oxy_ctd(aux_samples(1)); 
   oxy_save_btl(t)=oxy_bottle_aux(aux_samples(1));
   quality_oxy_ctd(t)=2;
   if oxy_match.quality1(aux_samples(1))==1;
   quality_oxy_btl(t)=2;
   else
   quality_oxy_btl(t)=3;
   end
   end
   end 
  %%%%%%%% 
  % saving the data
  expocode='31WBTSOCEANUS';
  sect_id='AB01';
  cast=1;
  for k=1:1:length(blist)
   for j=1:1:length(btl)
      if cond_match.stnnbr(blist(k))==btl(j).station %& cond_cal.castnbr(i)==bl(j).cast      
	  sta_idx=j;
      end   
   end
   for j=1:1:length(cnv_cal)
      if cond_match.stnnbr(blist(k))==cnv_cal(j).station %& cond_cal.castnbr(i)==bl(j).cast      
	  sta_idx_d=j;
      end   
   end
  latitude=btl(sta_idx).lat;
  longitude=btl(sta_idx).lon;
  GMT=btl(sta_idx).gtime(4)*100+btl(sta_idx).gtime(5);
  date=btl(sta_idx).gtime(1)*10000+btl(sta_idx).gtime(2)*100+btl(sta_idx).gtime(3);
  depth=round(max(cnv_cal(sta_idx_d).depth+20)); 
  quality_btl=2; 
  quality_sal_ctd=2;
  if cond_match.quality1(blist(k))==1
  quality_sal_btl=2;
  else
  quality_sal_btl=3;
  end
 fprintf(fid1,'%16s,%6s,%6s,%3i,%7s,%7s,%1i,%8i,%4i,%8.4f,%9.4f,%5i,%9.1f,%9.4f,%9.4f,%1i,%9.4f,%1i,%9.1f,%1i,%9.1f,%1i \r',...
  expocode,sect_id,num2str(sta),cast,num2str(cond_match.fireorder(blist(k))),num2str(cond_match.niskinbtlpos(blist(k))),...
  quality_btl,date,GMT,latitude,longitude,depth,cond_match.ctdprs(blist(k)),cond_match.ctdtmp1(blist(k)),sal_aux(k),...
  quality_sal_ctd,cond_match.btlsal(blist(k)),quality_sal_btl,oxy_save(k),quality_oxy_ctd(k),oxy_save_btl(k),quality_oxy_btl(k));
 end
end
fprintf(fid1,'END_DATA \r');
fclose(fid1)

