function export_ab_matrix(solver, outDir)
%EXPORT_AB_MATRIX  Export assembled A (COO) and b in OpticsFEM3D text format.
%
%   export_ab_matrix(solver)
%   export_ab_matrix(solver, outDir)
%
% Writes Ai.txt, Aj.txt, Av.txt, Bv_real.txt, Bv_imag.txt compatible with
% 3D opticsfem-master/build/Release/OutFile/ layout.
% Row/column indices are 0-based (MATLAB edge IDs minus 1).

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

Ai = solver.Ai(:) - 1;
Aj = solver.Aj(:) - 1;
Av = complex(solver.Av(:));
b = complex(solver.b(:));

fidAi = fopen(fullfile(outDir, 'Ai.txt'), 'w');
fidAj = fopen(fullfile(outDir, 'Aj.txt'), 'w');
fidAv = fopen(fullfile(outDir, 'Av.txt'), 'w');
fidBr = fopen(fullfile(outDir, 'Bv_real.txt'), 'w');
fidBi = fopen(fullfile(outDir, 'Bv_imag.txt'), 'w');
cleanup = onCleanup(@() closeOpenFiles({fidAi, fidAj, fidAv, fidBr, fidBi}));

fprintf(fidAi, '%d\n', Ai);
fprintf(fidAj, '%d\n', Aj);
fprintf(fidAv, '(%g,%g)\n', [real(Av), imag(Av)].');

fprintf(fidBr, '%.12g\n', real(b));
fprintf(fidBi, '%.12g\n', imag(b));

fprintf('Exported A/b to %s\n', outDir);
fprintf('  nnz=%d, b length=%d\n', numel(Ai), numel(b));
end

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