function dat2mat2d( filename )
% 将2维Fortran程序的结果dat文件，转换为matlab数据，并画图
% 
% Copyright Bao-Shan Wang, School of Mathematical Sciences, Ocean University of China
% Link : http://www.amsc-ouc.ac.cn/Research_skills.html
% $ MATLAB R2020b $ $ Date: 2020/10/26 11:01:55 $
%
% filename = 'DMR_2D_AWENO_CU_2050.dat';
fid = fopen( filename ); % 以只读模式打开混合格式文本文件

dt = textscan( fid, '%s', 'Delimiter', '\n' );

fclose( fid );
%% 变量个数 NV，变量名称 Variables
data = dt{1,1};
Var = char( data(2) );
NV = sum( Var == ',' ) + 1; % 变量个数

Variables = cell( NV, 1 );
id  = strfind( Var, '=' );
Var = Var(id + 1:end);
id2 = [strfind( Var, ',' ), length(Var) + 1];

i1 = 0;
for i = 1:NV
    i0 = i1 + 1;
    i1 = id2(i);
    Variables{i} = Var(i0:i1-1); % 变量名称
end

%% Nx Ny
strNx = char( data(3) );
Nx = str2num( strNx( isstrprop( strNx, 'digit' ) ) );
strNy = char( data(4) );
Ny = str2num( strNy( isstrprop( strNy, 'digit' ) ) );
%% 数值开始的位置 I0
n  = length( data );
I0 = 1;
for i_st = 1:n
    if ~isempty( str2num( char( data(i_st) ) ) )
        I0 = i_st;
        break
    end
end
%% 提取数据
Nd = floor( (n - I0 + 1) / NV );
i1 = I0 - 1;
for j = 1:NV
    i0 = i1      + 1;
    i1 = i0 + Nd - 1;
    
    dt  = str2num( char( data(i0:i1-1) ) )';
    dt2 = str2num( char( data(   i1  ) ) ) ;
    D = reshape( [dt(:); dt2(:)], Nx, Ny )';
    
    eval( [char( Variables(j) ), ' = D;'] )
end
%% 画图
Vx = 1;
Vy = 2;
Vr = 3;

str = ['mesh(', char( Variables(Vx) ), ', ', char( Variables(Vy) ), ', ', ...
                char( Variables(Vr) ), ')'];
eval(str)
%% 设置x，y轴范围
x0 = min( eval( [char(Variables(Vx)), '(:)'] ) );
x1 = max( eval( [char(Variables(Vx)), '(:)'] ) );
y0 = min( eval( [char(Variables(Vy)), '(:)'] ) );
y1 = max( eval( [char(Variables(Vy)), '(:)'] ) );

xlim( [x0, x1] )
ylim( [y0, y1] )

xlabel( char( Variables(Vx) ) )
ylabel( char( Variables(Vy) ) )
title ( char( Variables(Vr) ) )

axis equal
view( 2 )