function cnv_cal=apply_calibration(cruiseid,cond_coeff,oxy_coeff)
% APPLY_CALIBRATION - Apply oxygen and conductivity calibration .
%
% CTD Calibration toolbox.
%
% USAGE:
% cond_match=apply_calibration(cruiseid,coeff);
%
% INPUT: cruiseid: Cruise identification name.
%        coeff: matrix with coefficients from conductivity calibration
%   
% OUTPUT: .... 
%          
% DESCRIPTION: ...  
% 
% AUTHORS:
%			Carlos Fonseca 
%         UM/CIMAS
%         Derrick Snowden
%         NOAA/AOML/PhOD
%         Tue May 11 11:23:37 EDT 2004
%
% CHANGELOG: 
%   07-Oct-2004, Version 1.0
%		* Initial version. 
%
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
flag_message1=0;
flag_message2=0;
flag_conv1=0;
flag_conv2=0;
%
% 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('cnv_dlp');

if isempty(n)==1
	error(['cnv_dlp not found. Run deloop.m ']);
	return;
end
disp('**************************************************************************************')
disp('This is the program that applies the calibration coefficients to the .cnv delooped data.')
disp('**************************************************************************************')

disp('**************************************************************************************')
disp(' 1 = use the primary sensor (DEFAULT)' )
disp(' 2 = 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>2)
	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>2)
	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: ');
%%%%%%%%%%%%%%%%%%%%
%max_cnv=max(size(cnv));
%for i=1:max_cnv;
pscount=-1; 
for j=1:1:length(cnv_dlp)
       if staa==cnv_dlp(j).station
       sta_min_idx=j;
       end
       if stab==cnv_dlp(j).station
       sta_max_idx=j;
       end
end
for i=sta_min_idx:1: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==1
        %%%%%% Need Check here%%%%%%%%%%%%%%%%%% 
     cond_aux=cnv_dlp(i).condpri*10;     
     aux_dcdp=gradient(cond_aux);
     temp_aux=cnv_dlp(i).temppri;
     qual_aux=cnv_dlp(i).quality;
     %oxy_sal=cnv_dlp(i).salpri;
     %oxyvolt_aux=cnv_dlp(i).oxvpri;
     %oxyvolt_aux=smooth(press_aux,oxyvolt_aux, 0.02,'loess');
    else
        %%%%%% Need Check here%%%%%%%%%%%%%%%%%% 
     cond_aux=cnv_dlp(i).condsec*10;     
     aux_dcdp=gradient(cond_aux);
     temp_aux=cnv_dlp(i).tempsec;
     qual_aux=cnv_dlp(i).quality;
     %oxy_sal=cnv_dlp(i).salsec;
     %oxyvolt_aux=cnv_dlp(i).oxvsec;
     %oxyvolt_aux=smooth(press_aux,oxyvolt_aux, 0.02,'loess');
    end
      if pri_sec_o==1
         oxyvolt_aux=cnv_dlp(i).oxvpri;
% mb        if i==1
% mb        oxyvolt_aux=weim(21,'rect',oxyvolt_aux)';
% mb        end
     else
         oxyvolt_aux=cnv_dlp(i).oxvsec;
      end
        %%%%%% Need Check here%%%%%%%%%%%%%%%%%%%%%%%%   
  sal_oxy=sw_salt(cond_aux/sw_c3515,temp_aux,press_aux);
  %sal_oxy=sw_salt(oxy_sal,temp_aux,press_aux);
  %sal_oxy=sw_salt(cond_aux/(sw_c3515/10),temp_aux,press_aux);
   % correcting the conductivity
  condc=(cond_coeff(1)*cond_aux)+(cond_coeff(2).*sta)+cond_coeff(3)+cond_coeff(4)*press_aux;
   %
    %%%%%% Need Check here%%%%%%%%%%%%%%%%%%%%%%%% 
  sal_aux=sw_salt(condc   /sw_c3515,temp_aux,press_aux);
  
   % correcting the oxygen (oxy fit 3.01 std dev)
    % correcting the oxygen (oxy fit 3.01 std dev)
   % calculating oxygen saturation
%%%%%%%%%%% CMDR use seawater O2 saturation function
% mb	oxsat=sw_satO2(temp_aux,sal_oxy);
	oxsat=sw_satO2(temp_aux,sal_oxy);
   % calibration coefficients for the oxygen
  Soc=oxy_coeff(1);
  Voffset=oxy_coeff(2);
  A=oxy_coeff(3);
  B=oxy_coeff(4);
  C=oxy_coeff(5);
  E=oxy_coeff(6);
  p1=oxy_coeff(7);
  stn=repmat(sta,length(oxyvolt_aux),1);
% new_oxy is in ml/l
  new_oxy=((Soc.*(oxyvolt_aux+Voffset))+(p1.*stn)).*...
	(1.0+(A.*temp_aux)+(B.*temp_aux.^2)+(C.*temp_aux.^3)).*oxsat.*exp((E.*press_aux)./(temp_aux+273.15));

