function [jphioR,djphioR_dx] = eval_jphioR(x,g,~,model,gaussgrid)
% #codegen
% function [jtor,djtor_dx] = eval_jphioR(x,g,v,model,whichgrid)
% returns jphioR = <jphi/R>
% Note that 
% jtor =DEF= R0*<jphi/R> = = 2*pi*R0*dIp/dV (see ASTRA manual)
% Full expression in RAPTOR equation doc


if ~gaussgrid;
    gauss = false;
    ngrid = model.rgrid.nrho;
else
    gauss = true;
    ngrid = model.rgrid.nrhogauss;
end

if nargout>1
    der = true; % compute derivative
    djphioR_dx = zeros(ngrid,numel(x)); % init
else
    der = false;
end

mu0    =  pi*4e-7;
Phib   =  eval_Phib([],g,[],model,[]);
Vp     =  eval_Vp([],g,[],model,gauss);

F      =  eval_F([],g,[],model,gauss);
Fp     =  eval_Fp([],g,[],model,gauss);
g23or  =  eval_g23or([],g,[],model,gauss); % d/drho g2*g3/rho
g23orp =  eval_g23orp([],g,[],model,gauss); % d/drho g2*g3/rho

%Alternative way to evaluate Vp
dpsidv = eval_H([],g,[],model,gauss);
psip = eval_psip(x, [],[], model,  gauss);
psipp = eval_psipp(x, [],[], model,  gauss);


k  =  1/(8*pi^2*mu0*Phib);

if ~gauss
    Vpp1  = model.geom.LamGp(1,:)*g(model.geom.ind_Vp);
    djphioR_dpsihat = bsxfun(@times,(k./Vp .* (F.*g23orp + Fp.*g23or) ),model.psi.Lamp) + ...
        bsxfun(@times,(k./Vp .* (F.*g23or) ),model.psi.Lampp);
    
    % l'Hopital for 0/0
    djphioR_dpsihat(1,:) = 2*(k./Vpp1(1) .* F(1).*g23orp(1) )*model.psi.Lampp(1,:);

else
    % gauss grid
    djphioR_dpsihat = bsxfun(@times,(k./Vp .* (F.*g23orp + Fp.*g23or) ),model.psi.Lampgauss) + ...
                bsxfun(@times,(k./Vp .* (F.*g23or) ),model.psi.Lamppgauss);

end
jphioR = djphioR_dpsihat*x(model.psi.xind);

if der
    djphioR_dx(:,model.psi.xind) = djphioR_dpsihat;
end

% Debugging plot
debug_plot = false;
if debug_plot
eval_debugging_plot(mfilename,'rhotor', x, model, gauss, 1./Vp,  '1/Vp', F, 'F', Fp, 'Fp', g23or, 'g23or', ...
    g23orp , 'g23orp', jphioR, 'jphioR', F.*g23orp, 'F.*g23orp',  Fp.*g23or, ' Fp.*g23or', k./Vp .* (F.*g23or),...
    'k./Vp .* (F.*g23or)', k./Vp .* (F.*g23orp), 'k./Vp .* (F.*g23orp)' ,k./Vp .* (F.*g23or).*psipp, 'k./Vp .* (F.*g23or).*psipp', ...
    F.*g23orp./Vp.*psip,'F.*g23orp./Vp.*psip',  Fp.*g23or./Vp.*psip, 'Fp.*g23or./Vp.*psip', psip./Vp, 'psip./Vp', Vp,'Vp', psip,'psip');

end

return
