function meqweqdsk(eqdsk,fname)
% MEQWEQDSK write G-EQDSK MATLAB structure to file
%
%   meqweqdsk(eqdsk,fname);
% Where eqdsk is a structure as generated by meq2eqdsk()
%
% Based on the write_eqdsk routine from the CHEASEgui toolbox by Olivier Sauter (SPC-EPFL).
%
% See also MEQ2EQDSK
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

fpath=fileparts(fname);
if isempty(fpath); fpath=pwd; fname=fullfile(fpath,fname); end

if ~exist(fpath,'dir'); mkdir(fpath); end
fid=fopen(fname,'w');

dumzer0 = 0;
% TITLE, IDUM, NR: FORMAT 48A, 3I4
ind1 = 3; % not sure of this parameter, put 3 by default
fprintf(fid,'%48s%4d%4d%4d\n',eqdsk.stitle,ind1,eqdsk.nr,eqdsk.nz);
% RBOXLEN, ZBOXLEN, R0EXP, RBOXLFT, ZMID: FORMAT 5E16.9
fprintf(fid,'%16.9E%16.9E%16.9E%16.9E%16.9E\n',eqdsk.rboxlen,eqdsk.zboxlen,eqdsk.r0,eqdsk.rboxleft,eqdsk.zmid);
% RAXIS, ZAXIS, PSIAXIS, PSIEDGE, B0EXP: FORMAT 5E16.9
fprintf(fid,'%16.9E%16.9E%16.9E%16.9E%16.9E\n',eqdsk.raxis,eqdsk.zaxis,eqdsk.psiaxis,eqdsk.psiedge,eqdsk.b0);
% IP, PSIAXIS, ZERO, RAXIS, ZERO: FORMAT 5E16.9
fprintf(fid,'%16.9E%16.9E%16.9E%16.9E%16.9E\n',eqdsk.ip,eqdsk.psiaxis,dumzer0,eqdsk.raxis,dumzer0);
% ZAXIS, ZERO, PSIEDGE, ZERO, ZERO: FORMAT 5E16.9
fprintf(fid,'%16.9E%16.9E%16.9E%16.9E%16.9E\n',eqdsk.zaxis,dumzer0,eqdsk.psiedge,dumzer0,dumzer0);
% T(NR): FORMAT 5E16.9
write_array(fid,'%16.9E',5,eqdsk.F);
% P(NR): FORMAT 5E16.9
write_array(fid,'%16.9E',5,eqdsk.p);
% TT_PRIME(NR): FORMAT 5E16.9
write_array(fid,'%16.9E',5,eqdsk.FFprime);
% P_PRIME(NR): FORMAT 5E16.9
write_array(fid,'%16.9E',5,eqdsk.pprime);
% PSI(R,Z): FORMAT 5E16.9
write_array(fid,'%16.9E',5,eqdsk.psirz);
% Q(NR): FORMAT 5E16.9
write_array(fid,'%16.9E',5,eqdsk.q);
% NPLASMA_BOUND, NLIMITER_BOUND: FORMAT 2I5
fprintf(fid,'%5d%5d\n',eqdsk.nbbound,eqdsk.nblim);
% RPLASMA_BOUND(NPLASMA_BOUND), ZPLASMA_BOUND(NPLASMA_BOUND)
if eqdsk.nbbound>0
  aa=reshape([eqdsk.rplas' ; eqdsk.zplas'],2*eqdsk.nbbound,1);
  write_array(fid,'%16.9E',5,aa);
end
% RLIMITER_BOUND(NLIMITER_BOUND), ZLIMITER_BOUND(NLIMITER_BOUND)
if eqdsk.nblim>0
  aa=reshape([eqdsk.rlim' ; eqdsk.zlim'],2*eqdsk.nblim,1);
  write_array(fid,'%16.9E',5,aa);
end
  
% EXTRA LINES
if isfield(eqdsk,'extralines')
  for i=1:length(eqdsk.extralines)
    fprintf(fid,'%s\n',eqdsk.extralines{i});
  end
end
  
fclose_out=fclose(fid);

end

function write_array(fid,format,nperline,array)
fprintf(fid,[repmat(format,1,nperline),newline],array(1:end-1));
fprintf(fid,[       format            ,newline],array(  end  ));
end
