function varargout  = load_oxy(cruiseid)
% LOAD_OXY - load *.oxy files from the AOML Winkler titration system
%
% CTD Calibration toolbox.
%
% USAGE: 
% 	load_oxy(cruiseid) 
%       Read the *.oxy files and save the results in the cruise database file. 
%                     
% 	oxy=load_oxy(cruiseid)  
%  	Return the data from the *.oxy files as a structure to the workspace
%
% INPUT: 
%	cruiseid	cruise identification name. 
%
% OUTPUT:
%   	oxy		winkler titration data and sample numbers
%	
%  The oxy structure has the fields:
%     date: time and date of titration (usually wrong on AOML computer)
%     station: string indicating station/cast
%     depth: depth field in the titration computer, frequently
%		Niskin bottle Rosette position
%     sample_bottle: label of the sample bottle in which the titration
%		was done.
%     thio_vol: solume of Thiosulphate in the titration.
%     oxygen: oxygen in units of micromoles per liter.  See ox_units for
%		conversion to other more standard units for analysis. 
%     units: 'mmmperl'
%

% AUTHORS:Carlos Fonseca 
%         UM/CIMAS
%         Derrick Snowden
%         NOAA/AOML/PhOD
%         Tue May 11 11:23:37 EDT 2004
%
% 
% VERSION: 
%	$Revision: 1.11 $
%	$Date: 2008/04/29 23:42:13 $
%	$Id: load_oxy.m,v 1.11 2008/04/29 23:42:13 duncombe Exp duncombe $
%
% CHANGELOG: 
%   23-Jul-2004, Version 1.0
%		* Initial version.
%
%   01-Oct-2004  Derrick Snowden 
%	* load_oxy (load_oxy): Removed dependence on directory
%	structure in favor of register_cruise
% 2007/11/29 CMDR
%	* read cruise id from the file in the current directory
%  2008/02/18 CMDR
%	* comments and style
%  2008/03/14 CMDR 
% 	* add cruiseid fieldname to the oxy structure
%  2008/04/29 CMDR
%	* edit out message boxes
%

% Check for correct number of inputs.
%%%%%%%%%%%%%%%%% CMDR
% error(nargchk(1,1,nargin))
if nargin==0, cruiseid=getcruiseid; end;

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

% oxy_dir is the calibration data directory 
if ispref(group,'cal_oxy_dir'),
	oxy_dir=getpref(group,'cal_oxy_dir');
else
%    errordlg(['The cal_oxy_dir preference was not set for cruise: ' ...
% 	 cruiseid '.  Run register_cruise.m']);
	error(['The cal_oxy_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
disp('********************************************************************')
disp('If no draw temps were taken, must convert from mm/l->mm/kg(ox_units)')
disp('********************************************************************')
% msgbox('Loading the oxygen samples','Loading Data')
% Check that the oxy files are in the given directory.
% TODO: Make use of the upper case/lower case preference.
ld_oxy = dir(fullfile(oxy_dir,'*.txt_ABR')); 

if size(ld_oxy)==size(ld_oxy)
    oxy_names = ld_oxy;
else
    if ~isempty(ld_oxy)
		error(['The *.oxy files in ', oxy_dir,  ...
		' are named in both upper and lower case.  Pick one ', ...
		'and rename before running ',mfilename]);
    elseif ~isempty(ld_oxy)
		oxy_names = ld_oxy;
    else
		error(['No *.oxy files were found in ', oxy_dir]);
    end
end

% The files are there, retrieve the data.
for i=1:length(oxy_names)
	oxy(i)=read_oxy_txt(fullfile(oxy_dir,oxy_names(i).name));
	oxy(i).cruiseid=cruiseid;
    
end
    
    quality = [];
    cast = [];
    quality = [quality; 2 * ones(length(vertcat(oxy.oxygen)),1)];
    cast = [cast; ones(length(vertcat(oxy.oxygen)),1)];
    output=[vertcat(oxy.station), vertcat(oxy.niskin), ...
        vertcat(oxy.sample_bottle),vertcat(oxy.draw_T), vertcat(oxy.thio_vol), ...
        vertcat(oxy.oxy_mml),vertcat(oxy.oxygen), quality, cast];

    % finally resort station numbers in order 0 to XXX.
    % Sorts by station number
    %
    [stt,ind] = sort(output(:,1),1);
    stt=output(ind,:);
    output = stt;
    

%output is in a matrix format of A(:,7)
% STT/ Niskin #/ trash/ standard/ salt/ flag?/ cast?
[output, duplicate_O] = average_and_remove_duplicates_oxy (output, fullfile('oxygen_as_loaded.txt'));

%Now make sure the salts information is in the structure that the
%           CTDtoolbox is expecting
%
            the_returned_oxygen.cruiseid = oxy(1).cruiseid;
            the_returned_oxygen.station = output(:,1);
            the_returned_oxygen.niskin = output(:,2);
            the_returned_oxygen.sample_bottle = output(:,3);            
            the_returned_oxygen.draw_T=output(:,4);
            the_returned_oxygen.thio_vol = output(:,5);
            the_returned_oxygen.oxy_mml = output(:,6);
            the_returned_oxygen.oxygen = output(:,7);
            the_returned_oxygen.quality = output(:,8);
            the_returned_oxygen.cast = output(:,9);
            the_returned_oxygen.units=oxy(1).units;

            oxy = the_returned_oxygen;
% Open the output file
db_file = fullfile(cruise_dir,[cruiseid '_db.mat']);
if exist(db_file)==2
	save(db_file,'oxy','-append');
else
	save(db_file,'oxy');
end;
station_list=unique(vertcat(oxy.station));
% msgbox(['Loaded oxygen samples from station ',num2str(min(station_list)), ...
% 	' to ',num2str(max(station_list))],'Loaded!','warn')
disp(['Loaded oxygen samples from station ',num2str(min(station_list)), ...
	' to ',num2str(max(station_list))]);
if nargout==0
	assignin('caller','ans',oxy);
else
	varargout{1}=oxy;
end;

return;

