function cond_match = make_cond_sumfile(cruiseid)
% make_cond_sumfile -  Makes conductivity bottle/ctd comparison summary file.
%
% CTD Calibration toolbox.
%
% USAGE:
%  [cond_struct] = make_cond_sumfile(cruiseid);
%
% INPUT: cruiseid: Cruise identification name. 
%   
% OUTPUT:  Automatically writes the summary file in the cruise database file.  
%          cond_match: contains a structure with the same information
%               contained in the *.mat file
%
% DESCRIPTION:  This function tries to merge the *.btl files from the Seabird 
%  and the conductivity files from the  salinity samples
%  and create a summary file containing coincident measurements from both
%  systems.  The data for a whole cruise is processed at once so if you want
%  less data you'll have to subset afterwards.
%
% AUTHORS:Carlos Fonseca 
%         UM/CIMAS
%         Derrick Snowden
%         NOAA/AOML/PhOD
%         Tue May 11 11:23:37 EDT 2004
%
% CHANGELOG: 
%   23-Jul-2004, Version 1.0
%		* Initial version.
%	27-Sep-2004  DPS 
%		*  (sample_struct): Merged the cond_struct and sample_struct functions into one.
%   Feb 2012 M.Baringer
%       * program is too dependent on variable names even though it tests
%       for them, trying to be more universal.  Does not work unless there
%       is a variable called "pressure".  Fixed this to search through all
%       names for likely matches.
%       * added a bunch of comments
%       * program is horrible.  Gutted it (only kept first 50 lines - should probably call it something new).
%         Should do the following as separate routines:  
%           1) merge bl and btl files
%           2) add salinity files to it
%           3) add oxygen files to it
%       Right now this routine just handles the salinity files.
%	
% DEPENDENCIES: SW package.
%               load_salts
%               load_btl
%               load_bl
%               deloop
%
% assumes bl is a structure from the CTD that has the form:
%    station
%    cast
%    niskinnumber
%    fireorder
% assumes salts is a structure from autosal files that looks like:
% salts
%    station
%    niskin_bottle
%    sample_bottle
%    cond_ratio_2
%    salinity
%
% assumes btl has the form of a structure that contains:
%   data
%   names
%
% write out a structure file that looks like this:
%   cond_match
%       cruiseid: 'Character array identifying cruise e.g. file naming etc.'
%          stnnbr: 'Station number'
%         castnbr: 'Cast number if there are multiple casts per station'
%         sampnbr: 'Cell array with the alphanumeric label on the sample bottle'
%          btlnbr: 'Permanent unique serial number on the sample bottle'
%    niskinbtlpos: 'The position of the Niskin bottle on the rosette.'
%       fireorder: 'The order in which the bottle was fired.'
%          btlsal: 'Bottle sample salinity PSS-78'
%         btlcon1: 'Bottle conductivity based on salinity/primary ctd temperature'
%         btlcon2: 'Bottle conductivity based on salinity/secondary ctd temperature'
%          ctdraw: 'Optional: nominal ctd pressure recorded at bottle closure. Uncalibrated pressure.'
%          ctdprs: 'Pressure '
%         ctdtmp1: 'Temperature in ITS-90 (Primary Sensor)'
%         ctdtmp2: 'Temperature in ITS-90 (Secondary Sensor)'
%         ctdsal1: 'Salinity PSS-78 (Primary Sensor)'
%         ctdsal2: 'Salinity PSS-78 (Secondary Sensor)'
%         ctdcon1: 'CTD Conductivity (Primary Sensor)'
%         ctdcon2: 'CTD Conductivity (Secondary Sensor)'
%           dcdp1: 'CTD Pressure rate of change in conductivity  (Primary Sensor)'
%           dcdp2: 'CTD Pressure rate of change in conductivity  (Secondary Sensor)'
%         quality:
%      niskinflag:
%
% WOCE/WHP bottle sample quality flags:
% The WHP bottle parameter data quality codes are:
% 1           	Sample for this measurement was drawn from water bottle but analysis not received. Note that if water is drawn for any measurement from a water bottle, the quality flag for that parameter must be set equal to 1 initially to ensure that all water samples are accounted for.
% 2 	Acceptable measurement.
% 3 	Questionable measurement.
% 4 	Bad measurement.
% 5 	Not reported.
% 6 	Mean of replicate measurements (Number of replicates should be specified in the -.DOC file and replicate data tabulated).
% 7 	Manual chromatographic peak measurement.
% 8 	Irregular digital chromatographic peak integration.
% 9 	Sample not drawn for this measurement from this bottle.
%
% The WHP quality codes for the water bottle itself are:
% 1           	Bottle information unavailable.
% 2 	No problems noted.
% 3 	Leaking.
% 4 	Did not trip correctly.
% 5 	Not reported.
% 6 	Significant discrepancy in measured values between Gerard and Niskin bottles.
% 7 	Unknown problem.
% 8 	Pair did not trip correctly. Note that the Niskin bottle can trip at an unplanned depth while the Gerard trips correctly and vice versa.
% 9 	Samples not drawn from this bottle.
%

