function [R, header] = read_prevah_result(file,nodata)
% PUPROSE: read result tabular data (txt) from PREVAH hydrological model
% -------------------------------------------------------------------
% USAGE: [R, header] = read_prevah_result(file,nodata)
% Input: file: filename and location
% nodata - nodata value (optional, if given value will be replaced
% with NaN)
% Output: R: x*n column, where n is the number of timesteps and x are
% the number of result columns, according to specification
% in the PREVAH manual, part III, p73)
% YYYY MM DD HH ... ... ...
%
% EXAMPLE: [R, header] = read_prevah_result(sample.q,9999);
%
% Note: at the moment, only *.q, *.mit, *.std and *pri files are explicitly
% supported (e.g. with header column information)
%
% See also: read_prevah_grid, write_prevah_grid, read_prevat_input
%
% Felix Hebeler, Geography Dept., University Zurich, Feb 2009
%open file
fid = fopen(file,'r');
[pathstr, name, ext] = fileparts(file);
% header for information only
h=0; % 0 header lines
switch ext
case '.q'
header={'YYYY','MM','DD','HH','RTOT','RTOT','R0','R1','R2','RG1','RG2','RG3'};
col=14;
case '.std'
header={'YYYY','MM','DD','HH','ZERO','P','ADJ-P','SWA','ETP','ETR','EI','EB','R0','R1','R2','RTOT','SSO','SI','SSM','SUZ','SLZ'};
col=21;
case '.mit'
header={'YYYY','MM','DD','P','ADJ-P','SWA','ETP','ETR','EI','EB','R0','R1','R2','RTOT','SSO','SI','SSM','SUZ','SLZ','BIL','ICEM','RG1','RG2','RG3','DIFGA'};
col=25;
h=27;
case '.pri'
header={'BASINID','YYYY','MM','BASINID','P','ADJ-P','SWA','ETP','ETR','EI','EB','R0','R1','R2','RTOT','SSO','SI','SSM','SUZ','SLZ','ICEM'};
col=21;
otherwise
header={'YYYY','MM','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA','NA'};
col=22;
end
if h>0;
header(col+1)=textscan(fid,'%q',h); % write whatever is read from the header line(s) to the header cell struct
end
% scan in text
format = '%d %d %d %d'; % first 4 columns are read in as integers
for c=5:col
format = [format,' %n']; % add a %n to read in double for each remaining column
end
data = textscan(fid,format);
%intialise result array
l=length(cell2mat(data(1,col))); % get length of last column, this is used because result files can contain gibberish from some point on,
% which will not be read, but the column length (no of timesteps) will not
% be correct anymore for the reformating
R=nan(l,col);
% reformat to column vector
for i= 1:col
R(:,i)=data{1,i}(1:l); % l (normally, l equals end)
end
clear data;
% check if nodata values should be replaced
if exist('nodata','var')
R(R==nodata)=NaN;
end
%close file
fclose(fid);