function exportOutFileFem2(outDir)
%EXPORTOUTFILEFEM2  MainFem2 / MeshData2：求解并导出 OutFile（场、S、X、fig4/5）
%
%   exportOutFileFem2
%   exportOutFileFem2('OutFile_fem2')

rootDir = fileparts(mfilename('fullpath'));
if nargin < 1 || isempty(outDir)
    outDir = fullfile(rootDir, 'OutFile_fem2');
end
if ~exist(outDir, 'dir')
    mkdir(outDir);
end

addpath(rootDir);

meshFile = fullfile(rootDir, 'MeshData2.mat');
S = load(meshFile);
Mesh = S.Mesh;
[Physic, Material, Port1Solver, Port2Solver] = configPhysicMaterialFem4();
if ~isfield(Mesh, 'NbrNodes')
    Mesh.NbrNodes = length(Mesh.Nodes);
    Mesh.NbrElements = length(Mesh.Elements);
end

fprintf('=== MainFem2 / MeshData2 export ===\n');
fprintf('nodes=%d elements=%d  z=[%g,%g]\n', ...
    size(Mesh.Nodes,1), size(Mesh.Elements,1), ...
    min(Mesh.Nodes(:,3)), max(Mesh.Nodes(:,3)));

Port1Mesh = GetBMesh(Mesh.Nodes, Mesh.Faces, Mesh.FacesIndex, Physic.Port1);
[Port1Solver, Port1Mesh] = BoundaryEigenMode(Port1Mesh, Physic, Material, Port1Solver);
Port1Solver = GetPowerCoef(Port1Solver, Port1Mesh, Material.murF, 1);
Port1Mesh.normal = [0; 0; -1];

Port2Mesh = GetBMesh(Mesh.Nodes, Mesh.Faces, Mesh.FacesIndex, Physic.Port2);
[Port2Solver, Port2Mesh] = BoundaryEigenMode(Port2Mesh, Physic, Material, Port2Solver);
Port2Mesh.normal = [0; 0; 1];

[Solver, Mesh] = FemMatrixAssembly(Physic, Material, Mesh, ...
    Port1Mesh, Port1Solver, Port2Mesh, Port2Solver);

S11 = Solver.e1 / abs(Port1Solver.powerCoef);
S21 = Solver.e2 / abs(Port1Solver.powerCoef);
fprintf('powerCoef=%g\n', Port1Solver.powerCoef);
fprintf('S11=%g%+gi  S21=%g%+gi\n', real(S11), imag(S11), real(S21), imag(S21));
fprintf('|S11|=%g  |S21|=%g\n', abs(S11), abs(S21));

savePortResults(outDir, Mesh, Solver, S11, S21, Port1Solver, Port2Solver);

fid = fopen(fullfile(outDir, 'X_real.txt'), 'w');
fprintf(fid, '%.16g\n', real(Solver.Et));
fclose(fid);
fid = fopen(fullfile(outDir, 'X_imag.txt'), 'w');
fprintf(fid, '%.16g\n', imag(Solver.Et));
fclose(fid);
fid = fopen(fullfile(outDir, 'e_port.txt'), 'w');
fprintf(fid, 'e1_re e1_im e2_re e2_im\n');
fprintf(fid, '%.16g %.16g %.16g %.16g\n', ...
    real(Solver.e1), imag(Solver.e1), real(Solver.e2), imag(Solver.e2));
fclose(fid);

[~, ~, ~, normE_elem] = GetExEyEz2(1, Mesh.Nodes, Mesh.Elements, ...
    Mesh.EdgesOfElements, Solver.Et);
In = plotE2(Mesh.Nodes, Port1Mesh.OldFaces, Mesh.AllFaces, ...
    Mesh.FacesOfElements, normE_elem, 4, 0.5);
Out = plotE2(Mesh.Nodes, Port2Mesh.OldFaces, Mesh.AllFaces, ...
    Mesh.FacesOfElements, normE_elem, 5, 0.5);
saveas(figure(4), fullfile(outDir, 'fig4_port_in_matlab.png'));
saveas(figure(5), fullfile(outDir, 'fig5_port_out_matlab.png'));
fprintf('port max |E| in=%g out=%g\n', In, Out);
fprintf('Saved OutFile -> %s\n', outDir);

end
