function varargout  = load_bl(cruiseid)
% LOAD_BL - read and save the SeaBird ASCII .BL file format
%
% CTD Calibration toolbox.
%
% INPUT
%	cruiseid	Cruise identification name. 
%
% OUTPUT
%	bl		bottle trigger data from SBE .BL file
% 
% USAGE: 
% load_bl(cruiseid): read the SeaBird ASCII .BL files and save in
%                     the database file of the cruise.This file will
%                     be named "cruiseid"_db.mat 
%                     
% bl=load_bl(cruiseid) : Additionally, it will save the  .BL files 
%                          in the workspace

% AUTHORS:Carlos Fonseca 
%         UM/CIMAS
%         Derrick Snowden
%         NOAA/AOML/PhOD
%         Tue May 11 11:23:37 EDT 2004
%
% 
% VERSION: 
%	$Revision: 1.9 $
%	$Date: 2008/03/23 23:59:10 $
%	$Id: load_bl.m,v 1.9 2008/03/23 23:59:10 duncombe Exp duncombe $
%
% CHANGELOG: 
% 23-Jul-2004, Version 1.0
%	* Initial version.
% 01-Oct-2004  Derrick Snowden 
%	* load_bl (load_bl): Removed dependence on directory 
% 	structure in favor of register_cruise
%	* load_bl (load_bl): Fixed some logic errors that missed
%	empty directories. e.g. size(dir()) doesn't work.
% 2007/11/27 CMDR
% 	* There is a whole directory structure set up for a cruise,
% 	and the calibration process starts with cd'ing to that 
%	directory structure. Therefore it seems counter productive 
%	to have to essentially enter the cruiseid by hand each time.
%	Create a cruise_id file, which has the cruise id in it, and 
%	use that. Create a function getcruiseid which searches for
%	this file, reads it if it exists and otherwise proceeds as
%	previously done, ie to fail with error.  I attempted to do 
%	this by having the cruise id be determined by group_name
%	function but that requires too many other changes have to be 
%	made. 
%  2008/02/17 CMDR
%	* comments and consistency
%  2008/03/14 CMDR
%	* add cruiseid to the bl structure
%

% % Check for correct number of inputs.
% % error(nargchk(1,1,nargin))
% if nargin==0, 
% 	if exist('cruise_id','file'), 
% 		fid=fopen('cruise_id','r');
% 		cruiseid=fscanf(fid,'%s',inf);
% 		fclose(fid);
% 		disp(['Working with ' cruiseid ]);
% 	else
% 		error(nargchk(1,1,nargin))
% 	end;
% end;

%%%%%%%%%%% CMDR read cruiseid if we can
if nargin==0, cruiseid=getcruiseid; end;
if isempty(cruiseid), cruiseid=getcruiseid; end;
%%%%%%%%%%%

% Retrieve the necessary preferences for this cruise
group = group_name(cruiseid);

% bl_dir is the calibration data directory 
if ispref(group,'cal_bl_dir')
	bl_dir=getpref(group,'cal_bl_dir');
else
    errordlg(['The cal_bl_dir preference was not set for cruise: ' ...
		cruiseid '.  Run register_cruise.m']);
    error(['The cal_bl_dir preference was not set for cruise: ' ...
		cruiseid '.  Run register_cruise.m']);
end

% cruise_dir is the calibration data directory 
if ispref(group,'cal_data_dir')
	cruise_dir=getpref(group,'cal_data_dir');
else
    errordlg(['The cal_data_dir preference was not set for cruise: ' ...
		cruiseid '.  Run register_cruise.m']);
	error(['The cal_data_dir preference was not set for cruise: ' ...
		cruiseid '.  Run register_cruise.m']);
end
% Check that the bl files are in the given directory.
% TODO: Make use of the upper case/lower case preference.
lc_bl = dir(fullfile(bl_dir,'*.bl')); 
uc_bl = dir(fullfile(bl_dir,'*.BL'));

if isempty(lc_bl) & isempty(uc_bl)
    errordlg(['No *.bl or *.BL files were found in ', bl_dir]);
	error(['No *.bl or *.BL files were found in ', bl_dir]);
end
if isequal(lc_bl,uc_bl)
    bl_names = lc_bl;
else
    if ~isempty(lc_bl) & ~isempty(uc_bl)
        	errordlg(['The *.bl files in ', bl_dir...
		,' are named in both upper and lower case. ' ...
		' Pick one and rename before running ',mfilename]);
		error(['The *.bl files in ', bl_dir...
		,' are named in both upper and lower case. ' ...
		' Pick one and rename before running ',mfilename]);
    elseif isempty(lc_bl) & ~isempty(uc_bl)
		bl_names = uc_bl;
    elseif ~isempty(lc_bl) & isempty(uc_bl)
		bl_names = lc_bl;
    else
        errordlg(['No *.bl or *.BL files were found in ', bl_dir]);
		error(['No *.bl or *.BL files were found in ', bl_dir]);
    end;
end;

fprintf(1,['Loading the .BL files \n']);
% The files are there, retrieve the data.
for i=1:length(bl_names),
	tmp = read_sbebl(fullfile(bl_dir,bl_names(i).name));
	if ~isempty(tmp),
		bl(i)=tmp;
	else
		%bl(i)=
	end;
end;
for i=1:length(bl),
	bl(i).cruiseid=cruiseid;
end;

% Should never get here but make sure.
if ~exist('bl','var') | isempty(bl)
	error('The bl output structure does not exist or is empty.')
end

% Open the output file
db_file = fullfile(cruise_dir,[cruiseid '_db.mat']);
if exist(db_file)==2
	save(db_file,'bl','-append');
else
	save(db_file,'bl');
end;

station_list=unique(vertcat(bl.station));

fprintf(1,['Loaded .BL files from station ' num2str(min(station_list)) ...
	' to ' num2str(max(station_list)) '\n'])

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

return;