% Flags for the temperature scale conversion (t90 to t68)
flag_conv1=0;
flag_conv2=0;
flag_message1=0;
flag_message2=0;
%
format long

common_start_up_tasks

% Check for the necessary variables in the cruise database.
n=who('btl');
if isempty(n)==1
	error(['btl variable not found in the cruise database. Run load_new_btl.m ']);
	return;
end
n=who('bl');
if isempty(n)==1
	error(['bl variable not found in the cruise database. Run load_bl_molly.m ']);
	return;
end
n=who('cnv_dlp');
if isempty(n)==1
	%error(['cnv_dlp variable not found in the cruise database. Run deloop_molly.m ']);
    n=who('cnv_fill');
	%return;
end
n=who('salts');
if isempty(n)==1
	error(['salts variable not found in the cruise database. Run load_salts_molly.m ']);
	return;
end

% Initialize an empty bottle sample data structure.
cond_match = sample_struct;
cond_match.cruiseid=cruiseid;

% We are trying to match the salinity bottle samples with the corresponding ctd 
% data.  Loop through the good samples and find the matching cnv/btl/bl data as 
% appropriate.

%
% For every recorded CTD bottle closure, we must gather all associated
% bottle data.
%
% First make one structure that contains all the bottle closure information
% Use ONLY btl and bl files created by the CTD
%
% Start with bl file as the most basic - created upon acquisition.
%
stations = [];
cast = [];
%for i = 1: length(bl)
ss=vertcat(bl.station);
stmx=find(ss==max(salts.station));
for i = 1:stmx
    stations = [stations; bl(i).station * ones(length(bl(i).niskinnumber),1)];
    cast     = [cast;     bl(i).cast    * ones(length(bl(i).niskinnumber),1)];    
end
cond_match.stnnbr  = stations;
cond_match.castnbr = cast;
% JH edit to take into account for whent he bottle station range isn't equal to
% the ctd station range
fire_aux=vertcat(bl.fireorder);
cond_match.fireorder = fire_aux(1:length(cond_match.stnnbr));
%cond_match.fireorder = vertcat(bl.fireorder);
nisk_aux=vertcat(bl.niskinnumber);
cond_match.niskinbtlpos = nisk_aux(1:length(cond_match.stnnbr));
%cond_match.niskinbtlpos = vertcat(bl.niskinnumber);

stations= unique(vertcat(salts.station));

%
% from the autosal files:
%
% loop through each salinity value and try to match to cond_match station
% number and niskin bottle number
%
% will set sampnbr, btlsal, 
% then will compute btlcon1, btlcon2
% So first set all the variables to have appropriate flag values
% and out of range values (e.g. set to -999)
%
cond_match.sampnbr = -999 * ones(size(cond_match.stnnbr,1), size(cond_match.stnnbr,2));
cond_match.btlsal  = -999 * ones(size(cond_match.stnnbr,1), size(cond_match.stnnbr,2));
cond_match.btlcon1 = -999 * ones(size(cond_match.stnnbr,1), size(cond_match.stnnbr,2));
cond_match.btlcon2 = -999 * ones(size(cond_match.stnnbr,1), size(cond_match.stnnbr,2));
cond_match.btlnbr  = -999 * ones(size(cond_match.stnnbr,1), size(cond_match.stnnbr,2));
cond_match.quality1  = 9 * ones(size(cond_match.stnnbr,1), size(cond_match.stnnbr,2));
cond_match.quality2  = 9 * ones(size(cond_match.stnnbr,1), size(cond_match.stnnbr,2));
cond_match.niskinflag  = 9 * ones(size(cond_match.stnnbr,1), size(cond_match.stnnbr,2));

for II = 1: length(salts.station)
    KK = find(cond_match.stnnbr == salts.station(II) & cond_match.niskinbtlpos == salts.niskin_bottle(II));
    cond_match.btlsal(KK) = salts.salinity(II);
    cond_match.sampnbr(KK) = salts.sample_bottle(II);
    cond_match.btlnbr(KK) = salts.niskin_bottle(II);
    cond_match.quality1(KK) = salts.quality(II);
    cond_match.quality2(KK) = 2;
    cond_match.niskinflag(KK) = 2;
end


%
% information from .btl files  
% disp('**************************************');
% disp('Extracting information from .btl files');
% disp('**************************************');  
% information from .btl files
% is stored in fireorder only.  There is no niskin bottle information.
%

