function [cnv_struct]=cnv2mat(cnv_file,varargin);
% CNV2MAT Reads the SeaBird BINARY or ASCII.CNV file format
%
%  Usage:   [cnv_struct]=cnv2mat(cnv_file);
%
%     Input:  CNV_file = name of .CNV file  (e.g. 'STC1002.CNV')
%
%     Output:cnv_struct with fields:
%             lon = longitude in decimal degrees, West negative
%             lat = latitude in decimal degrees, North positive
%             gtime = Gregorian time vector in UTC
%             sensors = string matrix containing the names of the sensors
%             names = cell of string matrix containing the names of the columns
%            data = matrix containing all the columns of data in the .CNV file
%
%  NOTE: The format of CNV header file must be:
%
%    * System UpLoad Time = Mar 21 2001 12:56:38
%    * NMEA Latitude = 06 19.96 N
%    * NMEA Longitude = 043 59.96 W
%    * NMEA UTC (Time) = 12:57:07
%    # name 0 = .....
%    # sensor 0 = .....
%    *end*
%
%
%  Modify the lat,lon and date string handling if your .CNV files are different.
%  Also, There are several possibilities for the way time is stored.  NMEA time 
%  has been used as time and it is in GMT.
%
%  
%  BUGS: 
%
%  CALLER: user
%
%  DEPENDENCIES:
%
%  AUTHOR: 29 Nov 2001 Sonia Cavalcante (Sonia.Cavalcante@noaa.gov)
%          based on btl2mat by Derrick Snowden (Derrick.Snowden@noaa.gov)
%          (wich was based on Rich Signell).  
%  4-8-98  Rich Signell (rsignell@usgs.gov)  
%     incorporates ideas from code by Derek Fong & Peter Brickley
%
if nargin > 1;
    type = varargin{1};
    if type== 1 | strcmp(upper(type(1)),'B')
        button = 'B';
    elseif type== 0 | strcmp(upper(type(1)),'A')
        button = 'A';
    else
        error('cnv2mat error: Unrecognized input file type.  {[B (binary) default] or A (ascii)}');
    end
elseif nargin > 2
    error('cnv2mat error: Too many input variables.');
else
    button = 'A';
end

% Open the .CNV file as read-only text
%
fid=fopen(cnv_file,'rt');
if fid == -1
    error(['Unable to open file: ',cnv_file]);
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*';

% This may change in different configurations.  I suppose it depends on your 
% shipboard processing scripts/procedures.  look through your files for 
%something that denots the end of the header but not the line containing the names ofthe columns.
%
choose_nmea = 0;
while (~strncmp(str,'*END*',5));
    str=fgetl(fid);
    %-----------------------------------
    %
    %    Read the NMEA latitude string.  This may vary with CTD setup.
    %
    if (strncmp(str,'* NMEA Lat',10))
        choose_nmea = 1;
        is=findstr(str,'=');
        isub=is+1:length(str);
        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 NMEA longitude string.  This may vary with CTD setup.
        %
    elseif (strncmp(str,'* NMEA Lon',10))
        choose_nmea = 1;
        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 NON NMEA latitude string.  This may vary with CTD setup.
        %
    elseif (strncmp(str,'** Lat',6))
        if choose_nmea == 0
            is=findstr(str,':');
            isub=is+1:length(str);
            dm=sscanf(str(isub),'%f',2);
            if(findstr(str(isub),'N'));
                if length(dm) == 2
                    lat=dm(1)+dm(2)/60;
                else
                    lat = dm(1); % assume they have used decimal degrees
                end
            else 
                if length(dm) == 2
                    lat=-(dm(1)+dm(2)/60);
                else
                    lat = -(dm(1)); % assume they have used decimal degrees
                end
                
            end
        end
        %-------------------------------
        %
        %    Read the NON NMEA longitude string.  This may vary with CTD setup.
        %
    elseif (strncmp(str,'** Lon',6))
        if choose_nmea == 0
            is=findstr(str,':');
            isub=is+1:length(str);
            dm=sscanf(str(isub),'%f',2);
            if(findstr(str(isub),'E'));
                 if length(dm) == 2
                    lon =dm(1)+dm(2)/60;
                else
                    lon = dm(1); % assume they have used decimal degrees
                end
            else 
                if length(dm) == 2
                    lon=-(dm(1)+dm(2)/60);
                else
                    lon = -(dm(1)); % assume they have used decimal degrees
                end
                
           end
        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;
        %CAF
        n=datenum(datstr);
        %CAF
        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
         isin=findstr(str,'=');
         is=findstr(str,':');
         names{var}=str(isin+1:is-1);
        %------------------------------
        %
        %    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!
%  It can be read as binary onto matrix data
%==============================================
%button=questdlg(' What is the data format? BINARY (B) or ASCII(A)?','B','A');
switch button
case 'B'
    data=fread(fid,[length(names) Inf],'float');
case 'A'
    data=fscanf(fid,'%f',[length(names) Inf]); 
end
    data=data';
% Begin to assemble the output matrix/structure.

cnv_struct.lat = lat;
cnv_struct.lon = lon;
cnv_struct.gtime = gtime;
cnv_struct.sensors = char(sensors');
% remove the spaces in the names cell
for i = 1:length(names)
    str = names{i};
    idxspc = isspace(str);
    str(idxspc) = [];
    names{i} = str;
end
cnv_struct.names = names;
cnv_struct.data = data;
disp([cnv_file,' loaded'])
fclose(fid)

