function Var=mudread(fid,RowCol,norec)
% function Var=mudread(fid,NRow,Ncol [,norec]) --- read in a 1D or 2D MODFLOW or MT3D matrix
% general function to read in nD matries. See UD2REL in Modflow manual
% TO 070703 081228 090713


% Copyright 2009 Theo Olsthoorn, TU-Delft and Waternet, without any warranty
% under free software foundation GNU license version 3 or later

NRow=RowCol(1); if length(RowCol)>1, NCol=RowCol(2); else NCol=1; end

%% Read without control record
if exist('norec','var') && ~isempty(norec)
        Var=fscanf(fid,'%f',[NRow,NCol]);
        fprintf(fgets(fid));
        return;
end

%% control record
s=fgets(fid); fprintf(s);
%wrd=textscan(s,'%d %d %d %s'); wrd=wrd{1}; % peel cell

%% read with control record

%% CONSTANT
C=textscan(s,'%s %f %s %d',1);
if strcmp(upper(C{1}{1}),'CONSTANT')
    Var=ones(NRow,NCol)*C{2};
    return;
end

%% INTERNAL
if strcmp(upper(C{1}{1}),'INTERNAL')
    Var=fscanf(fid,'%f',[NCol,NRow])*C{2};
    Var=Var';
    fprintf(fgets(fid));
    return;
end
    
%% EXTERNAL
C=textscan(s,'%s %d %f %s %d',1);
if strcmp(upper(C{1}{1}),'EXTERNAL')
    error('Can''t yet read files externally');
end

%% OPEN CLOSE
C=textscan(s,'%s %s %f %s %d',1);
if strcmp(upper(C{1}(1)),'OPEN/CLOSE')
    fid=fopen(C{2}{1},'r');
    cnst=C{3};
    if cnst<=0, cnst=1; end
    Var=fscanf(fid,'%f',[NCol,NRow]);
    Var=Var'*cnst;
    fprintf(fgets(fid));
    return;
end

%% FIXED FORMAT
C=textscan(s,'%d %f %s %d',1);
LOCAT  =C{1};
CNSTNT =C{2};
%FMTIN  =C{3}{1};
%IPRN   =C{4};

if LOCAT==0,
    Var=ones(NRow,NCol)*CNSTNT;
    return;
end
if LOCAT> 0,
    Var=fscanf(fid,'%f',[NCol,NRow]); % USE current file for reading the data
    Var=Var';
    fprintf(fgets(fid));
    return;
end
if LOCAT< 0,  % Binary
    error('Can''t read from binary file, used locat>0');
end