%
% Assume that each btl file has the same btl.names stings
%
% determine which column of data is each variable
% by extracting the indexes for the .btl files usin ghte names field.
%
[ctd_pr_idx, ctd_con1_idx, ctd_con2_idx, ctd_temp1_idx, ctd_temp2_idx, ctd_oxy1_idx, ctd_oxy2_idx, ctd_oxv1_idx, ctd_oxv2_idx, flag_conv1, flag_message1, flag_cond_Sm_to_mScm] = ...
    determine_column_names_of_btl_file (btl);


for NumMatch = 1:length(cond_match.stnnbr)
    KK_station = find(vertcat(btl.station) == cond_match.stnnbr(NumMatch));
   
    if ~isempty(KK_station)
        JJ_bottle = find( btl(KK_station).Bottle == cond_match.fireorder(NumMatch));
        % have now found the station/bottle match-up
        %    cond_match(NumMatch) = btl(KK_station).XXXX(JJ_bottle)
 
        cond_match.latitude(NumMatch,1) = btl(KK_station).lat;
        cond_match.longitude(NumMatch,1)=btl(KK_station).lon;
    
        % this original routine was setting cond_match.ctdupprs,
        % cond_match.ctdupcon1, cond_match.ctdupcon2, cond_match.ctduptmp1,
        % cond_match.ctduptmp2
        % Looks like it wants mS/cm but read in S/m so it is multiplying
        % conductivity by 10.
        % Also looks like it was doing a downcast interpolation for the bottle
        % stops and computing gamma.  
        % That's fine to do - but most definitely *NOT* fine to do in this
        % routime.
        % This routine should simply match up the three files - period.
        % Better yet - it should be broken into three routines - one to match bl
        % and btl files, one to add salts to that, and a third to add oxygen 
 
        cond_match.ctdprs (NumMatch,1)=btl(KK_station).data(JJ_bottle,ctd_pr_idx);
        cond_match.ctdtmp1(NumMatch,1)=btl(KK_station).data(JJ_bottle,ctd_temp1_idx);
        cond_match.ctdtmp2(NumMatch,1)=btl(KK_station).data(JJ_bottle,ctd_temp2_idx);
        cond_match.ctdcon1(NumMatch,1)=btl(KK_station).data(JJ_bottle,ctd_con1_idx);
        cond_match.ctdcon2(NumMatch,1)=btl(KK_station).data(JJ_bottle,ctd_con2_idx);
        cond_match.time(NumMatch,1)   =btl(KK_station).time(JJ_bottle);
        if flag_conv1==1;
            cond_match.ctdtmp1(NumMatch,1)=t68tot90(cond_match.ctduptmp1(NumMatch,1));   
        end

        if flag_conv2==1;
            cond_match.ctdtmp2(NumMatch,1)=t68tot90(cond_match.ctdtmp2(NumMatch,1));   
        end 
        
        if flag_cond_Sm_to_mScm==1;
            cond_match.ctdcon1(NumMatch,1) = 10. * cond_match.ctdcon1(NumMatch,1);
            cond_match.ctdcon2(NumMatch,1) = 10. * cond_match.ctdcon2(NumMatch,1);
        end
    else
        fprintf(1,'WARNING: BTL files for station %3.0f have not been found.  Filling with -999.\n', ...
            cond_match.stnnbr(NumMatch));
        cond_match.latitude(NumMatch,1)  = -999;
        cond_match.longitude(NumMatch,1) = -999;
        cond_match.ctdprs (NumMatch,1)   = -999;
        cond_match.ctdtmp1(NumMatch,1)   = -999;
        cond_match.ctdtmp2(NumMatch,1)   = -999;
        cond_match.ctdcon1(NumMatch,1)   = -999;
        cond_match.ctdcon2(NumMatch,1)   = -999;
        cond_match.time(NumMatch,1)      = -999;
    end
end % i loop

%
% calculating the salinity
cond_match.ctdsal1 = sw_salt(cond_match.ctdcon1/sw_c3515, cond_match.ctdtmp1, cond_match.ctdprs);
cond_match.ctdsal2 = sw_salt(cond_match.ctdcon2/sw_c3515, cond_match.ctdtmp2, cond_match.ctdprs);
cond_match.ctdsal1(find(cond_match.ctdcon2(:,1)==-999),1) = -999.;
cond_match.ctdsal2(find(cond_match.ctdcon2(:,1)==-999),1) = -999.;

%
cond_match.btlcon1 = sw_c3515*sw_cndr(cond_match.btlsal,cond_match.ctdtmp1,cond_match.ctdprs);
cond_match.btlcon2 = sw_c3515*sw_cndr(cond_match.btlsal,cond_match.ctdtmp2,cond_match.ctdprs);
cond_match.btlcon1 (find(cond_match.btlsal(:,1)==-999),1) = -999.;
cond_match.btlcon2 (find(cond_match.btlsal(:,1)==-999),1) = -999.;


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

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