! $Id: teqinit.f90,v 1.2 2007/07/23 16:00:58 meyer Exp $

MODULE teqlib_input

  USE sep_math

  IMPLICIT NONE

! Note units are cgs unless otherwise stated---USUALLY--will be cleaned up.

  INTEGER, PARAMETER :: MC=500,MLIM=50,MBD=500

  LOGICAL, TARGET :: &
       fix_bound=.FALSE.,&! if false boundary moves
       use_halo= .FALSE.,&! uses halo modes: inactive
       iter_bdry=.TRUE.   ! forces boundary to equal angle as polar1 converges
  INTEGER, TARGET :: &
       jqm,&
       lmax,&         ! equals mls for asymmetric and map for symmetric
       map=64,& 
       mls,&          ! number of points on surface = 2*map-1
       msrf=61,&      ! number of surfaces
       jm=33,&        ! dimension of radial mesh; must equal 2**n+1
       km=65,&        ! dimension of z mesh; must equal 2**n+1
       jmkm=33*65,&
       lsrf=-22,&     ! =11 , uniform; -22, stretched axis and edge [sin^2]
                      ! =jk , stretched as j power on axis and k power edge 
                      ! =-jk, stretched similar to positive jk, but uses 
                      ! sin's and cos's
       inv_flag=0,&   ! =0 uses polar1; =1 uses Esc
       inv_eq=0,&     ! =1 inverse equilibrium is used
       n4=6,&         ! 16 saves and uses all the bispline coefs for cps
       n6=6,&         ! 16 saves and uses all the bispline coefs for rhosq
       inv_k=0,&      ! =0, q;=1, FF';=2 <J.B>/<B-grad phi>;=3 <J.B>/<B.B>
                      ! as one input profile for the inverse solver; the
                      ! is P. The profiles are qsave, fsave, jtsave, jparsave
                      ! and psave
       inv_p=0,&      ! =-1 dpsi00, =1 plcm; =0 fwall
       entropy_flag=0,& ! zero uses pressure directly in adiabat and teqinv
                      ! negative uses entropy to calculate pressure nitt=1
                      ! (1st iteration) and then uses pressure
                      ! if positive uses entropy for all iterations
       filter_p=0,&   ! >0 smooths P using legendre polynomial fit with 
                      ! P'(msrf)=0; <0 smooths P using legendre polynomial
                      ! fit P'(msrf) floats. Always with the the derivative
                      ! wrt to sqrt(psibar)=0 on axis.
       filter_wp=0,&  ! same as filter_p for w(proportional to FF') except
                      ! =999 uses splider with w'=0 at edge
                      ! =-999 uses splider with w' at edge fixed
                      ! These two options modify in the vicinity of the edge
       one_pow=4,&    ! power of one~(F/F) in adiabat---incoming and new
                      ! for relaxation
       lelm=0,&       ! grid position where ELM occurs; if zero no ELM
       lflat=0,&      ! grid position where q-profile flattens to if <>0,
       mdpsi=0,&      ! if /= 0, psiscl applies dpsi00 at psrf(mdpsi)

       ipp=0,&        ! P profile selection selection:
                      !  ipp=1 : P' exp(-alfa(1)*x); x dimensionless flux
                      !  ipp=2 : P' exp(-alfa(1))*x-aap*exp(-alfa(1)*x)
                      !  ipp=3 : P (1-x^betp)^alfa
                      !  ipp=4 : P flat to x=app, then as ipp=3 beyond
                      !  ipp=5 : P=(1-xx^alfa);xx=x^betp; if betp>2 then
                      !  xx=((x+2-betp)/(3-betp))^2 and hollows
                      !  ipp=6 : j0=(1-xx)^aa if alfa>1 xx=x and aa=alfa...
                      !  else aa=1 and xx=x/(1-alfa*(1-x)/x*log(1-x))...
                      !  or xx=x^betp if betp<2 else xx=((x+2-betp)/(3-betp))^2
                      !  ipp=7 : Efit forms uses fefit pefit
                      !  ipp=999: spline fit; v, vp,vpp,vppp
       ipf=0,&        !  F^2-Fwall^2 profile options; same as ipp, but...
                      !  ipf>7 : j0=betp*(1.-xx)**aa+(1-betp)*(1-x)^(ipf-1)
                      !  if alfa>1 xx=x and aa=alfa
                      !  else aa=1 and xx=x/(1-(1-alfa)*(1-x)/x*log(1-x))
                      !  ipf=999; spline fit; w,wp,wpp,wppp
                      !  ipf=0 ;Spheromak(RFP);lambda profile with asph
                      !  ipf<0 ;Spheromak;external lambda profile with bsph
       ipj=0,&        !  flag for how Fand P is calculated...
                      !  ipj=0 : F' from profile form specified by ipf
                      !          P' from profile form specified by ipp
                      !          scalar constraint set by ipscl
                      !          if ipf<=0 lamda profile
                      !  ipj=1 : F,P from jtsave,psave (sets ipp/ipf=999)
                      !          scalar constraint set by ipscl
                      !  ipj=2 : uses ohmic profile, <J.B>/<B.grad phi> and
                      !          P' profile; use ipp and ipf per above
                      !          scalar constraint set by ipscl
                      !  ipj=3 : uses jparsave and psave: see ipscl
                      !  ipj=4 : F and P from qsave and psave: see ipscl
                      !  ipj=5 : F and P from qsave and psave with no scaling
       kedge=0,&      !  edge-current-model flag: ...=0 => no correction
                      !  =1 => LLL's model: current approximately 2nd-order
                      !  =2 => TBK's model: (1)+source distribution within
                      !  edge-cell to 2nd-order---not quite
                      !  USE default; othwer options needs work!!!
       ! Also see comments in source.f90 subroutine s_source
      
       ifluxCord=0,&  !  equals fluxCord
       nsym=2,&       ! =1 UP/DOWN symmetric; =2 asummetric
       nsymo=0,&
       kbfc=0,&
       ncf=0,&
       jm0p=0,&
       km0p=0,&
       nc0b=0,&
       nc0p=0,&
       nloop0p=0,&
       ncfo=0,&
       nsymco=0,&
       ngpo=0,&
       nfbc=0,&
       nmsc=0,&
       ircwt=3,&      ! -1 minimizes (dI/dz)^2;all coils and in sequence.
                      !  1 minimizes (cc-cc0)!(cc-cc0)
                      !  2 minimizes cc!cc
                      !  3 minimizes j**2=(cc/drc/dzc)^2
                      !  4 minimizes cc!pfim*!cc=I!L!I
                      !  5 minimizes B!B at the coils
                      !  6 minimizes (pfpsi-pfps0)^2;change in flux at coils
                      !  7 minimizes pfpsi!cc
                      !  8 minimizes fields at loops: see floop, rloop etc
                      !  9 reconstruction for SSPX (needs much work)
                      ! 11 minimizes (cc*rc)!(cc*rc)
                      ! svec will weight;
       lhalo=0,&      ! Surface where halo begins;=0 not used
       nprt59=0,&     ! =1 prints converging output
       npoly=8,&      ! number of polynomial in fit (filter_p, filter_wp)
       nsol,&
       nsep,&
       npri,&
       lflux,&
       jqd,&
       ncallsf=0,&
       bsph_flag=0,&  ! Spheromak option
                      ! If bsph_flag=1,2,3,4 bsph(bsph_flag) is used to force
                      ! the derivative of lamda to be continuous across the 
                      ! plasma boundary.
                      ! If bsph_flag=ij;ij=12,13,14,23,24,34 then bsphof i & j
                      ! used to force continuity of the lamda derivative and 
                      ! in addition forces the derivative to be zero at the 
                      ! geometric axis (R=0), The derivative across the private
                      ! flux region will be discontinuous if gsph is non zero.
       logunit,&
       nprob,&
       
       nplates        ! number of plates defining first wall

  REAL(rq), TARGET :: &
       npf=0,&        ! see epf
       npp=0,&        ! see epp
       m95=.95,&      ! boundary at the %m95 surface;if zero set to 0.95
       qcelm=0,&      ! coefficient of parabolic departure;>0 q=q*(1+qcelm*.)
                      ! <0 q=q/(1-qcelm*.)
       pcelm=0,&      ! coefficient of parabolic departure;>0 P=P(1+pcelm*.)
                      !<0 P=P/(1-pcelm*.)	
       scelm=0,&      ! coefficient of parabolic departure;>0 S=S(1+scelm*.)
                      !<0 S=S/(1-sccelm*.)
       qflat=0,&      ! q flattens inside this value; stores profile in qelm
       qrat=0,&       ! The flat portion of q = qflat+qrat*(qsave(1)-qflat)
       scflat=0,&     ! ssave multiplier
       betaj=0.5,&    ! FF' is proportional to (1/betaj -1)
       prsx=1.0001,&  ! normalization on pressure and FF'
       alfa(0:1)=0,&  ! alfa(i) is a profile parameter (see ipp) for
                      ! 0 element is FF'; 1 element1 is P'
       asph(4)=0,&    ! Spheromak lamda profile- confined region: ipf=0,-1
                      ! Spheromak FF' profile- confined region;   abs(ipf)=8
       bsph(4)=0,&    ! Spheromak lamda profile-outside region region;
                      ! ipf=-1,-8, In the code, bsph/(-psix/(psil-psix))**i
                      ! is used and i is the appropriate power:see nbsp
       aap=0,&        ! coefficient of subtraction (quartic if 1;ipp=2)
       betp(0:1)=0,&  ! betp(i) is a profile parameter (see ipp) for ith...
                      ! i=0 is FF';i=1 is P';
       pefit(5)=0,&   ! EFIT P' profiles
       fefit(5)=0,&   ! EFIT FF' profiles
       nasp=10._rq,&  ! power of flux for 4th asph
       nbsp=10._rq,&  ! power of flux for 4th bsph
       gsph=0,&       ! if not zero modifies private flux
       psph=0,&       ! value of poloidal flux [G cm^2/radian] where current
                      ! vanishes for spheromak in gun
       xsph=0,&       ! floor value of dimensionless flux for gsph option:
                      ! if too small not used.
       rzsph(2)=0,&   ! current vanishes at zero flux to the left of (1)
                      ! and above (2)
       epf=0,&        ! bump added to FF'(J0) ~epf* x**npf *(1.-x)
                      ! last piece if npp<0; normalized to epf
       epp=0,&        ! bump added to P ~x**npp *(1-x)**2 ;see epp
       rn=0,&         !  minimum value of r (mesh) [cm]
       rx=0,&         !  maximum value of r (mesh) [cm]
       zn=0,&         !  minimum value of z (mesh) [cm]
       zx=0,&         !  maximum value of z (mesh) [cm]: zn=-zx
       btor=0, &      ! external toroidal field at r=ro
       plcm=0, &      ! desired plasma current (used if ipscl=0) [MA]
       psix=0, &      ! psi at magnetic axis [Gauss cm**2/radian]
       psil=0,&       ! psi at plasma boundary; see ixpt [Gauss cm**2/radian]
       dphi00=0, &    ! desired dphi0 (toroidal flux) [Gauss cm**2/radian]
       dpsi00=0, &    ! desired dshi0 polroidal flux) [Gauss cm**2/radian]
       qmax=1.e3_rq,& ! maximum value of qaxis
                      ! see teq_inv comments-- for reverse shear
       inv_x=0,&      ! position in dimensionless flux where q is adjusted to
                      ! force FF'=0 at edge
       psilm,&        ! flux at limiter point [Gauss cm**2/radian]
       raxis,&        !  r at magnetic axis [cm]
       zaxis,&        !  z at magnetic axis [cm]
       splbdry=-111._rq,& 
                      ! boundary cond. for cubic spline:= 777. not-a-knot;..
                      ! =-111. extraps for 1st deriv;=-666. periodic
       alphac=.5+rq,& ! relaxation on plasma current update; =0 all new
       alpha=0,&      ! dynamic value
       gammac=0,&     ! relaxation on 2D mesh b.c.; =0 all new
       gamma=0,&      ! dynamic value
       deltac=.7_rq,& ! relaxation on scaling (see scl); =1 all new
       delta=0,&      ! dynamic value
       deltadc=.3_rq,&  ! relaxation in adiabat; =1 all new; if trub, try .3
       deltad,&       ! dynamic value
       sigmac=0,&     ! relaxation on psil; =0 all new
       sigma=0,&      !  relaxation on psil (dynamic value)
       tauc=.3_rq,&   ! relaxation on sawtooth model (aap); =0 all new...
                      ! sawtooth model not present at present
       thetac=0,&     ! psil = pxpt - thetac*( pxpt - psix )
       theta=0,&      ! dynamic value
       wvert=1._rq,&  ! ellipticity on axis;used for quasi-polar coords unless
                      ! defaulted to one
       ro,&           ! r-grid midpoint value, occurs at j=jm/2+1 [cm]
       dr,&           ! radial grid increment [cm]
       dz,&           ! radial grid increment [cm]
       hsrf=0.5,&     ! parameter used for stretching; use default value
       rxpr(2)=0,&    ! range in r for radial position of accepted xpoint; 
                      ! = 0 not used
       zxpr(2)=0,&    ! range in z for axial  position of accepted xpoint;!
                      ! =0 not used
       rapr(2)=0,&    ! range in r for radial position of accepted axis;
                      ! =0 not used
       zapr(2)=0,&    ! range in z for axial  position of accepted axis;
                      ! =0 not used
       rcur,&         !  r at current centroid [cm]
       zcur,&         !  z at current centroid [cm]
       dn_criterion=.0025_rq,&
       spt_angle=PI/8._rq,&
       plcm_gun,&     ! gun current at gun entrance [MA]
       shotTime,&
       f_gun0,&       ! desired f_gun
       epsb=1.e-8_rq,&! resb must be less than epsb
       epsj=1.e-8_rq  ! residj must be less than epsj

  REAL(rq), DIMENSION(:), ALLOCATABLE, TARGET ::  &
       qsave,&        ! qsrf for adiabat, computed in diag if ipj<3
       ssave,&        ! saved srsrf 
       psave,&        ! saved prsrf
       jtsave,&       ! saved jtsrf
       jparsave,&     ! saved jparsrf
       fsave,&        ! saved FF'
       psibin,&       ! dimensionless poloidal flux
       w,&            ! Spline at nodes F**2-F(msrf)**2)/(8*pi*dcpsi0*prsx)
       v,&            ! Spline at nodes P/(betaj*prsx)
       psi,&          ! total poloidal flux on 2D mesh
       r,&            ! mesh -r- coordinates
       z,&            ! mesh -z- coordinates
       rwl,&          ! radius of inner wall boundary on z-grid
       rwu,&          ! radius of outer wall boundary on z-grid
       rls,&          ! value of r along plasma boundary, input/output
       zls            ! value of z along plasma boundary, input/output

  INTEGER,  DIMENSION(:), ALLOCATABLE, TARGET :: &
       iloop,&        ! iloop=4 gaps,6 plasma current,7 coil currents (control)
                      ! iloop=4 uses rloop etc
       jwl,&          ! inner wall boundary on z-grid (j)
       jwu            ! outer wall boundary on z-grid (j)

  ! I/O Linkage [done] ...
  ! The input variables in this group may be used to change or assign
  ! names to the external disk files.

  CHARACTER(len=128),TARGET :: eqsum="eqsum" ! file name for summary output
  CHARACTER(len=20), TARGET :: aheader=" "   ! header for EQDSK a-file
  CHARACTER(len=48), TARGET :: gheader=" "   ! header for EQDSK g-file
  CHARACTER(len=40), TARGET :: theader=" "   ! header for EQDSK t-file
  CHARACTER(len=16), TARGET :: shotName = " ", site
  CHARACTER(len=80), TARGET :: note = " "
  CHARACTER(len=40), TARGET :: probid = " "
  CHARACTER(len=8),  TARGET :: rundate,runtime,codetime
  CHARACTER(len=10), TARGET :: codedate
  CHARACTER(len=64), TARGET :: logname
  CHARACTER(len=3),  TARGET :: pkgname

  ! teqPol

  INTEGER, TARGET ::&
       nht=100,&
       ntet=0,&
       npo=0,&
       ijob=0,&
       mesc=6,&
       ns1=0
  REAL(rq), TARGET ::&
       epsrk=1.e-6_rq,&
       epskrk=1.e-3_rq,&
       alfa0=.3_rq,&
       alfa1=.3_rq,&
       alfa2=.3_rq,&
       tpl,&
       anun=1_rq
  REAL(rq), DIMENSION(:,:), ALLOCATABLE, TARGET ::&
       rork
  LOGICAL, TARGET :: itimestep_converged=.TRUE.

  ! TeqGS_input

  REAL(rq), DIMENSION(:), ALLOCATABLE, TARGET :: &
       rbd,&
       ! radial coordinate of boundary points[cm]: ...
       ! curcal varies ic-currents to get psi(rbd,zbd)= psi@ 0-pressure surface
       ! (except if diverted & thetac not 0, psi(rbd,zbd)=pxpt)
       zbd,&
       ! vertical coordinate of boundary points[cm]
       tbd,&
       psibd,&
       rfbd,&
       ! fuzzy boundary(minimizes); see rbd
       zfbd,&
       ! fuzzy boundary; see zbd
       psiwfc,&
       ! used to get SN generator
       whtz,&
       ! used to get SN generator
       alfbd,&
       ! fuzzy boundary weighting added to the regular1zation (see ircwt)
       rloop,&
       ! radial position of meassuring loop;[cm]
       zloop,&
       ! radial position of meassuring loop;[cm]
       thloop,&
       ! loop orientation: Bpol=Br*sin(thloop)-Bz*cos(thloop)
       ! iloop=4 gaps, 6 plasma current, 7 coil currents
       sigloop,&
       ! error in measurement
       floop0,&
       ! desired flux or field at meassuring loop[cgs]
       cc,&
       !  coil currents[MA]
       rc,&
       !  mean radii of PF coils[m]
       zc,&
       !  mean z-locations[m]
       drc,&
       !  cross-section radial build[m]
       dzc,&
       !  cross-section axial height[m]
       ac,&
       ! Non-zero for Type 1 parallelogram coil section (a la EFIT) angle, ...
       ! measured from a radial line to the upper (or lower) edge [radians]
       ac2,&
       ! Non-zero for Type 2 parallelogram coil section
       svec,&
       ! Weighting for coil current regularization; defaulted to one
       rcase,&
       !  mean radii PF coil casings
       zcase,&
       !  mean -z- PF coil casings
       drcase,&
       !  delta-r PF coil casings
       dzcase,&
       !  delta-z PF coil casings
       rhc,&
       !  resisitivity
       rextc,&
       ! external resistance in coils
       lextc,&
       ! external inductance in coils
       pfps0,&
       !  desired flux at coil see iflxc=1
       cc0,&
       ! desired current at coils see ircwt=1 which minimizes error
       rxc,&
       rlim,&
       zlim,&
       dlim
  
  REAL(rq), DIMENSION(:,:), ALLOCATABLE, TARGET :: &
       gdc,&
       !  current grading ratio
       rplate,&
       !  r-coordinates of each plate defining 1st wall
       zplate
  !  z-coordinates of each plate defining 1st wall
  
  INTEGER, DIMENSION(:), ALLOCATABLE, TARGET :: &
       nrc,&
       !  no. of filaments across drc
       nzc,&
       !  no. of filaments across dzc
       ic,&
       ! Current circuit index...i.e. ic(3)=1 and ic(5)=1 keeps the current
       ! ratio fixed
       ict,&
       ! =1 for Series; =0 for Parallel for the ic circuits
       ix,&
       ! Circuit for flux at coils
       ! ix(i) = j makes the flux at cc(i) the jth circuit, note circuit number
       ! starts at jbdcir, the number of curcal constraints
       iferro
       ! = 1 if coil is ferromagnetic
  
  CHARACTER(len=8), DIMENSION(:), ALLOCATABLE, TARGET ::&
       pfid
  
  REAL(rq), TARGET :: &
       scl=1,&
       psil00=0,&
       dt=0,&
       !  time increment [sec]
       thetat=0.5_rq,&
       !  2nd order accurate time stepping
       ccoil,&
       !  initial guess for coil currents [MA]
       zocoil,&
       !  Z0 for analytic coil generator [cm]
       rocoil,&
       !  R0 for analytic coil generator [cm]
       rbcoil,&
       !  a for analytic coil generator [cm]
       elcoil,&
       !  kappa for analytic coil generator
       dcoil,&
       !  delta for analytic coil generator
       qcoil,&
       !  q-bean for anal. coil generator
       cnorm,&
       !  internal normalization=0.5abs(plcm)
       crdn=4000._rq,&
       !  J for sizing coil sect. in plots [A/cm^2]
       acmin=10._rq,&
       !O min. coil section dimension
       magfac=0 ,&
       ! magnetization factor (saturated magnetization (T) in ferromagnetic ...
       ! coil, and switch for existence of any ferromagnetic coils) [T]
       bsat=8.864e-2_rq,&
       ! magnetic-field magnitude (T) at which magnetization is half saturated
       ! for Incoloy Alloy 908 [T]
       dsurf=.1_rq,&
       ! width of magnetization surface current [cm]
       almim,&
       ! multiplier of constraint when added to the minimization
       geomo,&
       ! stored value of coil geometry factor; used to decide whether
       ! Greens' functions need to be recalculated
       pfjx,&
       !  maximum value of pfjf(1,...,nfjx)
       pfbx,&
       !  maximum value of pfbc(1,...,nfjx) [T]
       delc,&
       !  grid size (coil B-fields)
       pftd=10.0_rq,&
       !  dump time constant (CICC) [s]
       pfahs=500.0_rq,&
       !  allow. hoop stress conduit (CICC) [MPa]
       dfac=10.0_rq,&
       !  EFFI distance factor in coils.f
       dtofst=0,&
       ! theta offset
       finit2=1.0_rq,&
       ! used if initflx,c=2; psil encloses finit2*(p_xpt-p_ax)
       el=2.0_rq,&
       !  zx=el*rb*(jm/2) / ((jm/2)+1-liml) !also /geo/!
       elx=1.6_rq,&
       ! z-length for psi ic (Strickler's initflx=0 option)
       bbdu,&
       !?
       bbdl,&
       !?
       dbdu=0,&
       ! upper triangularity, analytic bdry model
       dbdl=0,&
       ! lower triangularity, analytic bdry model
       ebdu=0,&
       ! upper elongation, analytic boundary model
       ebdl=0,&
       ! lower elongation, analytic boundary model
       queu=0,&
       ! upper beaning, analytic boundary model
       quel=0,&
       ! lower beaning, analytic boundary model
       alpcoilc=0.,&
       ! PF coil update relaxation; =0 all new
       alpsphc=0.,&
       ! asph/bsph update relaxation; =0 all new
       alpcoil,&
       !
       alpsph,&
       !
       vltf,&
       ! if cejima=0 & vltf not 0, then VS fixed to vltf.   ... [Vs]
       ! if cejima not 0 then prebiased VS fixed using vltf: see cejima.
       rfix=0.0,&
       !  if=0, rfix=rb; used if ibdry>0 to set rbd array [cm]
       psires0,&
       ! desired average plasma poloidal flux [Wb]
       raxis0,&
       ! desired raxis [cm]
       zaxis0,&
       ! desired zaxis [cm]
       rxpt0,&
       ! desired rxpt [cm]
       zxpt0,&
       ! desired zxpt [cm]
       cejima,&
       ! psires=vltf-0.4*pi*cejima*plcm*ro/100
       plcx,&
       ! forces psix to plcx in curcal
       rl,&
       !  distances between separatrices fixed in curcal... [cm]
       !  irl=0; rl relative flux between separatrices (pxpu-pxpl)/dpsi0
       !  irl=+(-) rl>0 then distance at outer mid-plane, upper(lower);
       !           rl<0                  inner mod_plane
       rb,&
       !  j=liml is at r=ro-rb [cm]
       betx=0.1_rq
  ! initial estimate of maximum beta (%)
  INTEGER, TARGET :: &
       nbd,&
       ! no. pts at which psi is to be = psil...
       !  ic-currents are varied to achieve this. see also rbd,zbd
       nfbd,&
       ! no. fuzzy points on boundary, see nbd
       ! number upper boundary points (asymmetric)
       nbdl,&
       ! number lower boundary points (asymmetric)
       nbdu,&
       ! number upper boundary points (asymmetric)
       lgrn=0,&
       ! =1 never recalculates Green functions
       kgreenc=1,&
       !  Green functions flag for gc and gp...
       !  kgreenc=0 computes when used; =1 computed at EQUILA and stores
       ncplot=0,&
       !  number of coils entered on plots usually the PFcoils only
       nc=0,&
       !  total number of coils PF coils plus passive coils representing walls
       nloop,&
       ! number of flux loops
       nsymc=2,&
       !  PFC symmetry flag: 1/2=sym/asym
       limw=0,&
       !
       lcal,&
       ! tells curcal to recalculate inverses (gmat(,,2),gmat(,,3)) if not -1
       liml=-1,&
       !  if =-1 uses rn, rx and zx as input and ro is computed; zn=-zx
       nitr,&
       ! EQUILC (finds ext & plasma currents for fixed bc) loop index
       ierr1=1,&
       ! =1 uses new crj + clj  in RESID
       nlim,&
       !
       lsph=0,&
       ! if=0 nothing; if=1 minimizes loops pf f_gun; if=2 forces current=plcm
       nsph,&
       ! number of asph's used for reconstruction;
       iflxc=0,&
       ! =1 runs circuit equations nbd=0!! etc. ic sets circuits
       ixpt,&
       ! flag for setting psil, the 0-pressure flux...
       ! rbd,zbd and rfbd,zfbd on separatrix
       ixp,&
       ! dynamic value
       ixpo=1,&
       ! nonzero sets ixp=ixpt for first PSILMS call
       ncsym,&
       !
       irl=0,&
       !  see rl
       jxp=0,&
       ! deprecated
       kxp=0,&
       ! if not zero forces X-point to (rxp,zxp)
       jaxis=0,&
       ! deprecated
       kaxis=0,&
       ! if not zero forces O-point to (raxis0,zaxis0); problematic
       ! since requires user ingenuity to avoid over-constraining
       ! can also be another X-point
       keqic=0,&
       ! flag for package eq initial values...
       !  for cc, prsx, and psi; if in ceq,meq also controls rbd,zbd,x0
       !  =0 do nothing; =2 use stored values for all EQUILA calls;
       !  =1(3) like =2 for 1st FCNS call, & like =0 thereafter
       !  1(3) uses "00"("01") stored values
       ifscl=0,&
       !  >1 scales F in PSISCL (see ipscl); =2 scales fwall
       ipscl=0,&
       !  scale Grad-Shafranov: =0 fix current (plcm), 
       !  =1  fix enclosed poloidal flux(dpsi00) ,
       !  =-1 no scale
       !  If ipj=3,4 (jparsave, qsave is input) and ipscl=-1, then
       !  inv_p=0 constrains to fwall,inv_p=-1 constrains to dpsi00, 
       !  inv_p=1 constrains to plcm
       !  If ipscl <>-1 (not recommended) uses the ipscl options

       ibdry=1,&
       !  option flag to set rbd,zbd arrays (pressure=0 pts)...
       ! =0 you set r,zbd; =1 for sym analytic; =2 for asym analytic
       ni=1,&
       ! # of internal iteration for each external iteration to convergence
       nl=100,&
       ! maximum number of iterations to equilblibrium
       initflx=0,&
       ! flux (r,z) initial condition option flag, in INITSI...
       !  =0 Strickler's parabolic;
       !  =1 models plasma as filaments with right current;
       !  =2 sym, triang=0, elong=ebdu at psi-psix=psil-psix,
       !  encloses finit2*(pxpt-psix);
       !  =3 asymmetric, single X-point enclosing psil-psix
       !  =4 psi00 (from last ksave)
       ksave=2,&
       ! flag to save flux & coil-current values; =0 don't save; ...
       ! =1 save start conditions for next equilibrium calc depends on keqic;
       ! =2 save after last equilibrium (from next EQ, CEQ, or MEQ run).
       ! ksave is 0'd after the save, stores into '00' arrays, has only 1 level
       ! =0 turns off lasteq=1 after HYBRD return (no plots, eqdsk)
       ! logic flag for DIAGNQ, GRAFIK; computed in CEQ, used in EQ ...
       ! If you're in package eq & want saved 01's for keqic=3
       ! preserved, set lasteq=1. See also lasteqsav.
       lasteq,&
       lasteqsav,&
       lop0,&
       nbs,&
       int_flag=0,&
       ! if =1 internal coils are treated as coils; ...
       ! GS solver solves for plasma flux and the external flux
       ! from Green's functions is added back in;
       ! if =0 internal coils are distributed and added to the source;
       ! GS solver solves for total flux: and coil currents inside
       ! computational grid, which are put in clj,  are added to the source
       n_gauss_even=4,&
       ! order for even-order quadrature
       n_gauss_odd=7,&
       ! order for odd-order quadrature
       ! The following parameters can each be either even or odd. The
       ! only restriction is that they be different, and not both odd.
       ! The total number of integrand evaluations required to compute
       ! the self-inductance is n_gauss_even*n_gauss_odd for rectangular
       ! and type 1 coils, 6*n_gauss_even*n_gauss_odd for type 2 coils.
       gauss_check=0,&
       ! set <> 0 to check Guassian quadrature, =1 to get certain
       ! debugging readout.
       nfil=1,&
       !  min. no. filaments across coil
       ngp=5,&
       ! min. no.  grid pts (field calc)
       ! ngp=1 when there are ferromagnetic coils
       nfjx=0,&
       !  no. coils to scan for pfjx
       ncase=0,&
       !  number of PF coil casings
       nsegs=10,&
       dbg=-1,&
       ncoil=0
  !  if ncf=0, use this for nc
  LOGICAL, TARGET :: &
       crj_flag=.FALSE.,&
       ! If true calculates current outside the plasma when inverse equlibrium
       ! used for plasma
       use_ellip=.FALSE.
  ! If true uses the complete elliptic integrals in Mutual.
  
CONTAINS

  SUBROUTINE teq_input

!    use teqlib_input
    USE teq_mod
    USE sep_interp, only : i_dbg
    USE sep_separatrix, only : s_n4
    USE teqSubs_mod,  only : teq_allocate, t_stretch

    s_n4        => n4
    i_dbg       => dbg
    t_jm        => jm
    t_km        => km
    t_jmkm      => jmkm
    t_mls       => mls
    t_map       => map
    t_msrf      => msrf
    t_n6        => n6
    t_n4        => n4
    t_lsrf      => lsrf
    t_lelm      => lelm
    t_lflat     => lflat
    t_ifluxcord => ifluxcord 
    t_nsym      => nsym
    t_nsymo     => nsymo
    t_entropy_flag=> entropy_flag
    t_filter_wp => filter_wp
    t_filter_p  => filter_p
    t_one_pow   => one_pow
    t_mdpsi     => mdpsi
    t_btor      => btor
    t_plcm      => plcm
    t_dphi00    => dphi00
    t_dpsi00    => dpsi00
    t_psilm     => psilm
    t_raxis     => raxis
    t_zaxis     => zaxis
    t_psix      => psix
    t_psil      => psil
    t_betaj     => betaj
    t_psilm     => psilm
    t_raxis     => raxis
    t_zaxis     => zaxis
    t_psix      => psix
    t_psil      => psil
    t_splbdry   => splbdry
    t_betaj     => betaj
    t_qcelm     => qcelm
    t_pcelm     => pcelm
    t_scelm     => scelm
    t_qflat     => qflat
    t_qrat      => qrat
    t_scflat    => scflat
    t_prsx      => prsx
    t_aap       => aap
    t_nasp      => nasp
    t_nbsp      => nbsp
    t_gsph      => gsph
    t_psph      => psph
    t_xsph      => xsph
    t_epf       => epf
    t_epp       => epp
    t_npf       => npf
    t_npp       => npp
    t_ipp       => ipp
    t_ipf       => ipf
    t_ipj       => ipj
    t_kedge     => kedge
    t_alphac    => alphac
    t_alpha     => alpha
    t_gammac    => gammac
    t_deltac    => deltac
    t_delta     => delta
    t_deltadc   => deltadc
    t_deltad    => deltad
    t_sigmac    => sigmac
    t_sigma     => sigma
    t_tauc      => tauc
    t_thetac    => thetac
    t_theta     => theta
    t_wvert     => wvert
    t_ro        => ro
    t_dr        => dr
    t_dz        => dz
    t_hsrf      => hsrf
    t_rcur      => rcur
    t_zcur      => zcur
    t_f_gun0    => f_gun0
    t_plcm_gun  => plcm_gun
    t_ircwt     => ircwt
    t_bsph_flag => bsph_flag
    t_inv_eq    => inv_eq
    t_lhalo     => lhalo
    t_use_halo  => use_halo
    t_fix_bound => fix_bound
    t_lmax      => lmax
    t_alfa      => alfa
    t_betp      => betp
    t_asph      => asph
    t_bsph      => bsph
    t_pefit     => pefit
    t_fefit     => fefit
    t_rzsph     => rzsph
    t_rxpr      => rxpr
    t_zxpr      => zxpr
    t_rapr      => rapr
    t_zapr      => zapr
    t_nprt59    => nprt59
    t_npoly     => npoly
    t_logunit   => logunit
    t_rn        => rn
    t_rx        => rx
    t_zn        => zn
    t_zx        => zx
    t_m95       => m95
    t_qsave     => qsave
    t_jtsave    => jtsave
    t_jparsave  => jparsave
    t_ssave     => ssave
    t_psave     => psave
    t_fsave     => fsave
    t_w         => w
    t_v         => v
    t_psi       => psi
    t_r         => r
    t_z         => z
    t_rwl       => rwl
    t_rwu       => rwu
    t_jwl       => jwl
    t_jwu       => jwu
    t_rls       => rls
    t_zls       => zls
    t_rplate    => rplate
    t_zplate    => zplate
    t_dn_criterion=> dn_criterion
    t_nplates   => nplates
    t_nsegs     => nsegs
    t_spt_angle => spt_angle
    t_rundate   => rundate
    t_runtime   => runtime
    t_codedate  => codedate
    t_codetime  => codetime
    t_aheader   => aheader
    t_gheader   => gheader
    t_theader   => theader
    t_logname   => logname
    t_probid    => probid
    t_note      => note
    t_nprob     => nprob
    t_shotName  => shotName
    t_shotTime  => shotTime
    t_site      => site
    t_pkgname   => pkgname
    t_ncallsf   => ncallsf
    
  END SUBROUTINE teq_input

  SUBROUTINE teq_input_allocate

    integer :: sz

    sz = 0; if (allocated(qsave)) sz = size(qsave)
    IF (sz/=msrf) THEN
       IF (ALLOCATED(qsave)) DEALLOCATE(qsave,jtsave,jparsave,fsave,ssave,w,v,&
            psave,psibin)
       ALLOCATE(jtsave(msrf),qsave(msrf),fsave(msrf),ssave(msrf),psave(msrf),&
            jparsave(msrf),w(msrf),v(msrf),psibin(msrf))
       qsave=0;psave=0;fsave=0;psave=0;ssave=0;jtsave=0;jparsave=0;w=0;v=0
       psibin=0
    END IF
    sz = 0; if (allocated(rls)) sz = size(rls)
    IF (sz/=mls) THEN
       IF(ALLOCATED(rls)) DEALLOCATE(rls,zls)
       ALLOCATE(rls(mls),zls(mls))
    END IF
    sz = 0; if (allocated(jwl)) sz = size(jwl)
    IF (sz/=km) THEN
       IF(ALLOCATED(jwl)) DEALLOCATE(jwl,jwu,rwl,rwu)
       ALLOCATE(jwl(km),jwu(km),rwl(km),rwu(km))
       jwl=0;jwu=0;rwl=0;rwu=0
    END IF
    sz = 0; if (allocated(psi)) sz = size(psi)
    IF (sz/=jmkm) THEN
       IF(ALLOCATED(r)) DEALLOCATE(r,z,psi)
       ALLOCATE(r(jm),z(km),psi(jmkm))
       r=0;z=0;psi=0
    END IF
    IF(.NOT.ALLOCATED(rbd)) THEN
       ALLOCATE(rbd(MBD),zbd(MBD))
    END IF
    IF(ALLOCATED(tbd)) THEN
       IF(SIZE(tbd)/=nbd) DEALLOCATE(tbd,whtz,psiwfc,psibd)
    END IF
    IF(.NOT.ALLOCATED(tbd)) THEN
       ALLOCATE(whtz(nbd),psiwfc(nbd),tbd(nbd),psibd(nbd))
       psibd=0;tbd=0;whtz=0;psiwfc=0
    END IF
    IF(.NOT.ALLOCATED(rfbd)) THEN
       ALLOCATE(rfbd(MBD),zfbd(MBD),alfbd(MBD))
       alfbd=100;rfbd=0;zfbd=0
    END IF
    IF(.NOT.ALLOCATED(rlim)) THEN
       ALLOCATE(rlim(0:MLIM),zlim(0:MLIM),dlim(0:MLIM))
    END IF
    sz = 0; if (allocated(rloop)) sz = size(rloop)
    IF (sz/=nloop .OR. .NOT.ALLOCATED(rloop)) THEN
       IF(ALLOCATED(rloop)) DEALLOCATE(rloop,zloop,thloop,floop0,iloop,sigloop)
       ALLOCATE(rloop(nloop),zloop(nloop),thloop(nloop),floop0(nloop),&
            iloop(nloop),sigloop(nloop))
       rloop=0;zloop=0;thloop=0;iloop=0;sigloop=1
    END IF
    IF(.NOT.ALLOCATED(cc)) THEN
       ALLOCATE(cc(MC),rc(MC),zc(MC),rhc(MC),drc(MC),dzc(MC),rxc(MC),cc0(MC),&
            ac(MC),ac2(MC),svec(MC),pfps0(MC),ic(MC),ix(MC),nrc(MC),nzc(MC),&
            pfid(MC),lextc(MC),iferro(MC),ict(MC),rcase(MC),zcase(MC),&
            drcase(MC),dzcase(MC),rextc(MC))
       cc=0;rc=0;zc=0;drc=0;dzc=0;rxc=0;cc0=0;ac=0;ac2=0;svec=1;pfps0=0
       ic=0;ix=0;nrc=0;nzc=0;pfid=" ";lextc=0;iferro=0;ict=0;rcase=0;zcase=0
       drcase=0;dzcase=0;rextc=0
    END IF
    sz = 0; if (allocated(gdc)) sz = SIZE(gdc,1)
    IF(ALLOCATED(gdc) .AND. sz/=nc) THEN
       DEALLOCATE(gdc)
    END IF
    IF(.NOT.ALLOCATED(gdc)) THEN
       ALLOCATE(gdc(nc,6));gdc=0
    END IF
    sz = 0; if (allocated(rplate)) sz = size(rplate,1)
    IF (sz/=nplates .OR. .NOT.ALLOCATED(rplate)) THEN
       IF(ALLOCATED(rplate)) DEALLOCATE(rplate,zplate)
       ALLOCATE(rplate(nplates,2),zplate(nplates,2))
       rplate=0;zplate=0
    END IF
    sz = 0; if (allocated(rork)) sz = size(rork,1) * size(rork,2)
    IF (sz/=msrf*mls) THEN
       IF(ALLOCATED(rork)) DEALLOCATE(rork)
       ALLOCATE(rork(msrf,mls))
       rork=0
    END IF
  END SUBROUTINE teq_input_allocate
 
END MODULE teqlib_input

MODULE teqlib_output

  USE sep_math

  ! teqPol

  REAL(rq), DIMENSION(:), POINTER :: &
       qrk,&
       jrk,&
       srk,&
       trk,&
       vrk,&
       crk,&
       rrk,& ! current centroid, r^2
       zrk,& ! current centroid, z
       f,&
       pff,&
       p,&
       pp
  REAL(rq), DIMENSION(:,:), POINTER :: &
       aj
  
  REAL(rq), DIMENSION(:,:,:), POINTER :: &
       rhosq ! transpose((rlsd(,,1)-raxis)**2+((zlsd(,,1)-zaxis)/wvert)**2)
  
  !teq
  
  REAL(rq), DIMENSION(:), POINTER :: &
       rm,&
       zm,&
       crj,&
       br,&
       bz,&
       bp,&
       bt,&
       bmod,&
       pvec,&
       fldind,&
       ! Prime means derivative wrt the poloidal flux divided by 2pi
       frsrf,&     ! F
       fpsrf,&     ! F'
       qsrf,&      ! q
       rsqbp,&
       jtsrf,&     ! <J.B>/<B-grad phi>
       jparsrf,&   ! <J.B>/<B.B>
       susrf,&     ! Area enclosed by flux surface
       cusrf,&     ! Mu0*I(psi)
       vpsrf,&     ! V'
       srsrf,&
       prsrf,&     ! P
       pdsrf,&     ! P'
       rsrf,&      ! Major radius of flux surface 
       asrf,&      ! Minor radius of flux surface  
       volsrf,&    ! Volume enclosed by flux surface
       c1srf,&
       c4srf,&
       c5srf,&
       esrf,&      ! Elongation
       tsrf,&      ! Triangularity
       tlsrf,&     ! Triangularity(lower)
       tusrf,&     ! Triangularity(upper)
       r2bzrf,&
       r4bp2rf,&
       rsqrf,&     ! <R**2>
       bpsrf,&     ! <Bpol>
       bsqrf,&     ! <B.B>
       rsqirf,&    ! <1/R**2>
       alsrf,&     ! Perimeter of flux surface
       risrf,&     ! <1/R>
       fttcsrf,&   ! Effective trapped to circulating
       qh,&        ! Integral q * d(psibar)
       psibar,&    ! Dimensionless poloidal flux (see lsrf), independent coord
       psidbar,&   ! Derivative of psibar wrt to the integer (1,msrf)
       phibar,&    ! Dimensional toroidal flux
       psiinv,&    
       psidinv,&
       rhosrf,&
       psrf,&      ! Poloidal flux/2/pi
       vptor,&     ! V'/q
       tswpts,&    ! Uniform angle coord (1-2pi)
       brwpts,&
       bzwpts,&
       psiw,&      ! External poloidal flux (R-Z grid)
       clj,&
       rlimw,&     ! Limiter coord
       zlimw,&     ! Limiter coord
       tlimw,&
       plimw,&
       rstkpt,&
       zstkpt,&
       dstkpt,&
       bstkpt,&
       psi00,&
       psi01,&
       vltsnd,&   ! Flux linkage(curren weighted,magnetic axis,geometric axis)
       li,&       ! Internal induction, standard definitions
       betap,&    ! beta poloidal, standard definitions
       betaps,&
       lam,&
       rspt,&
       zspt,&
       dspt,&
       bspt,&
       rpts,&
       wp,wpp,wppp,& ! Spline derivatives: see w
       vp,vpp,vppp,& ! Spline derivatives: see v
       zpts        
  
  REAL(rq), DIMENSION(:,:), POINTER :: &
       plsolo,&
       plsoli,&
       tlsolo,&
       tlsoli
  
  REAL(rq), DIMENSION(:,:,:), POINTER :: &
       rlsd,&    ! R,dR/dtheta,dR/dpsibar,Bpol     on inverse coordinates
       zlsd      ! Z,dZ/dtheta,dZ/dpsibar,Jacobian on inverse coordinates
  
  REAL(rq), POINTER :: &
       rxpf,&
       zxpf,&
       rxpt,&    ! R at X_point
       zxpt,&    ! Z at X_point
       pxpt,&    ! Value of psi at X_point
       psih,&
       dpsi0,&   ! delta psi(poloidal flux) across plasma
       dphi0,&   ! delta phi(toroidal flux) across plasma
       fwall,&   ! vacuum F=ro*btor(ro)
       plc,&     ! plasma current amps/10
       lamda_gun,&
       r_gun,&
       z_gun,&
       f_gun,&
       residj,&  ! Residual error of equilibrium solver
       betae,&
       betat,&
       flxln,&
       absflx,&
       psisep,&
       psipls,&
       xindf,&
       slfnd,&   ! plasma self inductance uH
       xlfnd,&
       volume,&  ! plasma volume
       surf,&    ! plasma cross sectional area
       ctroy,&   ! Troyon coeff
       qmerc,&
       placur,&
       helicity,&! Helicity of plasma (wb**2)
       elongn,&
       trianu,&
       trianl,&
       trian,&
       t95,&
       tl95,&
       tu95,&
       trider,&
       f95,&
       p95,&
       psi95,&
       e95,&
       q95,&
       qmin,&
       rhomin,&
       qstar,&  ! Cylindrical q
       aspct,&
       wpf,&    ! PF coils stored energy (GJ)
       wpt,&
       ccdir,&  ! average current per unit length of PFCoil system (MA/m)
       al,&
       bpsqva,&
       presva,&
       pressa,&
       betal, &
       bpolsa,&
       skew,  & ! Orientation of axis at magnetic axis; 0=up/down symmetric
       dsep,  & ! Distance bewtween separatrices at outboard midplane
       dsip,  & ! Distance bewtween separatrices at inboard midplane
       rcntr, & ! Major radius of plasma at plasma mid-plane 
       rbore    ! Minor radius of plasma at plasma mid-plane 
  
  INTEGER, POINTER ::&
       nspt,&   ! number of strike points
       nitt,&   ! number of current iterations in GS 
       nstkpts  ! number of candidaye strike points(could be redundant)
  
  INTEGER, DIMENSION(:), POINTER ::&
       lstkpt   ! plate number containing strike points
  
  ! teqGS
  
  INTEGER, POINTER ::&
       ncircuit,&
       jbdcir,& ! total number of constraints in gs_curcal
       ncrmx,&  ! maximum nrc
       nczmx,&  ! maximum nzc
       ifjx,&   ! index of coil prodcing pfjx
       ifbx,&   ! index of coil prodcing pfbx
       ncs,&    ! number analytic coil filamants
       ngroup   ! number of current circuits: see ic
  
  REAL(rq), DIMENSION(:), POINTER ::&
       ccf,&    ! variables ending in f desribe filaments: see cc,  etc
       rcf,&
       zcf,&
       drcf,&
       dzcf,&
       ccfd,&   ! ignore
       ccmf,&   ! ignore
       cscl,&   ! ignore
       ccls,&   ! group currents
       cscl00,& ! ignore
       cscl01,& ! ignore
       cclsr,&  ! ignore
       cmplas,& ! mutual inductance between coil and plasma
       pfjp,&   ! pack current density
       pfjc,&   ! critical (Miller) current density MA/m^2
       pfjf,&   ! ratio of actual/critical current
       pfbc,&   ! conductor B-field
       pfbi,&   ! max B inner coil surface
       pfbo,&   ! max B outer coil surface
       pfbr,&   ! mean radial B-field T
       pfbz,&   ! mean axial  B-field T
       pfhs,&   ! average hoop stress MPa
       pfms,&   ! maximun hoop stress MPa
       pffr,&   ! radial force MN
       pffz,&   ! axial force MN
       pfil,&   ! current length product MA*m
       pfse,&   ! storage energy per coil MJ
       pfe0,&   ! stored self energy per coil
       pfpsi,&  ! Poloidal flux at coils (Wb)
       vlts2D,& ! Flux linkage per coil (VS)
       pfpci,&  ! average Poloidal flux per group: not connected
       pfpc0,&  ! average Poloidal flux per group (desired ?)
       rcg,&    ! weighted average radius of coil group M
       zcg,&    ! weighted average height of coil group M
       gloop,&  ! loop output: see iloop, rloop, zloop
       br0p,&   ! radial field at the coil center not connected G
       bz0p,&   ! axial  field at the coil center not connected G
       aac,&    ! ignore
       rcs,&    ! ignore
       zcs,&    ! ignore
       ths      ! ignore
  
  INTEGER, DIMENSION(:), POINTER ::&
       p_in,&   ! flags coil number inside mesh ignore
       jnt,&    ! ignore
       knt,&    ! ignore
       icc,&    ! ignore
       loopm,&  ! ignore
       loop0,&  ! ignore
       icf,&    ! ignore
       icnf     ! ignore
  
  REAL(rq), DIMENSION(:,:), POINTER ::&
       pfim,&   ! induction matrix coil to coil uH
       pbim,&   ! Bpol matrix
       floop,&  ! user variable see iloop, gloop
       ploop,&  ! flux and first derivs at loops see iloop, rloop, zloop
       rc4,&    ! corners of the coils, used for graphics M
       zc4      ! "
  
  REAL(rq), DIMENSION(:,:,:), POINTER ::&
       gc,&     ! Green's function between coil and 2D mesh
       gfbr,&   ! Green's function for Br between coil and 2D mesh
       gfbz,&   ! Green's function for Bz between coil and 2D mesh
       gp,&     ! Green's function between 2D mesh mesh boundary
       plim,&   ! spheromak option
       gpl      ! spheromak option
  
  REAL(rq), POINTER ::&
       psires,& ! average poloidal flux across plasma
       rbin,&   ! radius of inner-most boundary point
       rbout,&  ! radius of outer-most boundary point
       pfcse,&  ! total store energy with in the coils MJ, from the coils
       pftse,&  ! total store energy with in the coils MJ 
       pfcsi,&  ! total magnitude of the coil currents MA
       pfcil,&  ! total magnitude of the coil current-lengths MA*m
       error,&  ! residual on psi
       resb,&   ! residual on boundary
       resid,&  ! residual between rhs and lhs of GS equation
       prsx00,& ! ignore
       prsx01,& ! ignore
       rlimm,&  ! equals rlim(0)
       zlimm    ! equals 

END MODULE teqlib_output

module teqinit

contains

  SUBROUTINE teq_output

    use teqlib_output
    USE teq_output_mod
    USE teq_mod, only : t_c1srf,t_c4srf,t_c5srf,t_r2bzrf,t_r4bp2rf,t_rm,t_zm,&
         t_clj,t_psi00,t_psi01
    USE source_mod, only : t_wp,t_wpp,t_wppp,t_vp,t_vpp,t_vppp
    USE sep_separatrix, only : s_skew,s_dsep,s_dsip,s_rbore,s_rcntr

    IMPLICIT NONE
    
    rm        => t_rm
    zm        => t_zm
    crj       => t_crj
    pvec      => t_pvec
    br        => t_br
    bz        => t_bz
    bp        => t_bp
    bt        => t_bt
    bmod      => t_bmod
    fldind    => t_fldind
    frsrf     => t_frsrf
    fpsrf     => t_fpsrf
    qsrf      => t_qsrf
    rsqbp     => t_rsqbp
    jtsrf     => t_jtsrf
    jparsrf   => t_jparsrf
    susrf     => t_susrf
    cusrf     => t_cusrf
    vpsrf     => t_vpsrf
    srsrf     => t_srsrf
    prsrf     => t_prsrf
    pdsrf     => t_pdsrf
    rsrf      => t_rsrf
    asrf      => t_asrf
    volsrf    => t_volsrf
    c1srf     => t_c1srf
    c4srf     => t_c4srf
    c5srf     => t_c5srf
    esrf      => t_esrf
    tsrf      => t_tsrf
    tlsrf     => t_tlsrf
    tusrf     => t_tusrf
    r2bzrf    => t_r2bzrf
    r4bp2rf   => t_r4bp2rf
    rsqrf     => t_rsqrf
    bpsrf     => t_bpsrf
    bsqrf     => t_bsqrf
    rsqirf    => t_rsqirf
    alsrf     => t_alsrf
    risrf     => t_risrf
    fttcsrf   => t_fttcsrf
    qh        => t_qh
    psibar    => t_psibar
    psidbar   => t_psidbar
    phibar    => t_phibar
    psiinv    => t_psiinv
    psidinv   => t_psidinv
    rhosrf    => t_rhosrf
    psrf      => t_psrf
    vptor     => t_vptor
    tswpts    => t_tswpts
    brwpts    => t_brwpts
    bzwpts    => t_bzwpts
    psiw      => t_psiw
    clj       => t_clj
    rlimw     => t_rlimw
    zlimw     => t_zlimw
    tlimw     => t_tlimw
    plimw     => t_plimw
    wp        => t_wp
    wpp       => t_wpp
    wppp      => t_wppp
    vp        => t_vp
    vpp       => t_vpp
    vppp      => t_vppp
    
    rlsd      => t_rlsd
    zlsd      => t_zlsd
    rstkpt    => t_rstkpt
    zstkpt    => t_zstkpt
    dstkpt    => t_dstkpt
    bstkpt    => t_bstkpt
    lstkpt    => t_lstkpt
    
    rxpf      => t_rxpf
    zxpf      => t_zxpf
    rxpt      => t_rxpt
    zxpt      => t_zxpt
    pxpt      => t_pxpt
    psih      => t_psih
    dpsi0     => t_dpsi0
    dphi0     => t_dphi0
    fwall     => t_fwall
    plc       => t_plc
    nitt      => t_nitt
    lamda_gun => t_lamdagun
    r_gun     => t_rgun
    z_gun     => t_zgun
    f_gun     => t_fgun
    residj    => t_residj
    psi00     => t_psi00
    psi01     => t_psi01
    vltsnd    => t_vltsnd
    li        => t_li
    betap     => t_betap
    betaps    => t_betaps
    lam       => t_lam
    betae     => t_betae
    betat     => t_betat
    flxln     => t_flxln
    absflx    => t_absflx
    psisep    => t_psisep
    psipls    => t_psipls
    xindf     => t_xindf
    slfnd     => t_slfnd
    xlfnd     => t_xlfnd
    volume    => t_volume
    surf      => t_surf
    ctroy     => t_ctroy
    qmerc     => t_qmerc
    placur    => t_placur
    helicity  => t_helicity
    elongn    => t_elongn
    trianu    => t_trianu
    trianl    => t_trianl
    trian     => t_trian
    t95       => t_t95
    tl95      => t_tl95
    tu95      => t_tu95
    trider    => t_trider
    f95       => t_f95
    p95       => t_p95
    psi95     => t_psi95
    e95       => t_e95
    q95       => t_q95
    qmin      => t_qmin
    rhomin    => t_rhomin
    qstar     => t_qstar
    aspct     => t_aspct
    wpf       => t_wpf
    wpt       => t_wpt
    ccdir     => t_ccdir
    al        => t_al
    bpsqva    => t_bpsqva
    presva    => t_presva
    pressa    => t_pressa
    betal     => t_betal
    bpolsa    => t_bpolsa
    rspt      => t_rspt
    zspt      => t_zspt
    dspt      => t_dspt
    bspt      => t_bspt
    nspt      => t_nspt
    nstkpts   => t_nstkpts
    skew      => s_skew
    dsep      => s_dsep
    dsip      => s_dsip
    
  END SUBROUTINE teq_output
  
  SUBROUTINE teqSurf_output

    USE teq_mod, only : t_nsym
    USE teqSurf_mod
    use teqlib_input
    USE teqlib_output, only : plsolo,plsoli,tlsolo,tlsoli,rpts,zpts
    USE teqSubs_mod

    t_nsol     => nsol
    t_nsep     => nsep
    t_npri     => npri
    t_lflux    => lflux
    t_jqm      => jqm
    t_jqd      => jqd
    t_nsym     => nsym

    CALL teqSurf_allocate

    plsolo     => t_plsolo
    plsoli     => t_plsoli
    tlsolo     => t_tlsolo
    tlsoli     => t_tlsoli
    rpts       => t_rpts
    zpts       => t_zpts

  END SUBROUTINE teqSurf_output
  
  SUBROUTINE teqPol_input

    use teqlib_input
    USE teqPol_mod

    t_tpl       => tpl
    t_epsrk     => epsrk
    t_epskrk    => epskrk
    t_anun      => anun
    t_alfa0     => alfa0
    t_alfa1     => alfa1
    t_alfa2     => alfa2
    t_nht       => nht
    t_ns1       => ns1
    t_ijob      => ijob
    t_mesc      => mesc
    t_inv_k     => inv_k
    t_inv_p     => inv_p
    t_rork      => rork
    t_npo       => npo
    t_ntet      => ntet
    t_iter_bdry => iter_bdry
    t_inv_flag  => inv_flag
    t_itimestep_converged => itimestep_converged
    t_qmax      => qmax
    t_inv_x     => inv_x

  END SUBROUTINE teqPol_input
  
  SUBROUTINE teqPol_output

    use teqlib_output
    USE teqPol_mod, only : t_qrk,t_jrk,t_srk,t_trk,t_vrk,t_crk,t_rrk,t_zrk,&
         t_f,t_pff,t_p,t_pp,t_aj
    USE sep_interp, only : i_rhosq

    IF(.NOT. ALLOCATED(t_qrk)) RETURN

    qrk    => t_qrk
    jrk    => t_jrk
    srk    => t_srk
    trk    => t_trk
    vrk    => t_vrk
    crk    => t_crk
    rrk    => t_rrk
    zrk    => t_zrk
    f      => t_f
    pff    => t_pff
    p      => t_p
    pp     => t_pp
    aj     => t_aj
    rhosq  => i_rhosq

  END SUBROUTINE teqPol_output

  SUBROUTINE teqGS_input

    use teqlib_input
    USE teqGS_mod
    USE sep_utils, only : use_elp

    t_ncsym    => ncsym
    t_nc       => nc
    t_cc       => cc(:nc)
    t_rc       => rc(:nc)
    t_zc       => zc(:nc)
    t_drc      => drc(:nc)
    t_dzc      => dzc(:nc)
    t_nrc      => nrc(:nc)
    t_nzc      => nzc(:nc)
    t_ac       => ac(:nc)
    t_ac2      => ac2(:nc)
    t_svec     => svec(:nc)
    t_rcase    => rcase
    t_zcase    => zcase
    t_drcase   => drcase
    t_dzcase   => dzcase
    t_rhc      => rhc(:nc)
    t_rxc      => rxc(:nc)
    t_rextc    => rextc
    t_pfps0    => pfps0(:nc)
    t_cc0      => cc0(:nc)
    t_gdc      => gdc
    t_ic       => ic(:nc)
    t_ix       => ix(:nc)
    t_ict      => ict
    t_lextc    => lextc
    t_iferro   => iferro
    t_pfid     => pfid(:nc)

    t_nloop    => nloop
    t_rloop    => rloop
    t_zloop    => zloop
    t_thloop   => thloop
    t_iloop    => iloop
    t_sigloop  => sigloop
    t_floop0   => floop0
    t_kgreenc  => kgreenc
    t_lgrn     => lgrn
    t_nsymc    => nsymc
    t_gauss_even=> n_gauss_even
    t_gauss_odd=> n_gauss_odd
    t_gauss_chck=> gauss_check
    use_elp    => use_ellip
    t_ncplot   => ncplot
    t_nsph     => nsph
    t_lsph     => lsph
    t_dt       => dt
    t_thetat   => thetat
    t_zocoil   => zocoil
    t_rocoil   => rocoil
    t_rbcoil   => rbcoil
    t_elcoil   => elcoil
    t_dcoil    => dcoil
    t_qcoil    => qcoil
    t_cnorm    => cnorm
    t_crdn     => crdn
    t_acmin    => acmin
    t_magfac   => magfac
    t_bsat     => bsat
    t_almim    => almim
    t_geomo    => geomo
    t_pfjx     => pfjx
    t_pfbx     => pfbx
    t_delc     => delc
    t_pftd     => pftd
    t_pfahs    => pfahs
    t_dfac     => dfac
    t_plcx     => plcx
    t_rlim     => rlim
    t_zlim     => zlim
    t_dlim     => dlim
    t_int_flag => int_flag
    t_rbd      => rbd(:nbd)
    t_zbd      => zbd(:nbd)
    t_tbd      => tbd
    t_psibd    => psibd
    t_rfbd     => rfbd(:nfbd)
    t_zfbd     => zfbd(:nfbd)
    t_psiwfc   => psiwfc
    t_whtz     => whtz
    t_alfbd    => alfbd(:nfbd)
    t_nbd      => nbd
    t_nfbd     => nfbd
    t_nlim     => nlim
    t_nfbc     => nfbc
    t_nmsc     => nmsc
    t_alpcoilc => alpcoilc
    t_alpsphc  => alpsphc
    t_epsb     => epsb
    t_epsj     => epsj
    t_alpcoil  => alpcoil
    t_alpsph   => alpsph
    t_vltf     => vltf
    t_alpcoil  => alpcoil
    t_alpsph   => alpsph
    t_iflxc    => iflxc
    t_ixpt     => ixpt
    t_raxis0   => raxis0
    t_zaxis0   => zaxis0 
    t_jaxis    => jaxis
    t_kaxis    => kaxis
    t_rxpt0    => rxpt0
    t_zxpt0    => zxpt0 
    t_jxp      => jxp
    t_kxp      => kxp
    t_cejima   => cejima
    t_rl       => rl
    t_irl      => irl
    t_keqic    => keqic
    t_ifscl    => ifscl
    t_ipscl    => ipscl
    t_ibdry    => ibdry
    t_ni       => ni
    t_nl       => nl
    t_ixp      => ixp
    t_ixpo     => ixpo
    t_initflx  => initflx
    t_ksave    => ksave
    t_lop0     => lop0
    t_betx     => betx
    t_rb       => rb
    t_nitr     => nitr
    t_limw     => limw
    t_lcal     => lcal
    t_ierr1    => ierr1
    t_psires0  => psires0
    t_dtofst   => dtofst
    t_rfix     => rfix
    t_dbdu     => dbdu
    t_queu     => queu
    t_bbdl     => bbdl
    t_bbdu     => bbdu
    t_ebdu     => ebdu
    t_dbdl     => dbdl
    t_quel     => quel
    t_ebdl     => ebdl
    t_nbdu     => nbdu
    t_nbdl     => nbdl
    t_nbs      => nbs
    t_dsurf    => dsurf
    t_lasteq   => lasteq
    t_lasteqsav   => lasteqsav
    t_nfil     => nfil
    t_ngp      => ngp
    t_nfjx     => nfjx
    t_ncase    => ncase
    t_ncoil    => ncoil
    t_crj_flag => crj_flag
    t_finit2   => finit2
    t_liml     => liml
    t_el       => el
    t_elx      => elx
    t_psil00   => psil00
  END SUBROUTINE teqGS_input

  SUBROUTINE teqGS_output

    use teqlib_input
    USE teqGS_mod, only : t_ncf,t_jm0p,t_km0p,t_nc0b,t_nc0p,t_nloop0p,&
         t_ncfo,t_nsymco,t_ngpo

    t_ncf     => ncf
    t_jm0p    => jm0p
    t_km0p    => km0p
    t_nc0b    => nc0b
    t_nc0p    => nc0p
    t_nloop0p => nloop0p
    t_ncfo    => ncfo
    t_nsymco  => nsymco
    t_ngpo    => ngpo

    CALL teqGS_p

  END SUBROUTINE teqGS_output
  
  SUBROUTINE teqGS_p

    USE teqlib_output
    USE teqGS_mod
    USE teqSubs_mod

    ncircuit=> t_ncircuit
    jbdcir  => t_jbdcir
    ncrmx   => t_ncrmx
    nczmx   => t_nczmx
    ifjx    => t_ifjx
    ifbx    => t_ifbx
    ncs     => t_ncs
    ngroup  => t_ngroup
    
    CALL teqGS_allocate_output
    CALL teq_allocate_greens
    
    ccf    => t_ccf
    rcf    => t_rcf
    zcf    => t_zcf
    drcf   => t_drcf
    dzcf   => t_dzcf
    ccfd   => t_ccfd
    ccmf   => t_ccmf
    cscl   => t_cscl
    ccls   => t_ccls
    cscl00 => t_cscl00
    cscl01 => t_cscl01
    cclsr  => t_cclsr
    cmplas => t_cmplas
    pfjp   => t_pfjp
    pfjc   => t_pfjc
    pfjf   => t_pfjf
    pfbc   => t_pfbc
    pfbi   => t_pfbi
    pfbo   => t_pfbo
    pfbr   => t_pfbr
    pfbz   => t_pfbz
    pfhs   => t_pfhs
    pfms   => t_pfms
    pffr   => t_pffr
    pffz   => t_pffz
    pfil   => t_pfil
    pfse   => t_pfse
    pfe0   => t_pfe0
    pfpsi  => t_pfpsi
    vlts2D => t_vlts2D
    pfpci  => t_pfpci
    pfpc0  => t_pfpc0
    rcg    => t_rcg
    zcg    => t_zcg
    gloop  => t_gloop
    br0p   => t_br0p
    bz0p   => t_bz0p
    aac    => t_aac
    rcs    => t_rcs
    zcs    => t_zcs
    ths    => t_ths
    p_in   => t_intc
    jnt    => t_jnt
    knt    => t_knt
    icc    => t_icc
    loopm  => t_loopm
    loop0  => t_loop0
    icf    => t_icf
    icnf   => t_icnf
    pfim   => t_pfim
    floop  => t_floop
    ploop  => t_ploop
    rc4    => t_rc4
    zc4    => t_zc4
    gc     => t_gc
    gfbr   => t_gfbr
    gfbz   => t_gfbz
    gp     => t_gp
    plim   => t_plim
    pbim   => t_pbim
    gpl    => t_gpl
    psires => t_psires
    rbin   => t_rbin
    rbout  => t_rbout
    pfcse  => t_pfcse
    pftse  => t_pftse
    pfcsi  => t_pfcsi
    pfcil  => t_pfcil
    error  => t_error
    resb   => t_resb
    resid  => t_resid
    prsx00 => t_prsx00
    prsx01 => t_prsx01
    rlimm  => t_rlimm
    zlimm  => t_zlimm

  END SUBROUTINE teqGS_p

  SUBROUTINE allocate_interface(jmm,kmm,mlss,nsymm,n4)
    USE sep_separatrix
    INTEGER, INTENT(IN) :: jmm,kmm,mlss,nsymm
    INTEGER, INTENT(INOUT) :: n4
    CALL allocate_separatrix(jmm,kmm,mlss,nsymm,n4)
  END SUBROUTINE allocate_interface

 end module teqinit
