function savePortResults(outDir, Mesh, Solver, S11, S21, Port1Solver, Port2Solver)
%SAVEPORTRESULTS  写出 normE / S 参数，供 C++ 与 COMSOL 对比

if ~exist(outDir, 'dir')
    mkdir(outDir);
end

writeScalarList(fullfile(outDir, 'normE'), Solver.normE);
writeScalarList(fullfile(outDir, 'Ex_real'), real(Solver.Ex));
writeScalarList(fullfile(outDir, 'Ex_imag'), imag(Solver.Ex));
writeScalarList(fullfile(outDir, 'Ey_real'), real(Solver.Ey));
writeScalarList(fullfile(outDir, 'Ey_imag'), imag(Solver.Ey));
writeScalarList(fullfile(outDir, 'Ez_real'), real(Solver.Ez));
writeScalarList(fullfile(outDir, 'Ez_imag'), imag(Solver.Ez));

fid = fopen(fullfile(outDir, 'S_params.txt'), 'w');
fprintf(fid, 'S11_real S11_imag S21_real S21_imag powerCoef neff1_real neff1_imag\n');
fprintf(fid, '%.16g %.16g %.16g %.16g %.16g %.16g %.16g\n', ...
    real(S11), imag(S11), real(S21), imag(S21), ...
    Port1Solver.powerCoef, real(Port1Solver.neff(1)), imag(Port1Solver.neff(1)));
fclose(fid);

meta = struct();
meta.lam0 = 1.55e-6;
meta.meshNodes = size(Mesh.Nodes, 1);
meta.meshElements = size(Mesh.Elements, 1);
save(fullfile(outDir, 'run_meta.mat'), 'meta', 'S11', 'S21', 'Port1Solver', 'Port2Solver');

end

function writeScalarList(path, values)
fid = fopen(path, 'w');
fprintf(fid, '//\n');
fprintf(fid, '%.16g\n', values(:));
fclose(fid);
end
