function [bottle_struct] = master_bottle_file(varargin)
% MASTER_BOTTLE_FILE -  Create a master bottle file from the .bot files in a given directory.
%
% USAGE:
%  [bottle_struct] = master_bottle_file(prefix);
%  [bottle_struct] = master_bottle_file(prefix,inputDirectory);
%  [bottle_struct] = master_bottle_file(prefix,inputDirectory,excludeStations);
%  [bottle_struct] = master_bottle_file(prefix,inputDirectory,excludeStations,outDir);
%
% INPUT:
%   in_vars: 
%            prefix = is a string representing the file naming convention.  
%                       It is assumed that all files to be processed are 
%                       similarly named according to the convention,
%                       prefix####.btl or .BTL.  There can be any number of #s representing the station number.
%            inputDir = string containing the path to the directory in which the .btl and .bot files reside.
%            excludeStations = vector contining the station numbers to exclude
%            outputDir = string containing the path to the directory in which the output file will be written.
%
% OUTPUT:
%   out_vars: bottle_struct = Structure containing all the bottle information in the .btl and 
%                   .bot files in the input directory.  Fieldnames will correspond to the 
%                    sensor types written on the first noncomment line in the .btl files.
%
%   
%
% BUGS:
%     1.  The prefix is case sensitive but the suffix (.btl or .BTL) is not.
% NOTE:
%
% TO BE DONE:
%   
%
% VERSION:  0.1
%
% AUTHOR: Derrick Snowden 
%         Derrick.Snowden@noaa.gov
%         NOAA/AOML/PhOD
%           Based on the program read_sbecnv.m from the 
%      	    www.mathtools.net Geographics and Oceanographics page.
%           which was written by Rich Signell. rsignell@usgs.gov
%  CALLER: User
%
%  DEPENDENCIES: 



% Check the input arguments
if (nargin == 0)
    print_error('Must include a prefix for the input btl file naming convention');
   
elseif (nargin == 1)
    if (ischar(varargin{1}))
        prefix = varargin{1};
        inputDir = './';
        excludeStations = [];
        outputDir = inputDir;
    else
        print_error('Input prefix not a character variable');
    end   
elseif (nargin == 2)
    if (ischar(varargin{1})) & (ischar(varargin{2}))
        prefix = varargin{1};
        inputDir = varargin{2};
        excludeStations = [];
        outputDir = inputDir;
    else
        print_error('Input prefix or directory is not a character variable.');
    end
elseif (nargin == 3)
    if (ischar(varargin{1})) & (ischar(varargin{2})) & (isnumeric(varargin{3}))
        prefix = varargin{1};
        inputDir = varargin{2};
        excludeStations = varargin{3};
        outputDir = inputDir;
    else
        print_error('Input prefix or directory is not a character variable or excludeStations not a numeric vector');
    end
elseif (nargin == 4)
     if (ischar(varargin{1})) & (ischar(varargin{2})) & (isnumeric(varargin{3})) & (ischar(varargin{4}))
        prefix = varargin{1};
        inputDir = varargin{2};
        excludeStations = varargin{3};
        outputDir = varargin{4};
    else
        print_error('Input prefix or i/o directorys are not character variables or excludeStations not a numeric vector');
    end
else  
    disp([mfilename,' error: Incorrect number of inputs.']);
    help master_bottle_file
    return
end



