function pdetool_write(flag)
% case: write geometry to MATLAB-file

%   Copyright 1994-2016 The MathWorks, Inc.

    pde_fig=findobj(allchild(0),'flat','Tag','PDETool');

    pde_circ=1; pde_poly=2; pde_rect=3; pde_ellip=4;

    fid=flag;
    
    editMsg = message('pde:pdetool:editWarning').getString();
    fprintf(fid, editMsg);
    
    fprintf(fid,'function pdemodel\n');

    fprintf(fid,'[pde_fig,ax]=pdeinit;\n');

    ax=findobj(get(pde_fig,'Children'),'flat','Tag','PDEAxes');

    % application parameters:
    appl=getappdata(pde_fig,'application');
    if (appl>1 && appl<5)
        mode=2;
    else
        mode=1;
    end
    fprintf(fid,'pdetool(''appl_cb'',%i);\n',appl);

    % scaling, grid etc. ...
    if getappdata(ax,'snap')
        fprintf(fid,'pdetool(''snapon'',''on'');\n');
    end

    xmax=get(ax,'XLim');
    ymax=get(ax,'YLim');
    dasp=get(ax,'DataAspectRatio');
    pasp=get(ax,'PlotBoxAspectRatio');
    xtck=get(ax,'XTick');
    ytck=get(ax,'YTick');
    n=length(xtck);
    tmps=char(ones(n,1)*' %.17g,...\n');
    tmps=tmps';
    tmps=reshape(tmps,1,12*n);
    tmpx=sprintf(tmps,xtck);
    n=length(ytck);
    tmps=char(ones(n,1)*' %.17g,...\n');
    tmps=tmps';
    tmps=reshape(tmps,1,12*n);
    tmpy=sprintf(tmps,ytck);

    fprintf(fid,'set(ax,''DataAspectRatio'',[%.17g %.17g %.17g]);\n',dasp);
    fprintf(fid,'set(ax,''PlotBoxAspectRatio'',[%.17g %.17g %.17g]);\n',pasp);

    if strcmp(get(ax,'XLimMode'),'auto')
        fprintf(fid,'set(ax,''XLimMode'',''auto'');\n');
    else
        fprintf(fid,'set(ax,''XLim'',[%.17g %.17g]);\n',xmax);
    end
    if strcmp(get(ax,'YLimMode'),'auto')
        fprintf(fid,'set(ax,''YLimMode'',''auto'');\n');
    else
        fprintf(fid,'set(ax,''YLim'',[%.17g %.17g]);\n',ymax);
    end

    if strcmp(get(ax,'XTickMode'),'auto')
        fprintf(fid,'set(ax,''XTickMode'',''auto'');\n');
    else
        fprintf(fid,'set(ax,''XTick'',[%s]);\n',tmpx);
    end
    if strcmp(get(ax,'YTickMode'),'auto')
        fprintf(fid,'set(ax,''YTickMode'',''auto'');\n');
    else
        fprintf(fid,'set(ax,''YTick'',[%s]);\n',tmpy);
    end

    extrax=pdequote(getappdata(ax,'extraspacex'));
    extray=pdequote(getappdata(ax,'extraspacey'));
    if ~isempty(extrax)
        fprintf(fid,'setappdata(ax,''extraspacex'',''%s'');\n',extrax);
    end
    if ~isempty(extray)
        fprintf(fid,'setappdata(ax,''extraspacey'',''%s'');\n',extray);
    end

    opthndl=findobj(get(pde_fig,'Children'),'flat','Tag','PDEOptMenu');
    gridhndl=findobj(get(opthndl,'Children'),'flat','Tag','PDEGrid');
    if strcmp(get(gridhndl,'Checked'),'on')
        fprintf(fid,'pdetool(''gridon'',''on'');\n');
    end

    pdegd=get(findobj(get(pde_fig,'Children'),'flat',...
        'Tag','PDEMeshMenu'),'UserData');

    labels=pdequote(getappdata(pde_fig,'objnames'));
    fprintf(fid,'\n%% Geometry description:\n');
    for i=1:size(pdegd,2)
        if pdegd(1,i)==pde_circ
            fprintf(fid,'pdecirc(%.17g,%.17g,%.17g,''%s'');\n',...
                pdegd(2:4,i),deblank(labels(:,i)'));
        elseif pdegd(1,i)==pde_ellip
            fprintf(fid,['pdeellip(%.17g,%.17g,%.17g,%.17g,...\n',...
                '%.17g,''%s'');\n'],...
                pdegd(2:6,i),deblank(labels(:,i)'));
        elseif pdegd(1,i)==pde_rect
            tmp=[pdegd(3:4,i)', pdegd(7,i), pdegd(9,i)];
            fprintf(fid,'pderect([%.17g %.17g %.17g %.17g],''%s'');\n',...
                tmp,deblank(labels(:,i)'));
        elseif pdegd(1,i)==pde_poly
            n=pdegd(2,i);
            tmps=char(ones(n,1)*' %.17g,...\n');
            tmps=tmps';
            tmps=reshape(tmps,1,12*n);
            tmpx=sprintf(tmps,pdegd(3:2+n,i));
            tmpy=sprintf(tmps,pdegd(3+n:2*n+2,i));
            fprintf(fid,'pdepoly([%s],...\n[%s],...\n ''%s'');\n',...
                tmpx,tmpy,deblank(labels(:,i)'));
        end
    end

    evalhndl=findobj(get(pde_fig,'Children'),'flat','Tag','PDEEval');
    evalstring=pdequote(get(evalhndl,'String'));
    fprintf(fid,['set(findobj(get(pde_fig,''Children''),'...
        '''Tag'',''PDEEval''),''String'',''%s'')\n'],evalstring);

    % non-empty boundary condition matrix and compatible geometry needed
    menuhndl=findobj(get(pde_fig,'Children'),'flat','Tag','PDEBoundMenu');
    hbound=findobj(get(menuhndl,'Children'),'flat','Tag','PDEBoundMode');
    pdebound=get(hbound,'UserData');
    h=findobj(get(pde_fig,'Children'),'flat','Tag','PDEFileMenu');
    flags=get(h,'UserData');

    if ~isempty(pdebound) && ~abs(flags(3))

        ax=findobj(get(pde_fig,'Children'),'flat','Tag','PDEAxes');
        bndlines=findobj(get(ax,'Children'),'flat','Tag','PDEBoundLine');
        nb=length(bndlines);
        % extract column in pdebound from external boundary lines' user data
        % column no is first user data entry
        for i=1:nb
            ud=get(bndlines(i),'UserData');
            bndcol(i)=ud(1);
        end

        fprintf(fid,'\n%% Boundary conditions:\n');
        fprintf(fid,'pdetool(''changemode'',0)\n');

        bl=getappdata(pde_fig,'bl');
        n=size(bl,1);
        for i=1:n
            blrow=bl(i,:);
            blines=blrow(1:find(blrow, 1, 'last' ));
            tmps=sprintf('%i ',blines);
            tmps=['[', tmps, ']'];
            fprintf(fid,'pdetool(''removeb'',%s);\n',tmps);
        end

        outbnds=find(pdebound(1,:)~=0);
        n=length(outbnds);
        for i=1:n
            j=bndcol(i);
            nn=pdebound(1,j);
            mm=pdebound(2,j);
            if nn==1
                if mm==0
                    type='neu';
                    ql=pdebound(3,j);
                    gl=pdebound(4,j);
                    qstr=sprintf('''%s''',pdequote(char(pdebound(5:4+ql,j))'));
                    gstr=sprintf('''%s''',...
                        pdequote(char(pdebound(5+ql:4+ql+gl,j))'));
                    fprintf(fid,['pdesetbd(%i,...\n',...
                        '''%s'',...\n',...
                        '%i,...\n',...
                        '%s,...\n',...
                        '%s)\n'],...
                        j,type,mode,qstr,gstr);
                elseif mm==1
                    type='dir';
                    hl=pdebound(5,j);
                    rl=pdebound(6,j);
                    hstr=sprintf('''%s''',pdequote(char(pdebound(9:8+hl,j))'));
                    rstr=sprintf('''%s''',...
                        pdequote(char(pdebound(9+hl:8+hl+rl,j))'));
                    fprintf(fid,['pdesetbd(%i,...\n',...
                        '''%s'',...\n',...
                        '%i,...\n',...
                        '%s,...\n',...
                        '%s)\n'],...
                        j,type,mode,hstr,rstr);
                end
            elseif nn==2
                if mm==0
                    type='neu';
                    ql=pdebound(3:6,j);
                    gl=pdebound(7:8,j);
                    qstr=sprintf('char(''%s'',''%s'',''%s'',''%s'')',...
                        pdequote(char(pdebound(9:8+ql(1),j))'),...
                        pdequote(char(pdebound(9+ql(1):8+sum(ql(1:2)),j))'),...
                        pdequote(char(pdebound(9+sum(ql(1:2)):8+sum(ql(1:3)),j))'),...
                        pdequote(char(pdebound(9+sum(ql(1:3)):8+sum(ql),j))'));
                    gstr=sprintf('char(''%s'',''%s'')',...
                        pdequote(char(pdebound(9+sum(ql):8+sum(ql)+gl(1),j))'),...
                        pdequote(char(...
                        pdebound(9+sum(ql)+gl(1):8+sum(ql)+sum(gl),j))'));
                    fprintf(fid,['pdesetbd(%i,...\n',...
                        '''%s'',...\n',...
                        '%i,...\n',...
                        '%s,...\n',...
                        '%s)\n'],...
                        j,type,mode,qstr,gstr);
                elseif mm==1
                    type='mix';
                    ql=pdebound(3:6,j);
                    gl=pdebound(7:8,j);
                    hl=pdebound(9:10,j);
                    rl=pdebound(11,j);
                    qstr=sprintf('char(''%s'',''%s'',''%s'',''%s'')',...
                        pdequote(char(pdebound(12:11+ql(1),j))'),...
                        pdequote(char(pdebound(12+ql(1):11+sum(ql(1:2)),j))'),...
                        pdequote(char(...
                        pdebound(12+sum(ql(1:2)):11+sum(ql(1:3)),j))'),...
                        pdequote(char(pdebound(12+sum(ql(1:3)):11+sum(ql),j))'));
                    gstr=sprintf('char(''%s'',''%s'')',...
                        pdequote(char(pdebound(12+sum(ql):11+sum(ql)+gl(1),j))'),...
                        pdequote(char(...
                        pdebound(12+sum(ql)+gl(1):11+sum(ql)+sum(gl),j))'));
                    hstr=sprintf('char(''%s'',''%s'')',...
                        pdequote(char(pdebound(12+sum(ql)+sum(gl):...
                        11+sum(ql)+sum(gl)+hl(1),j))'),...
                        pdequote(char(...
                        pdebound(12+sum(ql)+sum(gl)+hl(1):...
                        11+sum(ql)+sum(gl)+sum(hl),j))'));
                    rstr=pdequote(char(pdebound(12+sum(ql)+sum(gl)+sum(hl):...
                        11+sum(ql)+sum(gl)+sum(hl)+rl,j))');
                    fprintf(fid,['pdesetbd(%i,...\n',...
                        '''%s'',...\n',...
                        '%i,...\n',...
                        '%s,...\n',...
                        '%s,...\n',...
                        '%s,...\n',...
                        '''%s'')\n'],...
                        j,type,mode,qstr,gstr,hstr,rstr);
                elseif mm==2
                    type='dir';
                    hl=pdebound(9:12,j);
                    rl=pdebound(13:14,j);
                    hstr=sprintf('char(''%s'',''%s'',''%s'',''%s'')',...
                        pdequote(char(pdebound(21:20+hl(1),j))'),...
                        pdequote(char(pdebound(21+hl(1):20+sum(hl(1:2)),j))'),...
                        pdequote(char(pdebound(21+sum(hl(1:2)):...
                        20+sum(hl(1:3)),j))'),...
                        pdequote(char(pdebound(21+sum(hl(1:3)):20+sum(hl),j))'));
                    rstr=sprintf('char(''%s'',''%s'')',...
                        pdequote(char(pdebound(21+sum(hl):20+sum(hl)+rl(1),j))'),...
                        pdequote(char(...
                        pdebound(21+sum(hl)+rl(1):20+sum(hl)+sum(rl),j))'));
                    fprintf(fid,['pdesetbd(%i,...\n',...
                        '''%s'',...\n',...
                        '%i,...\n',...
                        '%s,...\n',...
                        '%s)\n'],...
                        j,type,mode,hstr,rstr);
                end
            end
        end

        meshstat=getappdata(pde_fig,'meshstat');
        n=length(meshstat);
        if n>0
            fprintf(fid,'\n%% Mesh generation:\n');
            trisize=getappdata(pde_fig,'trisize');
            if ~isempty(trisize)
                if ischar(trisize)
                    fprintf(fid,'setappdata(pde_fig,''trisize'',''%s'');\n',...
                        trisize);
                else
                    fprintf(fid,...
                        'setappdata(pde_fig,''trisize'',%.17g);\n', trisize);
                end
            end
            Hgrad=getappdata(pde_fig,'Hgrad');
            fprintf(fid,'setappdata(pde_fig,''Hgrad'',%.17g);\n', Hgrad);
            refmet=getappdata(pde_fig,'refinemethod');
            fprintf(fid,'setappdata(pde_fig,''refinemethod'',''%s'');\n',...
                refmet);
            jiggle=getappdata(pde_fig,'jiggle');
            fprintf(fid,'setappdata(pde_fig,''jiggle'',char(''%s'',''%s'',''%s''));\n',...
                strtrim(jiggle(1,:)), strtrim(jiggle(2,:)), strtrim(jiggle(3,:)));
            meshAlgo=getappdata(pde_fig,'MesherVersion');
            fprintf(fid,'setappdata(pde_fig,''MesherVersion'',''%s'');\n',...
                meshAlgo);
            for i=1:n
                if meshstat(i)==1
                    fprintf(fid,'pdetool(''initmesh'')\n');
                elseif meshstat(i)==2
                    fprintf(fid,'pdetool(''refine'')\n');
                elseif meshstat(i)==3
                    fprintf(fid,'pdetool(''jiggle'')\n');
                elseif meshstat(i)==4
                    % mesh change from adaptive solver
                    break;
                end
            end
        end

    end

    fprintf(fid,'\n%% PDE coefficients:\n');
    % Unpack parameters:
    params=pdequote(get(findobj(get(pde_fig,'Children'),'flat',...
        'Tag','PDEPDEMenu'),'UserData'));
    timeeigpar=pdequote(getappdata(pde_fig,'timeeigparam'));
    ncafd=getappdata(pde_fig,'ncafd');
    nc=ncafd(1); na=ncafd(2); nf=ncafd(3); nd=ncafd(4);
    c=params(1:nc,:); a=params(nc+1:nc+na,:);
    f=params(nc+na+1:nc+na+nf,:);
    d=params(nc+na+nf+1:nc+na+nf+nd,:);
    cstr=['''', deblank(c(1,:)), ''''];
    if nc>1
        if nc<12
            for i=2:nc
                cstr=[cstr, ',''' deblank(c(i,:)), '''']; %#ok - suppress preallocation warning
            end
            cp=sprintf('char(%s)',cstr);
        else
            for i=2:11
                cstr=[cstr, ',''' deblank(c(i,:)), '''']; %#ok - suppress preallocation warning
            end
            cstr2=['''', deblank(c(12,:)), ''''];
            for i=13:nc
                cstr2=[cstr2, ',''' deblank(c(i,:)), '''']; %#ok - suppress preallocation warning
            end
            cp=sprintf('char(char(%s),%s)',cstr,cstr2);
        end
    else
        cp=cstr;
    end
    astr=['''', deblank(a(1,:)), ''''];
    if na>1
        for i=2:na
            astr=[astr, ',''' deblank(a(i,:)), '''']; %#ok - suppress preallocation warning
        end
        ap=sprintf('char(%s)',astr);
    else
        ap=astr;
    end
    fstr=['''', deblank(f(1,:)), ''''];
    if nf>1
        for i=2:nf
            fstr=[fstr, ',''' deblank(f(i,:)), '''']; %#ok - suppress preallocation warning
        end
        fp=sprintf('char(%s)',fstr);
    else
        fp=fstr;
    end
    dstr=['''', deblank(d(1,:)), ''''];
    if nd>1
        for i=2:nd
            dstr=[dstr, ',''' deblank(d(i,:)), '''']; %#ok - suppress preallocation warning
        end
        dp=sprintf('char(%s)',dstr);
    else
        dp=dstr;
    end
    pde_type=get(findobj(get(pde_fig,'Children'),'flat',...
        'Tag','PDEHelpMenu'),'UserData');
    fprintf(fid,['pdeseteq(%i,...\n',...
        '%s,...\n',...
        '%s,...\n',...
        '%s,...\n',...
        '%s,...\n',...
        '''%s'',...\n',...
        '''%s'',...\n',...
        '''%s'',...\n',...
        '''%s'')\n'],...
        pde_type,cp,ap,fp,dp,deblank(timeeigpar(1,:)),...
        deblank(timeeigpar(2,:)),deblank(timeeigpar(3,:)),...
        deblank(timeeigpar(4,:)));

    [currparams,I]=pdequote(getappdata(pde_fig,'currparam'));
    nc=size(currparams,1);
    if ~isempty(I)
        cpstr=sprintf('[''%s'';...\n', currparams(1,1:I(1)));
        for i=2:nc-1
            cpstr=sprintf('%s''%s'';...\n', cpstr, currparams(i,1:I(i)));
        end
        cpstr=sprintf('%s''%s'']',cpstr, currparams(nc,1:I(nc)));
        fprintf(fid,['setappdata(pde_fig,''currparam'',...\n',...
            '%s)\n'],cpstr);
    end

    fprintf(fid,'\n%% Solve parameters:\n');
    % Unpack parameters:
    solveparams=pdequote(getappdata(pde_fig,'solveparam'));
    adapt=deblank(solveparams(1,:));
    maxtri=deblank(solveparams(2,:));
    maxref=deblank(solveparams(3,:));
    tripick=deblank(solveparams(4,:));
    param=deblank(solveparams(5,:));
    refmet=deblank(solveparams(6,:));
    nonlin=deblank(solveparams(7,:));
    nonlintol=deblank(solveparams(8,:));
    nonlininit=deblank(solveparams(9,:));
    jac=deblank(solveparams(10,:));
    nonlinnorm=deblank(solveparams(11,:));
    fprintf(fid,['setappdata(pde_fig,''solveparam'',...\n',...
        'char(''%s'',''%s'',''%s'',''%s'',...\n',...
        '''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s''))\n'],...
        adapt,maxtri,maxref,tripick,param,refmet,...
        nonlin,nonlintol,nonlininit,jac,nonlinnorm);

    fprintf(fid,'\n%% Plotflags and user data strings:\n');
    plotflags=getappdata(pde_fig,'plotflags');
    fprintf(fid,...
        ['setappdata(pde_fig,''plotflags'',', mat2str(plotflags), ');\n']);
    colstring=pdequote(getappdata(pde_fig,'colstring'));
    fprintf(fid,...
        ['setappdata(pde_fig,''colstring'',''', colstring, ''');\n']);
    arrowstring=pdequote(getappdata(pde_fig,'arrowstring'));
    fprintf(fid,...
        ['setappdata(pde_fig,''arrowstring'',''', arrowstring, ''');\n']);
    deformstring=pdequote(getappdata(pde_fig,'deformstring'));
    fprintf(fid,...
        ['setappdata(pde_fig,''deformstring'',''', deformstring, ''');\n']);
    heightstring=pdequote(getappdata(pde_fig,'heightstring'));
    fprintf(fid,...
        ['setappdata(pde_fig,''heightstring'',''', heightstring, ''');\n']);

    if ~abs(flags(3)) && flags(6)
        fprintf(fid,'\n%% Solve PDE:\n');
        fprintf(fid,'pdetool(''solve'')\n');
    end

    fclose(fid);
end