function [bl_struct]=read_sbebl(bl_file);
% READ_SBEBL - read SeaBird ASCII .BL files
%
%  Usage:   [bl_struct]=read_sbebl(bl_file);
%
%     Input:  bl_file = name of .BL file  (e.g. 'cast002.bl')
%
%     Output:bl_struct with fields:
%         station = station number
%    niskinnumber = niskin bottle number      
%       fireorder = fire order
%
%  CALLER: user
%
%  DEPENDENCIES:
%

%  AUTHOR: 18 Aug 2004 Carlos Fonseca (Carlos.Fonseca@noaa.gov)
%    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.7 $
%	$Date: 2008/03/14 17:22:08 $
%	$Id: read_sbebl.m,v 1.7 2008/03/14 17:22:08 duncombe Exp duncombe $
%
% CHANGELOG:
%  2008/03/14 CMDR
%	* add cruiseid fieldname to the bl structure
%

% TODO: Add calling syntax for no input args to return complete
%		struct w/ nan fields.
% TODO: How to handle the not-quite-empty bl files generated when
%		no bottles were tripped?

% Open the .bl file as read-only text
%
fid=fopen(bl_file,'rt');
if fid < 0 
    disp(['WARNING: read_sbebl could not open ',bl_file]);
    bl=[];
    return
end
count=1;
sta = [];
niskin = [];
fire = [];
while ~feof(fid)
     str=fgetl(fid);
	 % Check to see if this is a placeholder file with no contents.
	 if isjunk(str)
		bl_struct.station = NaN;
		bl_struct.niskinnumber = NaN;
		bl_struct.fireorder = NaN;	
		fclose(fid);
		return
	  end
   isf=findstr(str,'.BL');
   if isempty(isf)
      isf=findstr(str,'.bl');
   end
   if isempty(isf)==0 
       is=findstr(str,'.');
       isub=is-2:1:is-1;
       sta=sscanf(str(isub),'%d',3);
       isub2=is-1;
       cast=1;
   else
    if (strncmp(str,'RESET',5))
    else
       is=findstr(str,',');
       isub=1:is(1)-1;
       fire(count,1)=sscanf(str(isub),'%d',3);
       isub=is(1)+1:is(2)-1;
       niskin(count,1)=sscanf(str(isub),'%d',3);
       count=count+1;
    end
   end
end
if isempty(sta) | isempty(niskin) | isempty(fire) |isempty(cast)
	bl_struct.cruiseid = NaN;
	bl_struct.station = NaN;
        bl_struct.cast=NaN;
	bl_struct.niskinnumber = NaN;
	bl_struct.fireorder = NaN;
    disp([bl_file,' loaded'])
	
	return
else
	bl_struct.cruiseid = [];
	bl_struct.station = sta;
        bl_struct.cast=cast;
	bl_struct.niskinnumber = niskin;
	bl_struct.fireorder = fire;
    disp([bl_file,' loaded'])
end
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function junk  = isjunk(str)
% isjunk: test to see if the file contains only null characers.
%
% The sbe system seems to log a bl file even if no bottles were fired, if the 
% prelimnary steps include rossum or bottlesum.  This checks to see
% if the current file is garbage.
junk = false;
cmp = char(zeros(size(str))); % string of N null characters.
if strncmp(char(double(str)),cmp,length(cmp)),
	junk = true;
end;

return;

