function export_fields(Ex, Ey, Ez, normE, outDir)
%EXPORT_FIELDS  Write Ex/Ey/Ez/normE in OpticsFEM 3D scatter post format.

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

Ex = Ex(:);
Ey = Ey(:);
Ez = Ez(:);
normE = normE(:);

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({fidEx, fidEy, fidEz, fidNe}));

fprintf(fidEx, '//\n');
fprintf(fidEy, '//\n');
fprintf(fidEz, '//\n');
fprintf(fidNe, '//\n');
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', normE);

fprintf('Exported fields to %s (NbrVertex=%d)\n', outDir, numel(normE));
fprintf('  max(normE)=%.12g\n', max(normE));
end

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