%  new_oxy=(Soc.*(volt       +Voffset))           .*...
%	(1.0+(A.*temp    )+(B.*temp    .^2)+(C.*temp    .^3)).*OXSAT.*exp((E.*press    )./(temp    +273.15)); 

  %new_oxymmk=ox_units(new_oxy, sal_aux,sw_ptmp(sal_oxy,temp_aux,press_aux,0),'mll2mmk');
  
% saving the variables
  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).quality=qual_aux;
  if isfield(cnv,'lat'),
  cnv_cal(i).depth(:,1)=sw_dpth(press_aux,cnv(i).lat);
  else,
  cnv_cal(i).depth(:,1)=sw_dpth(press_aux,cnv(i).latitude);
  end;
  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

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

  %ploting 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','Abaco February - March 2012 R/V Brown');
  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');


    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);
        bhan(oo)=text(30.1,cond_match.ctdprs(blist(oo)),botstr(oo,:),'FontSize',6); %bottle pressures
    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
    if pri_sec_c==1
        good_idx=(find(cond_match.quality1(blist)==2 & cond_match.quality2(blist)==2));
        bad_idx=(find(cond_match.quality1(blist)>2 & cond_match.quality2(blist)>2));
    else
        good_idx=(find(cond_match.quality1(blist)==2 & cond_match.quality2(blist)==2));
        bad_idx=(find(cond_match.quality1(blist)>2 & cond_match.quality2(blist)>2));    
    end
    plot(cond_match.btlsal(blist(good_idx)),sw_ptmp(cond_match.btlsal(blist(good_idx)),cond_match.ctdtmp1(blist(good_idx)),cond_match.ctdprs(blist(good_idx)),0),'k.');
    plot(cond_match.btlsal(blist(bad_idx)),sw_ptmp(cond_match.btlsal(blist(bad_idx)),cond_match.ctdtmp1(blist(bad_idx)),cond_match.ctdprs(blist(bad_idx)),0),'ko','MarkerSize',3);
    set(ts,'xlim',[33.7 37.3],'ylim',[0 30]);

