function [cnv_struct]=read_sbecnv(cnv_file,varargin);
% READ_SBECNV - read SeaBird BINARY or ASCII *.cnv files
%
%  Usage:   [cnv_struct]=read_sbecnv(cnv_file);
%           [cnv_struct]=read_sbecnv(cnv_file,fileType);
%
%     Input:  CNV_file = name of .CNV file  (e.g. 'STC1002.CNV')
%             fileType = ['B'] | 'A' for binary or ascii.
%
%     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.
%

%
%  HISTORY: 
%  29 Nov 2002: Now reads both binary and ascii on Linux using 
%           command line inputs (no guis).  Returns correct orientation.
%  29 Nov 2001 Sonia Cavalcante (Sonia.Cavalcante@noaa.gov)
%          based on read_sbebtl by Derrick Snowden (Derrick.Snowden@noaa.gov)
%          (which was based on cnv2mat by Rich Signell).  
%  4-8-98  Rich Signell (rsignell@usgs.gov)  
%     incorporates ideas from code by Derek Fong & Peter Brickley
% 
% VERSION: 
%	$Revision: 1.10 $
%	$Date: 2008/04/10 19:29:57 $
%	$Id: read_sbecnv.m,v 1.10 2008/04/10 19:29:57 duncombe Exp duncombe $
%
% CHANGELOG:
%  2008/02/15 CMDR
%	* some formatting and tidying up
%  2008/03/14 CMDR
%	* add fieldname cruiseid to the cnv structure
%  2008/03/24 CMDR
%	* test for broken NMEA time string
%  2008/04/10 CMDR
% 	* there are cases where the full string with the variable name would
%	be useful. Store this in fullnames and add it to the cnv structure.
%

% By default assume the cnv file is written in ascii.  If binary reading
% doesn't work on your computer, rewrite the cnv files in ascii since that
% works everywhere and send me the bug information.

isbinary = false;
time_offset = 0;
error(nargchk(1,3,nargin));
if nargin == 2
    type = varargin{1};
    if type== 1 | strcmp(upper(type(1)),'B')
        isbinary = true;
    elseif type== 0 | strcmp(upper(type(1)),'A')
        isbinary = false;
    else
        error(['read_sbecnv error: Unrecognized input file type. ', ...
		' {[B (binary)] or A (ascii)[default]}'] );
    end
elseif nargin ==3
	time_offset = varargin{2};
    error('read_sbecnv error: Too many input variables.');
end

if nargin == 2
	time_offset = varargin{1};
else
	time_offset = 0;
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 denotes the end of the header but not the line containing
% the names of the columns.

choose_nmea = 0;
while (~strncmp(str,'*END*',5));
    str=fgetl(fid);
   % 
   %A16S
   %Reading Station number and cast number
   % ----------------------------------------------------
   %  if (strncmp(str,'* FileName',10))
   %    is=findstr(str,'.');
   %    isub=is-4:1:is-2;
   %    sta=sscanf(str(isub),'%d',3);
   %    isub2=is-1;
   %    cast=sscanf(str(isub2),'%d',1);  
   % ----------------------------------------------------
   %AB0505
   %Reading Station number and cast number
   % ----------------------------------------------------
   %   if (strncmp(str,'* FileName',10))
   %  is=findstr(str,'.');
   %   isub=is-3:1:is-1;
   %   sta=sscanf(str(isub),'%d',3);
   %   cast=1;  
   % ----------------------------------------------------
   %AB0206
   %Reading Station number and cast number
   % ----------------------------------------------------
      if (strncmp(str,'* FileName',10))
     is=findstr(str,'.');
      isub=is-2:1:is-1;
      sta=sscanf(str(isub),'%d',2);
      cast=1;  
   % ----------------------------------------------------
   % -----------------------------------
   % 
   %     Read the NMEA latitude string.  This may vary with CTD setup.
   % 
   % if (strncmp(str,'* NMEA Lat',10))
   elseif (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),'S'));
            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),'S'));
                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) + time_offset/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,':');
	if ~isempty(is),
        	isub=is(1)-2:length(str);
        	gtime([4:6])=sscanf(str(isub),'%2d:%2d:%2d');
	end;
        %------------------------------
        %
        %    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);
%%%%%%%% CMDR
	fullnames{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!
%  It can be read as binary into matrix data
%==============================================
if isbinary,
    data=fread(fid,[length(names) Inf],'float');
else
    data=fscanf(fid,'%f',[length(names) Inf]); 
end;
    
data=data';
% Begin to assemble the output matrix/structure.
cnv_struct.cruiseid = [];
cnv_struct.station = sta;
cnv_struct.cast = cast;
cnv_struct.lat = lat;
cnv_struct.lon = lon;
cnv_struct.gtime = gtime;
%cnv_struct.sensors = char(sensors');%removed for New SBEpocessing header
%2/28/2012
cnv_struct.tcor=0; % flag indicates if correction appld for temp. sensors 
cnv_struct.pcor=0; % flag indicates if correction appld for press. sensor
% 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.fullnames = fullnames;
cnv_struct.data = data;

fclose(fid);
return;