% See how many .btl files are in the given directory.
% Try to assemble a list of unique filenames regardless of case (btl or BTL)
if (inputDir(end) ~= '/' | inputDir(end) ~= '\' | prefix(1) ~= '/' | prefix(1) ~= '\')
    inputDir
    lowercase = dir([inputDir,'/',prefix,'*.btl']);
    uppercase = dir([inputDir,'/',prefix,'*.BTL']);
else 
    lowercase = dir([inputDir,prefix,'*.btl']);
    uppercase = dir([inputDir,prefix,'*.BTL']);
end
identical = [];
btlFileNames = {};
% Make sure the capitalized suffixes actually represent different files
if length(lowercase) == 0 & length(uppercase) == 0
    print_error([' No .btl or .BTL files found in ',inputDir]);
end
if length(lowercase) == 0 & length(uppercase) ~= 0
    btlFileNames = cellstr(strcat(inputDir,strvcat(uppercase.name)));
elseif length(lowercase) ~= 0 & length(uppercase) == 0
    btlFileNames = cellstr(strcat(inputDir,strvcat(lowercase.name)));
else % don't make any assumptions.  Check every name for duplicates
    % A duplicate name will be any name that is identical except for case.
    % If there is even one character different between two similar names then 
    % the names will be considered distinct.
    for i = 1:length(lowercase)
        for j = 1: length(uppercase)
            rootIndex = findstr(lowercase(i).name,'.');
            rootLC = lowercase(i).name(1:rootIndex-1);
            rootIndex = findstr(uppercase(i).name,'.');
            rootUC = uppercase(j).name(1:rootIndex-1);
            if strcmpi(rootLC,rootUC) %1 => identical except for case
                if (lowercase(i).size == uppercase(j).size)
                    % Names are identical except for case and sizes are identical 
                    % so they are the same file.  Ignore one of them
                    identical = [identical ; j];
                end
            end
        end
    end
    if (length(identical) ~= length(uppercase)) 
        if (length(identical) ~= 0)
            % Those files in uppercse not flagged as identical
            uniqueIndex = setdiff([1:length(uppercase)],identical);  
        else 
            uniqueIndex = [1:length(uppercase)];
        end       
        btlFileNames = cellstr(strvcat(strcat(inputDir,strvcat(lowercase.name)),...
            strcat(inputDir,strvcat(uppercase(uniqueIndex).name))));
    else
        btlFileNames = cellstr(strcat(inputDir,strvcat(lowercase.name)));
    end
    btlFileNames = {inputDir,btlFileNames};
end

% Step through the input files and open them in turn.
btlFileNames = sort(btlFileNames); %Hopefully this sorts by station number if 
% everything else works correctly.
for i = 1:length(btlFileNames)
        
    % Open the .btl files as read-only text
    %
    fid=fopen(btlFileNames{i},'rt');
    if fid == -1
        print_error(['Error opening ',btlFileNames{i}]);
    end
    % 
    % Read the header.
    % Start reading header lines of .CNV file,
    % Stop at line that starts with '*END*'
    %
    % Pull out NMEA lat & lon along the way and look
    % at the '# name' fields to see how many variables we have.
    %
    str='*START*';
    while (~strncmp(str,'   Bottle',10));
        str=fgetl(fid);
        %-----------------------------------
        %
        %    Read latitude string.  This may vary with CTD setup.
        %
        if (strncmp(str,'** Latitude',11))
            is=findstr(str,':');
            isub=is+1:length(str);  %Index of susbstring
            dm=sscanf(str(isub),'%f',2);
            if(findstr(str(isub),'N'));
                lat=dm(1)+dm(2)/60;
            else  
                lat=-(dm(1)+dm(2)/60); 
            end

        %-------------------------------
        %
        %    Read the longitude string.  This may vary with CTD setup.
        %
        elseif (strncmp(str,'** Longitude',12))
            is=findstr(str,':');
            isub=is+1:length(str);
            dm=sscanf(str(isub),'%f',2);
            if(findstr(str(isub),'E'));
                lon=dm(1)+dm(2)/60;
            else  
                lon=-(dm(1)+dm(2)/60); 
            end
                        
            
        %------------------------
        %
        %    Read the 'System upload time' to get the date.
        %           This may vary with CTD setup.
        %
        %    I'm reading this in to get the date, since the NMEA time string
        %    does not contain date.  Unfortunately, the system upload time is
        %    in local time (here, EST), so I need to convert to UTC by adding
        %    5 hours (5/24 days).
        %
        elseif (strncmp(str,'* System UpLoad',15))
            is=findstr(str,'=');
            %    pick apart date string and reassemble in DATEFORM type 0 form
            datstr=[str(is+6:is+7) '-' str(is+2:is+4) '-' str(is+9:is+12)];
            datstr=[datstr ' ' str(is+14:is+21)];
            %    convert datstr to Julian time, add 5 hours to convert from EST to GMT
            n=datenum(datstr)+5/24;
            gtime=datevec(n);
%             %----------------------------
%             %
%             %    Read the NMEA TIME string.  This may vary with CTD setup.
%             %
%             %      replace the System upload time with the NMEA time
%         elseif (strncmp(str,'* NMEA UTC',10))
%             is=findstr(str,':');
%             isub=is(1)-2:length(str);
%             gtime([4:6])=sscanf(str(isub),'%2d:%2d:%2d');
            %------------------------------
            %
            %    Read the variable names & units into a cell array
            %
%         elseif (strncmp(str,'# name',6))  
%             var=sscanf(str(7:10),'%d',1);
%             var=var+1;  % .CNV file counts from 0, Matlab counts from 1
%             %      stuff variable names into cell array
%             names{var}=str;
            %------------------------------
            %
            %    Read the sensor names into a cell array
            %
        elseif (strncmp(str,'# sensor',8))  
            sens=sscanf(str(10:11),'%d',1);
            sens=sens+1;  % .CNV file counts from 0, Matlab counts from 1
            %      stuff sensor names into cell array
            sensors{sens}=str;
            %
            %  pick up bad flag value
%         elseif (strncmp(str,'# bad_flag',10))  
%             isub=13:length(str);
%             bad_flag=sscanf(str(isub),'%g',1);
        end
    end
    %==============================================
    %
    %  Done reading header.  Now read the data!
    %
    nvars=var;  %number of variables
    
    % Read the data into one big matrix
    %
    data=fscanf(fid,'%f',[nvars inf]);
    
    fclose(fid);
    
    %
    % Flag bad values with nan
    %
    ind=find(data==bad_flag);
    data(ind)=data(ind)*nan;
    
    %
    % Flip data around so that each variable is a column
    data=data.';
    
    % Convert cell arrays of names to character matrices
    names=char(names);
    sensors=char(sensors);
    
end %End looping through the input files btlFileNames
return

    
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Subfunctions
function [] = print_error(error_message);
disp('master_bottle_file error error:')
error(error_message);
return


