function [geom,g,ng, config, params] = build_geom(rho,rhogauss,config, params)
% [geom,g,ng] = build_geom(rho,rhogauss,config)
% geom contains spline matrices and indeces of the geometrical parameters.
% g = container for spline coefficients of the geometrical parameters. (right dimension and ordering)

% prepare spline matrices
geom = prep_geom(rho,rhogauss, config);
% get spline coefficients for the geometrical parameters
geom.debug = config.debug.checkgeom; % flag for debugging

ng = geom.ng;
nt = numel(config.grid.tgrid);

if config.equi.eq_call  % The equilibrium solver is called during RAPTOR time iteration
    switch config.equi.source
        case 'liuqe'
            [config.equi, params.equi, params.eq_tran_iter, params.numerics.equi] = conf_params_LIUQE_call(config.equi);
            g = zeros(ng,1);
        otherwise
            error('RAPTOR:UnknownEquilibriumCode', 'Equilibrium code during time iteration call not recognized');
    end
else    % Feedforward equilibrium
    % Get equilibrium data.
    [iR,iR2,dpsi,dpsi2,dpsi2oR2,dpsidV,F,epsilon,Rgeom,kappa,delta,Phib,tgridin,rhoin,config, params] = get_equilibrium_data(config, params);
    
    % Compute geometrical spline coefficients
    if isempty(tgridin) % Use the same equilibrium for all the time slices
        g = zeros(ng,1);
        g = geom2RAPTOR(rhoin,iR,iR2,dpsi,dpsi2,...
            dpsi2oR2,dpsidV,F,...
            epsilon,Rgeom,kappa,delta,Phib, geom);
    else% interpolate to RAPTOR time grid
        g = zeros(ng,nt);
        % Interpolate in RAPTOR time grid
        [rhoin,iR,iR2,dpsi,dpsi2,dpsi2oR2,dpsidV,F,epsilon,Rgeom,kappa,delta,Phib] =...
            interp2RAPTOR_tgrid(tgridin,config.grid.tgrid,...
            rhoin,iR,iR2,dpsi,dpsi2,dpsi2oR2,dpsidV,F,epsilon,Rgeom,kappa,delta,Phib);
        for it = 1:nt
            g(:,it) = geom2RAPTOR(rhoin(:,it),iR(:,it),iR2(:,it),dpsi(:,it),dpsi2(:,it),...
                dpsi2oR2(:,it),dpsidV(:,it),F(:,it),...
                epsilon(:,it),Rgeom(:,it),kappa(:,it),delta(:,it),Phib(it), geom);
        end
    end
end


return