%i=10
%pri_sec_o=2
%sta=9
%blist=find(cond_match.stnnbr==sta);
% olist=find(oxy_match.stnnbr==sta);
 
    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
    if pri_sec_o==1
        good_idx=(find(oxy_match.quality1(olist)==2 & oxy_match.quality2(olist)==2));
        bad_idx=(find(oxy_match.quality1(olist)>2 & oxy_match.quality2(olist)>2));
    else
        good_idx=(find(oxy_match.quality1(olist)==2 & oxy_match.quality2(olist)==2));
        bad_idx=(find(oxy_match.quality1(olist)>2 & oxy_match.quality2(olist)>2));    
    end
    %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');
    oxy_bottle=oxy_match.btloxy(olist);%,oxy_match.ctdsal1(olist),sw_ptmp(oxy_match.ctdsal1(olist),oxy_match.ctdtmp1(olist),oxy_match.ctdprs(olist),0),'mll2mmk');
    if pri_sec_o==1
        plot(oxy_bottle(good_idx),sw_ptmp(oxy_match.ctdsal1(olist(good_idx)),oxy_match.ctdtmp1(olist(good_idx)),oxy_match.ctdprs(olist(good_idx)),0),'k.');
        plot(oxy_bottle(bad_idx),sw_ptmp(oxy_match.ctdsal1(olist(bad_idx)),oxy_match.ctdtmp1(olist(bad_idx)),oxy_match.ctdprs(olist(bad_idx)),0),'ko','MarkerSize',3);
        set(to,'xlim',[75 280],'ylim',[0 30]);
    else
        plot(oxy_bottle(good_idx),sw_ptmp(oxy_match.ctdsal2(olist(good_idx)),oxy_match.ctdtmp2(olist(good_idx)),oxy_match.ctdprs(olist(good_idx)),0),'k.');
        plot(oxy_bottle(bad_idx),sw_ptmp(oxy_match.ctdsal2(olist(bad_idx)),oxy_match.ctdtmp2(olist(bad_idx)),oxy_match.ctdprs(olist(bad_idx)),0),'ko','MarkerSize',3);
        set(to,'xlim',[75 280],'ylim',[0 30]);    
    end;


    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');
    oxy_bottle_aux=oxy_match.btloxy(olist);
    %
    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);
        if pri_sec_c==1
            good_idx=(find(cond_match.quality1(blist(aux_plot))==2 & cond_match.quality2(blist(aux_plot))==2));
            bad_idx=(find(cond_match.quality1(blist(aux_plot))>2 & cond_match.quality2(blist(aux_plot))>2));
        else
            good_idx=(find(cond_match.quality1(blist(aux_plot))==2 & cond_match.quality2(blist(aux_plot))==2));
            bad_idx=(find(cond_match.quality1(blist(aux_plot))>2 & cond_match.quality2(blist(aux_plot))>2));    
        end
        plot(oxy_bottle_aux(aux_sample(aux_plot(good_idx))),cond_match.btlsal(blist(aux_plot(good_idx))),'k.');
        plot(oxy_bottle_aux(aux_sample(aux_plot(bad_idx))),cond_match.btlsal(blist(aux_plot(bad_idx))),'ko','MarkerSize',3);
    end
    set(so,'xlim',[75 280],'ylim',[33.7 37.3]);
    orient tall

    %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=[1 10:10:30 50 75 100 125 150 200 250 300:100:1500 1750 2000:500:6000];

    fid=fopen(['abaco1202_',sprintf('%03d',sta),'.tab'],'w');
    fprintf(fid,'Abaco February_March 2012 R/V Brown');
    fprintf(fid,'\n');
    fprintf(fid,'%s',ctdb);
    fprintf(fid,'\n');
    fprintf(fid,'%s',ctda,' ',ctdc);
    fprintf(fid,'\n');
    fprintf(fid,'%s',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
        end
    end
    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)~=1
        dd=[cond_match.ctdprs(blist),cond_match.niskinbtlpos(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);
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %                 Make Latex 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 &','$^\circ$C &','$^\circ$C &','PSS-78 &',...
        '$\mu\mathrm{mol}\!\cdot\!\mathrm{kg}^{-1}$ &',...
        '$\mathrm{m}^2\!\cdot\!\mathrm{s}^{-2}$ &','$\mathrm{kg}\!\cdot\!\mathrm{m}^{-3}$\\')];


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

    fid=fopen(['abaco1202_',sprintf('%03d',sta),'.txt'],'w');
    fprintf(fid,'%s','\begin{tabular}{*{7}{c}}');
    fprintf(fid,'\n');    
    fprintf(fid,'%s','\multicolumn{7}{c}{Abaco February--March 2012 R/V Brown}\\');
    fprintf(fid,'\n');
    fprintf(fid,'%s',['\multicolumn{7}{c}{',ctdb,'}\\']);
    fprintf(fid,'\n');
    fprintf(fid,'%s',['\multicolumn{7}{c}{',ctda,' ',ctdc,'}\\']);
    fprintf(fid,'\n');
    fprintf(fid,'%s',['\multicolumn{7}{c}{',ctdd,'}\\']);
    fprintf(fid,'\n');
    fprintf(fid,'%s','\\');
    fprintf(fid,'\n');
    fprintf(fid,p);
    fprintf(fid,'\n');
    fprintf(fid,'%s',pp);
    fprintf(fid,'\n');
    
    %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));
    for j=1:length(table);
        for k=1:length(cnv_cal(i).pressure);
            if(table(j)==cnv_cal(i).pressure(k));
                fprintf(fid,'%s%5.0f\t%s%8.3f\t%s%8.3f\t%s%8.3f\t%s%6.1f\t%s%8.3f\t%s%8.3f%s\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
        end
    end
    fprintf(fid,'%s','\end{tabular}');
    fprintf(fid,'\n');
    fprintf(fid,'\n');
    fprintf(fid,'%s','\begin{tabular}{*{6}{c}}');
    fprintf(fid,'\n');
    fprintf(fid,'%s','\\');
    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)~=1
        %dd=[cond_match.ctdprs(blist),'&',cond_match.niskinbtlpos(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 &','   &','$^\circ$C &','$^\circ$C &','PSS-78 &','$\mu\mathrm{mol}\!\cdot\!\mathrm{kg}^{-1}$\\')];
        fprintf(fid,'%s',bp);
        fprintf(fid,'\n');
        fprintf(fid,'%s',bpp);
        fprintf(fid,'\n');
        %blst=find(cond_match.stnnbr==sta);
           for bb=1:length(blist)
        fprintf(fid,'%s%5.0f\t%s%5.0f\t%s%8.3f\t%s%8.3f\t%s%8.3f\t%s%8.1f%s\n',...
            '$',cond_match.ctdprs(blist(bb)),'$ & $',cond_match.niskinbtlpos(blist(bb)),...
            '$ & $',cond_match.ctdtmp1(blist(bb)),'$ & $',sw_ptmp(cond_match.btlsal(blist(bb)),...
            cond_match.ctdtmp1(blist(bb)),cond_match.ctdprs(blist(bb)),0),'$ & $',...
            cond_match.btlsal(blist(bb)),'$ & $',oxy_save(bb),'$\\');
           end;
        
    end
    fprintf(fid,'%s','\end{tabular}');
    fclose(fid);    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %              end Latex Format                                       %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    
    orient tall
    jpeg=['print -deps cal_ctd',sprintf('%03d',sta),'.eps'];
    eval(jpeg)
    if pscount==0
        print -dps cal_ctd.ps
    else
        print -dps -append cal_ctd.ps
    end
    close all
    %
    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);
    return
else
    varargout{1}=cnv_cal;
    return
end
return