function [S,l] = ReadSpectrum(filename, format) 

% [Spec, lambda] = ReadSpectrum(filename)
% Spec = ReadSpectrum(filename)
%
% Reads a spectrum with given filename.
% format = 'asdi', ASDI Fieldspec format, as converted with portspec - NOT IMPLEMENTED
% format = 'ooi', Ocean Optics exported spectrum format					- NOT IMPLEMENTED
% format = 'txt', plain text file, no header, no wavelength file.
% format = 'mat', matlab .mat file, with spectrum in 'spectrum'.
% format = 'dat', John Bates software format, for saving ocean optics format.
% format = 'ast', Aster spectral library text file format.
%
% returns S = -1 if failure

% Liam Pedersen, August 1998, NASA A.R.C.
% version 1.0

% Liam Pedersen, September 1998, CMU
% version 2.0 - accepts .dat spectra files
  
% Liam Pedersen, September 1999, CMU
% version 2.1 - LINUX port (filenames use '/', not '\'.

Err = 0;

% get path
i = find(filename == '/');
if (isempty(i))
   i = 0;
   spath = './';			% default case
else
   i = max(i);
   spath = filename(1:i);
end

% get extension
j = find(filename == '.');
if (isempty(j))
   ext = 'mat';			% default case
   j = length(filename)+1;
else
   ext = filename(j+1:length(filename));
end

% get root file name
fn = filename(i+1:j-1);

% check input arguments
if (nargin == 1)
   format = ext;
end

% case 'DAT'
if (strcmp(format,'dat') | strcmp(format,'DAT'))
   ld = ['load ' filename '; Spec = ' fn '; S = Spec(:,2); l = Spec(:,1);'];  
   fail = 'Err = 1;';
   eval(ld,fail);
end
      

% case 'MAT'
if (strcmp(format,'mat') | strcmp(format,'MAT'))
   ld = ['load ' filename '; S = spectrum;'];
   fail = 'Err = 1;';
   eval(ld,fail);
   if (nargout == 2)
      ld = ['load ' spath 'lambda.mat; l = lambda;'];
      eval(ld, fail);
   end
end

% case 'TXT'
if (strcmp(format,'txt') | strcmp(format,'TXT'))
   ld = ['load ' filename '; S = ' fn ';'];  
   fail = 'Err = 1;';
   eval(ld,fail);
      
   if (nargout == 2)
      ld = ['load ' spath 'lambda.txt; l = lambda;'];
      eval(ld, fail);
    end
end

% case 'AST'
if (strcmp(format,'ast') | strcmp(format,'AST'))
   ld = '[S,l,Name,Type,Class,Subclass] = ReadAsterSpectra(filename);';
   fail = 'Err = 1';
   eval(ld, fail);
end

if (Err)
  S = -1;
end


