function grace(cfg,xg)
arguments
    cfg (1,1) struct {mustBeNonempty}
    xg (1,1) struct {mustBeNonempty}
end

%% unpack configuration data
ymd = cfg.ymd;
UTsec0 = cfg.UTsec0;
tdur = cfg.tdur;
dtprec = cfg.dtprec;
dtE0 = cfg.dtE0;
itprec = 0:dtprec:tdur;
itE0 = 0:dtE0:tdur;
ltE0 = length(itE0);

%% unpack grid data
x2 = xg.x2(3:end-2);
x3 = xg.x3(3:end-2);
mlon = squeeze(xg.phi(end,:,1))*180/pi;
mlat = 90-squeeze(xg.theta(end,1,:))*180/pi;
llon = length(mlon);
llat = length(mlat);

%% create east-north-time grid
[~,X3prec,~] = ndgrid(x2,x3,itprec);
[~,X3E0,~] = ndgrid(x2,x3,itE0);

%% generate input data maps
if strcmp(cfg.ap_rocket,'crex')
    [Qit,E0it,~] = crex(X3prec,cfg);
    [~,~,phi] = crex(X3E0,cfg);
elseif strcmp(cfg.ap_rocket,'lamp')
end

%% write precip files
pg.mlon = mlon;
pg.mlat = mlat;
pg.llon = llon;
pg.llat = llat;
pg.Qit = Qit;
pg.E0it = E0it;
pg.times = datetime(ymd) + seconds(UTsec0+itprec);
gemini3d.write.precip(pg,cfg.prec_dir)

%% write field files
Vmaxx1it = phi;
Vmaxx1it(:,:,1) = zeros(llon,llat); % no forcing in first timestep

E.flagdirich = ones(1,ltE0)*cfg.flagdirich;
E.Exit = ones(llon,llat,ltE0)*cfg.ap_ExBg;
E.Eyit = ones(llon,llat,ltE0)*cfg.ap_EyBg;
E.Vminx1it = zeros(llon,llat,ltE0);
E.Vmaxx1it = Vmaxx1it;
E.Vminx2ist = zeros(llat,ltE0);
E.Vmaxx2ist = zeros(llat,ltE0);
E.Vminx3ist = zeros(llon,ltE0);
E.Vmaxx3ist = zeros(llon,ltE0);
E.mlon = mlon;
E.mlat = mlat;
E.llon = llon;
E.llat = llat;
E.times = datetime(ymd) + seconds(UTsec0+itE0);
gemini3d.write.Efield(E,cfg.E0_dir);

%% functions
% input function
    function [Qit,E0it,phi] = crex(x3,pars)
        p = pars;
        Qit = p.Q_amp * gaussian(x3,p.Q_pos,p.Q_wth);
        E0it = p.E_min + (p.E_amp - p.E_min) * gaussian(x3,p.E_pos,p.E_wth);
        phi = p.F_bkg * p.B_mag * x3...
            + sqrt(pi/16/log(2)) * (p.F_bkg-p.F_amp) * p.F_wth * p.B_mag *...
            erf(2 * sqrt(log(2)) * (p.F_pos-x3)/p.F_wth);
    end

% gaussian definition
    function v = gaussian(x3,pos,fwhm)
        v = exp(-4*log(2)*(x3-pos).^2/fwhm^2);
    end
end