%FSGIMEX  Flux surface geometrical integrals
%
% This is the MATLAB equivalent implementation of libmeq/fsgi.c.
% A more detailed help is available in FSGIMEX.
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
function [Q0Q,Q1Q,Q2Q,Q3Q,Q4Q,iqQ] = fsgimexm(a1q,a2q,rq,irq,rA,FA,FB,BA,lX,rX,iTQ,idoq)
 hipi = 1/(2*pi);
 irA = 1/rA;
 FAB = FA - FB;
 CA  = hipi*BA; C3 = 16*FAB^2; Cq = 4*idoq*FAB;
 s1q =                      1.0./sum( rq.*a1q) ;
 s2q =                           sum(irq.*a1q) ;
 Q0Q = [irA                 s1q.*sum(     a1q)].';       % <1/R>
 Q1Q = [hipi*CA*irA hipi*Cq*s1q               ].';       % -dpsi/dV
 Q2Q = [irA*irA             s1q.*s2q          ].';       % <1/R^2>
 Q3Q = [0                C3*s1q.*sum(irq.*a2q)].';       % <(grad psi)^2/R^2>
 Q4Q = [0                C3*s1q.*sum( rq.*a2q)].';       % <(grad psi)^2>
 iqQ = [CA*rA                Cq./s2q          ].'.*iTQ; % 1/q
 if lX % special cases for diverted plasmas
  irX = 1/rX;
  Q0Q(end) = irX;
  Q1Q(end) = 0;
  Q2Q(end) = irX*irX;
  Q3Q(end) = 0;
  Q4Q(end) = 0;
  iqQ(end) = 0;
 end
end