function y = readoasis(Filename)
% READOASIS - Read files compiled using the java program CoallateOasisFiles
% 
% Use As: x = readoasis(Filename)
%      or x = readoasis
%
% Inputs: Filename = name of coallated data file
%
% Output: x        = matrix of data. The first column is the Day of the year, 
%							the last column is the year. Refer to the header in <Filename>
%                    for specifics on each column of data.

% Brian Schlining
% 22 Apr 1999

%===========
% Open File
%===========
if ~nargin
   [infile inpath] = uigetfile('*.*','Select Oasis data file',0,0);
   if infile == 0
      y = [];
      return                            % Return if CANCEL is selected
   end
   Filename = [inpath infile];
end

tic
fid  = fopen(Filename,'rt');
if fid < 0
   error(['Unable to open file ' Filename])
end

trashheader(fid);                       % Get rid of the Header (i.e. lines that start with '#')

fprintf(1, 'Reading %s.', Filename);

p    = ftell(fid);                     % Get the position of the first data point

c    = ones(60000,1)*NaN;              % Initialize memory to speed things up, we're quessing file size here

%========================================================
% 1st pass is to check the number of inputs on each line
%========================================================
n    = 0;
while ~feof(fid)
   s = fgetl(fid);
   v = sscanf(s,'%f');
   n = n + 1;
   c(n,1) = length(v);
end
fprintf(1, '.');

c    = nanmax(c);                      % Find the longest line. This is assumed to be the number of
                                       % points all the lines shoudl have.
fseek(fid,p,'bof');                    % Rewind to the start of the data

%=======================================
% 2nd pass reads the data into a matrix
%=======================================
t    = ones(n,1)*NaN;
y    = ones(n,c)*NaN;
l    = n;
n    = 0;
while ~feof(fid)
   s = fgetl(fid);
   v = sscanf(s,'%f')';
   n = n + 1;
   if n > 60000
      if length(v) < c
         v(length(v+1):c) = NaN;
      end
   end
   if ~rem(n,1000);tt = toc; disp([num2str(tt) ': Read line ' num2str(n) ' of ' num2str(l)]);end
   y(n,1:length(v)) = v;
end
fprintf(1, '.');

bad = find(y == -999);
y(bad) = NaN;

y = snip(y);


fclose(fid);
fprintf(1, '\n');

%=================================
% function SNIP
% Remove rows that start with NaN
%=================================
function x = snip(x)

i = find(~isnan(x(:,1)));
x = x(i,:);

%====================================================
% function TRASHHEADER
% Remove the first block of lines beginning with '#'
%====================================================
function p = trashheader(fid)

OK = 1;
n = 0;
while OK
   p = ftell(fid);
   s = fgetl(fid);

   if strmatch('#',s)
      OK = 1;
      n = n + 1;
   else
      OK = 0;
   end
   
end
fseek(fid,p - n,'bof');
