function export_eigen_fields(freq, Ex, Ey, Ez, outDir)
%EXPORT_EIGEN_FIELDS  Write freq / Ex / Ey / Ez / normE for FemType=5 comparison.
%
%   export_eigen_fields(freq, Ex, Ey, Ez)
%   export_eigen_fields(freq, Ex, Ey, Ez, outDir)
%
% Format matches OpticsFEM3D Post_3D_EigenFreq::OutputData:
%   freq          — one line per mode:  real imag  (Hz)
%   Ex,Ey,Ez      — multi-mode, each block preceded by '//' on its own line
%   normE         — sqrt(|Ex|^2+|Ey|^2+|Ez|^2), same block layout as C++

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

freq = freq(:);
nMode = numel(freq);
if size(Ex, 2) ~= nMode
    error('export_eigen_fields:SizeMismatch', ...
        'freq has %d modes but Ex has %d columns.', nMode, size(Ex, 2));
end

fidF = fopen(fullfile(outDir, 'freq'), 'w');
fidEx = fopen(fullfile(outDir, 'Ex'), 'w');
fidEy = fopen(fullfile(outDir, 'Ey'), 'w');
fidEz = fopen(fullfile(outDir, 'Ez'), 'w');
fidNe = fopen(fullfile(outDir, 'normE'), 'w');
cleanup = onCleanup(@() closeOpenFiles({fidF, fidEx, fidEy, fidEz, fidNe}));

for k = 1:nMode
    fprintf(fidF, '%.12g %.12g\n', real(freq(k)), imag(freq(k)));

    fprintf(fidEx, '//\n');
    fprintf(fidEy, '//\n');
    fprintf(fidEz, '//\n');
    fprintf(fidNe, '//\n');

    ex = Ex(:, k);
    ey = Ey(:, k);
    ez = Ez(:, k);
    ne = sqrt(abs(ex).^2 + abs(ey).^2 + abs(ez).^2);

    fprintf(fidEx, '%.12g %.12g\n', [real(ex), imag(ex)].');
    fprintf(fidEy, '%.12g %.12g\n', [real(ey), imag(ey)].');
    fprintf(fidEz, '%.12g %.12g\n', [real(ez), imag(ez)].');
    fprintf(fidNe, '%.12g\n', ne);
end

fprintf('Exported eigen fields to %s\n', outDir);
fprintf('  NbrMode=%d, NbrVertex=%d\n', nMode, size(Ex, 1));
fprintf('  freq (Hz): %s\n', mat2str(real(freq(:)).', 5));
fprintf('  max(normE) per mode: %s\n', mat2str(max(sqrt(abs(Ex).^2+abs(Ey).^2+abs(Ez).^2), [], 1), 5));
end

function closeOpenFiles(fids)
for k = 1:numel(fids)
    if fids{k} > 0
        fclose(fids{k});
    end
end
end
