!-------------------------------------------------------------------------------

!                      Code_Saturne version 5.0.3
!                      --------------------------
! This file is part of Code_Saturne, a general-purpose CFD tool.
!
! Copyright (C) 1998-2017 EDF S.A.
!
! This program is free software; you can redistribute it and/or modify it under
! the terms of the GNU General Public License as published by the Free Software
! Foundation; either version 2 of the License, or (at your option) any later
! version.
!
! This program is distributed in the hope that it will be useful, but WITHOUT
! ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
! FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
! details.
!
! You should have received a copy of the GNU General Public License along with
! this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
! Street, Fifth Floor, Boston, MA 02110-1301, USA.

!-------------------------------------------------------------------------------

!===============================================================================
! Function:
! ---------
!> \file  cs_user_boundary_conditions-electric_arcs.f90
!> \brief Example of cs_user_boundary_conditions subroutine for electric arcs
!
!-------------------------------------------------------------------------------

!-------------------------------------------------------------------------------
! Arguments
!______________________________________________________________________________.
!  mode           name          role                                           !
!______________________________________________________________________________!
!> \param[in]     nvar          total number of variables
!> \param[in]     nscal         total number of scalars
!> \param[out]    icodcl        boundary condition code:
!>                               - 1 Dirichlet
!>                               - 2 Radiative outlet
!>                               - 3 Neumann
!>                               - 4 sliding and
!>                                 \f$ \vect{u} \cdot \vect{n} = 0 \f$
!>                               - 5 smooth wall and
!>                                 \f$ \vect{u} \cdot \vect{n} = 0 \f$
!>                               - 6 rough wall and
!>                                 \f$ \vect{u} \cdot \vect{n} = 0 \f$
!>                               - 9 free inlet/outlet
!>                                 (input mass flux blocked to 0)
!> \param[in]     itrifb        indirection for boundary faces ordering
!> \param[in,out] itypfb        boundary face types
!> \param[out]    izfppp        boundary face zone number
!> \param[in]     dt            time step (per cell)
!> \param[in,out] rcodcl        boundary condition values:
!>                               - rcodcl(1) value of the dirichlet
!>                               - rcodcl(2) value of the exterior exchange
!>                                 coefficient (infinite if no exchange)
!>                               - rcodcl(3) value flux density
!>                                 (negative if gain) in w/m2 or roughness
!>                                 in m if icodcl=6
!>                                 -# for the velocity \f$ (\mu+\mu_T)
!>                                    \gradt \, \vect{u} \cdot \vect{n}  \f$
!>                                 -# for the pressure \f$ \Delta t
!>                                    \grad P \cdot \vect{n}  \f$
!>                                 -# for a scalar \f$ cp \left( K +
!>                                     \dfrac{K_T}{\sigma_T} \right)
!>                                     \grad T \cdot \vect{n} \f$
!_______________________________________________________________________________

subroutine cs_user_boundary_conditions &
 ( nvar   , nscal  ,                                              &
   icodcl , itrifb , itypfb , izfppp ,                            &
   dt     ,                                                       &
   rcodcl )

!===============================================================================

!===============================================================================
! Module files
!===============================================================================

use paramx
use numvar
use optcal
use cstphy
use cstnum
use entsor
use parall
use period
use ihmpre
use ppppar
use ppthch
use coincl
use cpincl
use ppincl
use ppcpfu
use atincl
use ctincl
use cs_fuel_incl
use mesh
use field
use cs_c_bindings

!===============================================================================

implicit none

! Arguments

integer          nvar   , nscal

integer          icodcl(nfabor,nvarcl)
integer          itrifb(nfabor), itypfb(nfabor)
integer          izfppp(nfabor)

double precision dt(ncelet)
double precision rcodcl(nfabor,nvarcl,3)

! Local variables

!< [loc_var_dec]
integer          ifac, ii, iel,iproc,icell
integer          idim,izone,it_pvbc,ilelt, nlelt,int32size,stat!,fbrnum  !cellsnum
integer          ifcurx,ifcury,ifcurz,ifcpvbc,ifcpvbcr        !pointers
integer          ipotr, ipoti, f_id, ipotva,keyvar
integer          ndimve
parameter        (ndimve = 3)  !dimensions number
integer          ncelglob4
integer          icelcur(ncelgb)
!parameter (fbrnum = 6390)!nfbrgb)
!parameter (cellsnum = 100000)!ncelgb - global ncel)
integer, allocatable, dimension(:) :: lstelt
character(len=80) :: filename,format_string,filenameout
double precision, dimension(:), pointer :: cpro_curx,cpro_cury,cpro_curz
double precision, dimension(:,:), pointer :: cpro_pvbc,cpro_pvbcrel
double precision elcurr , elcurr1, surface
double precision ray , Rarc , jmax , bb, mu0, pii,mu0div4pi,currelcoef
double precision rr1, rr2, debit, surftot
double precision vol(ncelgb),coord(3,ncelgb),elcur(3,ncelgb)
double precision elcurcheck,pvrelcoef,rfminrc,elcursum,maxBC,checksum,pvbc_mag
!< [loc_var_dec]
common /curoutput/ filenameout
!===============================================================================
allocate(lstelt(nfabor))  ! temporary array for boundary faces selection

!===============================================================================
! Assign boundary conditions to boundary faces here

! For each subset:
! - use selection criteria to filter boundary faces of a given subset
! - loop on faces from a subset
!   - set the boundary condition for each face
!===============================================================================

! --- For boundary faces of entree assign an inlet for all phases and assign a cathode for "electric" variables.
!=========================================================================================================       
!This subroutine doesn't work for gas mixtures

!**************************************************
!                CONSTANTS                        *
!**************************************************

Rarc = 1.5D-3
jmax = 1.27D8
elcurr = 2.0D1
elcurr1 = 0.0D0
bb = 1.96D3
jmax = 6*elcurr / (pi*Rarc*Rarc)
elcurr = 0.0D0
mu0 = 1.2566370614d-6 !Vacuum permeability
pii = 3.14159265359d0 !π number
mu0div4pi=mu0/4d0/pii
it_pvbc=50 !PV BC recalculation period
pvrelcoef=0.99d0 !Relaxation coefficient for vector potential boundary condition
int32size=2147483647

if ( ippmod(ielarc).ge.2 ) then  !ONLY FOR ELECTRIC ARCS
!*********************************************************************************************
!                POINTERS                                                                    *
!*********************************************************************************************
  call field_get_key_id("variable_id", keyvar)
  
  call field_get_id('elec_pot_r', f_id)
  call field_get_key_int(f_id, keyvar, ipotr)
  
  call field_get_id('vec_potential', f_id)
  call field_get_key_int(f_id, keyvar, ipotva)
  !ifcpvbc=-1
  !ifcpvbcr=-1
  call field_get_id_try('PotVecBC', ifcpvbc)              !Obtaining pointer to PV boundary condition directly calculated from electric current.
  if (ifcpvbc.ge.0) call field_get_val_v(ifcpvbc, cpro_pvbc)                !obtaining PV boundary condition directly calculated from electric current.
  if (ifcpvbc.lt.0) print*,'ERROR: No PotVecBC id. cs_user_boundary_conditions.f90' !error message just in case. 
  call field_get_id_try('PVBCRel', ifcpvbcr)              !Obtaining pointer to PV boundary condition with relaxation.
  if (ifcpvbcr.ge.0) call field_get_val_v(ifcpvbcr, cpro_pvbcrel)            !obtaining PV boundary condition with relaxation
  if (ifcpvbcr.lt.0) print*,'ERROR: No PVBCRel id. cs_user_boundary_conditions.f90' !error message just in case. 
  
  call field_get_id_try('current_re', ifcurx)
  if (ifcurx.ge.0) call field_get_val_s(ifcurx, cpro_curx)
  if (ifcurx.lt.0) print*,'ERROR: No current_re_1 id. cs_user_boundary_conditions.f90' !error message just in case. 
  !call field_get_id_try('current_re_2', ifcury)
  ifcury=ifcurx+1
  if (ifcury.ge.0) call field_get_val_s(ifcury, cpro_cury)
  if (ifcury.lt.0) print*,'ERROR: No current_re_2 id. cs_user_boundary_conditions.f90' !error message just in case. 
  !call field_get_id_try('current_re_3', ifcurz)
  ifcurz=ifcury+1
  if (ifcurz.ge.0) call field_get_val_s(ifcurz, cpro_curz)
  if (ifcurz.lt.0) print*,'ERROR: No current_re_3 id. cs_user_boundary_conditions.f90' !error message just in case. 

!***************************************************************************************
!  INITIALIZATION OF PV BC WITH ZERO AT FIRST TIME STEP                                *
!***************************************************************************************

  if (ntcabs-ntpabs.eq.1 .and. ifcpvbcr.ge.0) then
    call getfbr('all[]', nlelt, lstelt)
    write(*,'(A,I5)')'global number of boundary faces nfbrgb=',nfbrgb
    do ilelt = 1, nlelt
        ifac = lstelt(ilelt)
        do idim = 1, ndimve
          cpro_pvbcrel(ifac,idim)=0d0
        end do
    end do
  end if

!***************************************************************************************
!                ELECTRIC CURRENT OUTPUT FOR PARALLEL CASE FOR BIG MESHES              *
!*************************************************************************************** 

  if (irangp.ge.0 .and. ncelgb.gt.int32size .and. ifcpvbc.ge.0 .and. ifcpvbcr.ge.0) then
    !STEP 1. Defining of file name for current thread = "geom_eleccur_+(1..(nrangp-1))+.out"
    !nrangp - number of processes (=1 if sequental)
    !irangp - process rank r (0 < r < n_processes) in distributed parallel run
    if (ntcabs-ntpabs.eq.1) then
      !write(*,'(A,
      if (irangp < 10) then
        format_string = "(A13,I1,A4)"
      else if(irangp <100) then
        format_string = "(A13,I2,A4)"
      else
        format_string = "(A13,I3,A4)"
      end if
      write (filenameout,format_string) "geom_eleccur_", irangp,".out"
      !inquire(FILE=filenameout, exist=file_exists)
      open(unit=impusr(10), iostat=stat, file=filenameout, status='new',form='formatted')
      close(impusr(10))
    end if
    !STEP 2. Cleaning of the file from old data.
    if (mod(ntcabs-ntpabs+1,it_pvbc).eq.0) then
      open(unit=impusr(10), iostat=stat, file=filenameout, status='replace',form='formatted')
      close(impusr(10))
    end if
    !STEP 3. The file writing.
    if ((mod(ntcabs-ntpabs,it_pvbc).eq.0 .and. ntcabs-ntpabs.ge.it_pvbc) .or.  &
        ((ntcabs-ntpabs).eq.2)) then     
      write(*,'(A20,A,I6)')filenameout,'Output of electric current and geometry. Time step ',ntcabs
      open(unit=impusr(10), iostat=stat, file=filenameout, status='old',form='formatted')
      do iel=1,ncel
        write(impusr(10),'(I6,E18.8,E18.8,E18.8,E18.8,E18.8,E18.8,E18.8)') &
                            iel,volume(iel),xyzcen(1,iel),xyzcen(2,iel),xyzcen(3,iel), &
                            cpro_curx(iel),cpro_cury(iel),cpro_curz(iel)
      end do
      close(impusr(10))
      !attempt to equalize the progress for every processor
      checksum=1d0
      call parsom(checksum)
      write(*,'(I3,A,F10.3)')irangp,' checksum=',checksum
    end if
  end if

!***************************************************************************************
!                BOUNDARY CONDION FOR VECTOR POTENTIAL EVERY  it_pvbc time steps       *
!***************************************************************************************
  if (ifcpvbc.ge.0 .and. ifcpvbcr.ge.0) then
    ! Recalculation starts at time step number 2,1*it_pvbc,2*it_pvbc,..
    ! Vector Potential is calculated with the formula similar to the Biot Savart law:
    ! cpro_pvbc(iface,1) = Ax=  mu0/4π *∫∫∫jx*dV/|vector Rface - vector Rcell|
    ! cpro_pvbc(iface,2) = Ay=  mu0/4π *∫∫∫jy*dV/|vector Rface - vector Rcell|
    ! cpro_pvbc(iface,3) = Az=  mu0/4π *∫∫∫jz*dV/|vector Rface - vector Rcell|
    if ((mod(ntcabs-ntpabs,it_pvbc).eq.0 .and. ntcabs-ntpabs.ge.it_pvbc) .or.  &
        (ntcabs-ntpabs.eq.2)) then
      !SINGLE PROCESSOR
      if (irangp.lt.0) then
        call getfbr('all[]', nlelt, lstelt)
        write(*,'(I3,A64,I3)')irangp,' Boundary condition for vector potential calculation. Time step=',ntcabs
        do ilelt = 1, nlelt
            ifac = lstelt(ilelt)
            cpro_pvbc(ifac,1)=0d0
            cpro_pvbc(ifac,2)=0d0
            cpro_pvbc(ifac,3)=0d0
            do iel=1,ncel
              !Calculation of |vector Rface - vector Rcell|
              rfminrc=sqrt((cdgfbo(1,ifac)-xyzcen(1,iel))**2+  &
                           (cdgfbo(2,ifac)-xyzcen(2,iel))**2+  &
                           (cdgfbo(3,ifac)-xyzcen(3,iel))**2)
              !Calculation of integral ∫∫∫j*dV/|vector Rface - vector Rcell|
              cpro_pvbc(ifac,1)=cpro_pvbc(ifac,1)+cpro_curx(iel)*volume(iel)/rfminrc
              cpro_pvbc(ifac,2)=cpro_pvbc(ifac,2)+cpro_cury(iel)*volume(iel)/rfminrc
              cpro_pvbc(ifac,3)=cpro_pvbc(ifac,3)+cpro_curz(iel)*volume(iel)/rfminrc
            end do
            cpro_pvbc(ifac,1)=cpro_pvbc(ifac,1)*mu0div4pi
            cpro_pvbc(ifac,2)=cpro_pvbc(ifac,2)*mu0div4pi
            cpro_pvbc(ifac,3)=cpro_pvbc(ifac,3)*mu0div4pi
        end do
      end if
      
      !PARALLEL CALCULATION 
      !SMALL MESHES - if ncelgb value fits to __int32 - MPI restriction
      !integer(kind=4) values range from -2,147,483,648 to 2,147,483,647
      if (irangp.ge.0 .and. ncelgb.le.int32size) then
        ncelglob4 = ncelgb
        call paragv(ncel, ncelglob4, xyzcen(1,:), coord(1,:)) !MPI paragv(__int32 size of the local array,__int32 size of the global array,array,g_array)
        call paragv(ncel, ncelglob4, xyzcen(2,:), coord(2,:))
        call paragv(ncel, ncelglob4, xyzcen(3,:), coord(3,:))
        call paragv(ncel, ncelglob4, cpro_curx, elcur(1,:))
        call paragv(ncel, ncelglob4, cpro_cury, elcur(2,:))
        call paragv(ncel, ncelglob4, cpro_curz, elcur(3,:))        
        call paragv(ncel, ncelglob4, volume, vol)
        call getfbr('all[]', nlelt, lstelt)
        do ilelt = 1, nlelt
            ifac = lstelt(ilelt)
            !Here we don't use loop "do idim = 1,ndimve" to avoid calculation of the same rfminrc three times for every dimension
            cpro_pvbc(ifac,1)=0d0
            cpro_pvbc(ifac,2)=0d0
            cpro_pvbc(ifac,3)=0d0
            do icell=1,ncelgb
              !Calculation of |vector Rface - vector Rcell|
              rfminrc=sqrt((cdgfbo(1,ifac)-coord(1,icell))**2    &
                          +(cdgfbo(2,ifac)-coord(2,icell))**2    &
                          +(cdgfbo(3,ifac)-coord(3,icell))**2)
              !Calculation of integral j*dV/|vector Rface - vector Rcell|
              cpro_pvbc(ifac,1)=cpro_pvbc(ifac,1)+elcur(1,icell)*vol(icell)/rfminrc
              cpro_pvbc(ifac,2)=cpro_pvbc(ifac,2)+elcur(2,icell)*vol(icell)/rfminrc
              cpro_pvbc(ifac,3)=cpro_pvbc(ifac,3)+elcur(3,icell)*vol(icell)/rfminrc
            end do
            cpro_pvbc(ifac,1)=cpro_pvbc(ifac,1)*mu0div4pi
            cpro_pvbc(ifac,2)=cpro_pvbc(ifac,2)*mu0div4pi
            cpro_pvbc(ifac,3)=cpro_pvbc(ifac,3)*mu0div4pi
            !Calculation of Max PV BC for output and debugging.
            pvbc_mag=sqrt(cpro_pvbc(ifac,1)**2 + cpro_pvbc(ifac,2)**2 + cpro_pvbc(ifac,3)**2)
            if (pvbc_mag.gt.maxBC) maxBC=pvbc_mag
        end do
        write(*,'(I3,I6,A,E12.5)')irangp,ntcabs,' MPI BC for vector potential calculation. Max Value=',maxBC
      end if
      !BIG MESHES with ncelgb bigger than __int32 range
      !BETA VERSION. ALGORITHM IS TESTED ONLY WITH SMALL MESH WITH 93375 CELLS
      !ncelgb = ncelg2 in majgeo ncelg2 = mesh->n_g_cells = n_g_elts[0]; in cs_preprocess.c from MPI_Allreduce
      if (irangp.ge.0 .and. ncelgb.gt.int32size) then
        write(*,'(I3,A,I5)')irangp,' files are read t=',ntcabs
        iel=1
        elcurcheck=0d0
        elcursum = 0d0
        do iproc=0,nrangp-1

          if (iproc < 10) then
            format_string = "(A13,I1,A4)"
          else if(iproc <100) then
            format_string = "(A13,I2,A4)"
          else
            format_string = "(A13,I3,A4)"
          end if
          write (filename,format_string) "geom_eleccur_", iproc,".out"
          open(unit=impusr(12), file=filename, status='old',form='formatted')
  
          do while (.true.)            !icelcur
            read(impusr(12),*,end=999) icelcur(iel),vol(iel),coord(1,iel),coord(2,iel),coord(3,iel),  &
                                       elcur(1,iel),elcur(2,iel),elcur(3,iel)
            if(iproc.eq.irangp) then
              elcurcheck=elcurcheck+dabs(cpro_curx(icelcur(iel))-elcur(1,iel))+ &
                                    dabs(cpro_cury(icelcur(iel))-elcur(2,iel))+ &
                                    dabs(cpro_curz(icelcur(iel))-elcur(3,iel))
              elcursum = elcursum + dabs(cpro_curx(icelcur(iel)))+ &
                                    dabs(cpro_cury(icelcur(iel)))+ &
                                    dabs(cpro_curz(icelcur(iel)))
              !if (mod(iel,10000).eq.0) then !output for debugging
              !  write(*,'(I3,I6,E17.7,E17.7,E17.7,E17.7,E17.7,E17.7,E17.7)')               &
              !          irangp,iel,vol(iel),coord(1,iel),coord(2,iel),                     &
              !          coord(3,iel),elcur(1,iel),elcur(2,iel),elcur(3,iel)
              !  write(*,'(I3,I6,E17.7,E17.7,E17.7,E17.7,E17.7,E17.7,E17.7)')               &
              !          irangp,icelcur(iel),volume(icelcur(iel)),xyzcen(1,icelcur(iel)),xyzcen(2,icelcur(iel)), &
              !          xyzcen(3,icelcur(iel)),cpro_curx(icelcur(iel)),cpro_cury(icelcur(iel)),cpro_curz(icelcur(iel))
              !end if
            end if
            iel=iel+1
          end do
  999     continue
          close(impusr(12)) 
        end do
        if (elcursum.gt.0d0) then
          write(*,'(I3,A,E15.7,I6,I6)')irangp,' Electric current from file delta/Sum(j)=',elcurcheck/elcursum
          maxBC=0d0
          call getfbr('all[]', nlelt, lstelt)
          do ilelt = 1, nlelt
              ifac = lstelt(ilelt)
              !Here we don't use loop "do idim = 1,ndimve" to avoid calculation of the same rfminrc three times for every dimension
              cpro_pvbc(ifac,1)=0d0
              cpro_pvbc(ifac,2)=0d0
              cpro_pvbc(ifac,3)=0d0
              do icell=1,ncelgb
                !Calculation of |vector Rface - vector Rcell|
                rfminrc=sqrt((cdgfbo(1,ifac)-coord(1,icell))**2    &
                            +(cdgfbo(2,ifac)-coord(2,icell))**2    &
                            +(cdgfbo(3,ifac)-coord(3,icell))**2)
                !Calculation of integral j*dV/|vector Rface - vector Rcell|
                cpro_pvbc(ifac,1)=cpro_pvbc(ifac,1)+elcur(1,icell)*vol(icell)/rfminrc
                cpro_pvbc(ifac,2)=cpro_pvbc(ifac,2)+elcur(2,icell)*vol(icell)/rfminrc
                cpro_pvbc(ifac,3)=cpro_pvbc(ifac,3)+elcur(3,icell)*vol(icell)/rfminrc
              end do
              cpro_pvbc(ifac,1)=cpro_pvbc(ifac,1)*mu0div4pi
              cpro_pvbc(ifac,2)=cpro_pvbc(ifac,2)*mu0div4pi
              cpro_pvbc(ifac,3)=cpro_pvbc(ifac,3)*mu0div4pi
              !Calculation of Max PV BC for output and debugging.
              pvbc_mag=sqrt(cpro_pvbc(ifac,1)**2 + cpro_pvbc(ifac,2)**2 + cpro_pvbc(ifac,3)**2)
              if (pvbc_mag.gt.maxBC) maxBC=pvbc_mag
          end do
          write(*,'(I3,A48,E12.5,A,I5)')irangp,' BC for vector potential calculation. Max Value=',maxBC,' nlelt=',nlelt
        else
          write(*,'(I3,A,E15.7,I6,I6)')irangp,'ERROR: Sum(j)=0d0 Electric current from file delta=',elcurcheck
        end if
      end if
    end if
    
    !RELAXATION OF BOUNDARY CONDITION FOR VECTOR POTENTIAL AT EVERY TIME STEP
    call getfbr('all[]', nlelt, lstelt)
    do ilelt = 1, nlelt
      ifac = lstelt(ilelt)
      do idim = 1, ndimve
        cpro_pvbcrel(ifac,idim)=cpro_pvbcrel(ifac,idim)*pvrelcoef+(1-pvrelcoef)*cpro_pvbc(ifac,idim)
        icodcl(ifac,ipotva + idim-1)   = 1
        rcodcl(ifac,ipotva + idim-1,1) = cpro_pvbcrel(ifac,idim)
      end do
    end do
  !If there is no field for vector potential boundary condition we impose PVNV for bord_lateral and PVNF for all other faces
  else
    if (ntcabs-ntpabs.eq.2) print*,"ERROR: No pointer to PV BC or PV BC with relaxation. 2."
    call getfbr('entree', nlelt, lstelt)
    do ilelt = 1, nlelt
      ifac = lstelt(ilelt)
      do idim = 1, ndimve
        icodcl(ifac,ipotva + idim-1)   = 3
        rcodcl(ifac,ipotva + idim-1,3) = 0.d0
      end do
    end do
    call getfbr('bord_lateral', nlelt, lstelt)
    do ilelt = 1, nlelt
      ifac = lstelt(ilelt)
      do idim = 1, ndimve
        icodcl(ifac,ipotva + idim-1)   = 1   !only here should be A=0 according to Isabelle Choquet 2012 On the choice of electromagnetic model for arcs
        rcodcl(ifac,ipotva + idim-1,1) = 0.d0
      end do
    end do
    call getfbr('bord_superieur', nlelt, lstelt)
    do ilelt = 1, nlelt
      ifac = lstelt(ilelt)
      do idim = 1, ndimve
        icodcl(ifac,ipotva + idim-1)   = 3
        rcodcl(ifac,ipotva + idim-1,3) = 0.d0
      end do
    end do
    call getfbr('bord_lateral_nozzle', nlelt, lstelt)
    do ilelt = 1, nlelt
      ifac = lstelt(ilelt)
      do idim = 1, ndimve
        icodcl(ifac,ipotva + idim-1)   = 3
        rcodcl(ifac,ipotva + idim-1,3) = 0.d0
      end do
    end do
    call getfbr('bord_anode', nlelt, lstelt)
    do ilelt = 1, nlelt
      ifac = lstelt(ilelt)
      do idim = 1, ndimve
        icodcl(ifac,ipotva + idim-1)   = 3
        rcodcl(ifac,ipotva + idim-1,3) = 0.d0
      end do
    end do
    call getfbr('base_anode', nlelt, lstelt)
    do ilelt = 1, nlelt
      ifac = lstelt(ilelt)
      do idim = 1, ndimve
        icodcl(ifac,ipotva + idim-1)   = 3
        rcodcl(ifac,ipotva + idim-1,3) = 0.d0
      end do
    end do
    call getfbr('cathode', nlelt, lstelt)
    do ilelt = 1, nlelt
      ifac = lstelt(ilelt)
      do idim = 1, ndimve
        icodcl(ifac,ipotva + idim-1)   = 3
        rcodcl(ifac,ipotva + idim-1,3) = 0.d0
      end do
    end do
  end if   
end if
!***************************************************************************************
!                THERMAL, INLET AND ELECTRIC BOUNDARY CONDITIONS                       *
!***************************************************************************************

call getfbr('entree', nlelt, lstelt)
if (ntcabs-ntpabs.eq.1) write(*,'(A,I5)')'BC entree nlelt=',nlelt
do ilelt = 1, nlelt

  ifac = lstelt(ilelt)
  itypfb(ifac) = ientre
  izone = 1 ! Zone Number (from 1 to n)
  ! Zone localization for a given face
  izfppp(ifac) = izone
  !Velocity
  rr2 = 3.0D-3   !external radius
  rr1 = 1.5D-3   !internal radius
  debit = 0.11D-3
  surftot = pi * ((rr2**2)-(rr1**2))
  rcodcl(ifac,iu,1) = 0.0d0 
  rcodcl(ifac,iv,1) = 0.d0
  rcodcl(ifac,iw,1) = debit / surftot
  !Enthalpy
  ii = ihm
  icodcl(ifac,isca(ii))   = 1
  rcodcl(ifac,isca(ii),1) = 14.0D3 !corresponds to the temperature of 300 Kelvin for argon at atmospheric pressure (see dp_ELE)
  !Electric potential
  if (ippmod(ielarc).ge. 2) then
    icodcl(ifac,ipotr)   = 3
    rcodcl(ifac,ipotr,3) = 0.0
  end if
end do

write(nfecra,1011)rcodcl(ifac,iw,1)
! --- For boundary faces of bord_lateral and bord_superieur assign an free outlet for all phases and example of electrode for Joule Effect by direct conduction.
!isolib - free outlet face or more precisely free inlet/outlet with forced pressure.  DOESN'T WORK IN CS4.2. GIVES UNSTABLE PRESSURE WHICH RESULTS IN UNSTABLE ELECTRIC ARC
!ifrent - free outlet, free inlet (based on Bernoulli relationship) face.
!     ================================================================================================================================
 
call getfbr('bord_lateral', nlelt, lstelt)
if (ntcabs-ntpabs.eq.1) write(*,'(A,I5)')'BC bord_lateral        nlelt=',nlelt
do ilelt = 1, nlelt

  ifac = lstelt(ilelt)
  itypfb(ifac)   = ifrent     !isolib is unstable with CS4.2, but was used with CS1.3 and worked okay. 
  izone = 2 ! Zone Number (from 1 to n)
  izfppp(ifac) = izone   ! Zone location for a given face

  ! --- Handle Scalars
  ! Enthalpy in J/kg  (By default zero flux with ISOLIB). Nothing to do
  ! Mass fraction of the (n-1) gas mixture components (Zero flux by defaut with ISOLIB). Nothing to do

  ! Specific model for Joule Effect by direct conduction:

  ! If you want to make a simulation with an imposed Power PUISIM
  ! (you want to get PUISIM imposed in useli1 and PUISIM = Amp x Volt)
  ! you need to impose IELCOR=1 in useli1
  ! The boundary conditions will be scaled by COEJOU coefficient
  ! for example the electrical potential will be multiplied bu COEJOU
  ! (both real and imaginary part of the electrical potential if needed)

  ! COEJOU is automatically defined in order that the calculated dissipated power
  ! by Joule effect (both real and imaginary part if needed) is equal to PUISIM

  ! At the beginning of the calculation, COEJOU ie equal to 1;
  ! COEJOU is writing and reading in the result files.

  ! If you don't want to calculate with by scaling,
  ! you can impose directly the value.
  
  !Electric potential
  if (ippmod(ielarc).ge. 2) then
    icodcl(ifac,ipotr)   = 3
    rcodcl(ifac,ipotr,3) = 0.0
  end if
end do

call getfbr('bord_superieur', nlelt, lstelt)
if (ntcabs-ntpabs.eq.1) write(*,'(A,I5)')'BC bord_superieur      nlelt=',nlelt
do ilelt = 1, nlelt
  ifac = lstelt(ilelt)
  itypfb(ifac)   = ifrent   !isolib is unstable with CS4.2, but was used with CS1.3 and worked okay.
  izone = 3
  izfppp(ifac) = izone
  !Electric potential
  if (ippmod(ielarc).ge. 2) then
    icodcl(ifac,ipotr)   = 3
    rcodcl(ifac,ipotr,3) = 0.0
  end if
end do

call getfbr('bord_lateral_nozzle', nlelt, lstelt)
if (ntcabs-ntpabs.eq.1) write(*,'(A,I5)')'BC bord_lateral_nozzle nlelt=',nlelt
do ilelt = 1, nlelt
  ifac = lstelt(ilelt)
  itypfb(ifac)   = iparoi   !smooth solid wall face, impermeable and with friction.
  izone = 4
  izfppp(ifac) = izone
  !Enthalpy
  ii = ihm
  icodcl(ifac,isca(ii))   = 3
  rcodcl(ifac,isca(ii),3) = 0.0D0  !zero flux of enthalpy
  !Electric potential
  if (ippmod(ielarc).ge. 2) then
    icodcl(ifac,ipotr)   = 3
    rcodcl(ifac,ipotr,3) = 0.0
  end if
end do

call getfbr('bord_anode', nlelt, lstelt)
if (ntcabs-ntpabs.eq.1) write(*,'(A,I5)')'BC bord_anode          nlelt=',nlelt
do ilelt = 1, nlelt
  ifac = lstelt(ilelt)
  itypfb(ifac)   = iparoi
  izone = 5
  izfppp(ifac) = izone
  !Enthalpy
  ii = ihm
  icodcl(ifac,isca(ii))   = 1
  rcodcl(ifac,isca(ii),1) = 14.0D3 !corresponds to the temperature of 300 Kelvin for copper (see H-T_Cu2)
  !Electric potential
  if (ippmod(ielarc).ge. 2) then
    icodcl(ifac,ipotr)   = 1
    rcodcl(ifac,ipotr,1) = 0.0
  end if
end do

call getfbr('base_anode', nlelt, lstelt)
if (ntcabs-ntpabs.eq.1) write(*,'(A,I5)')'BC base_anode          nlelt=',nlelt
do ilelt = 1, nlelt
  ifac = lstelt(ilelt)
  itypfb(ifac)   = iparoi
  izone = 6
  izfppp(ifac) = izone
  !Enthalpy
  ii = ihm
  icodcl(ifac,isca(ii))   = 3
  rcodcl(ifac,isca(ii),3) = 0.d0!14.0D3 corresponds to the temperature of 300 Kelvin for copper (see H-T_Cu2)
  !Electric potential
  if (ippmod(ielarc).ge. 2) then
    icodcl(ifac,ipotr)   = 1
    rcodcl(ifac,ipotr,1) = 0.0
  end if
end do
!For Argon start with 100Amp is unstable. But for 30Amp it is okay. Therefore we use relaxation from 30Amp to 100Amp.
!currelcoef=0.99d0   !Relaxation coefficient for the electric current value.
!couimp = couimp*currelcoef+100.0d0*(1-currelcoef) !Imposed current intensity (electric arc) in Amp
!if (mod(ntcabs-ntpabs,50).eq.0) write(*,'(I5,A,F10.4)')ntcabs,' Imposed current couimp=',couimp
call getfbr('cathode', nlelt, lstelt)
if (ntcabs-ntpabs.eq.1) write(*,'(A,I5)')'BC cathode             nlelt=',nlelt
do ilelt = 1, nlelt
  ifac = lstelt(ilelt)
  itypfb(ifac)   = iparoi
  izone = 7
  izfppp(ifac) = izone
  !Enthalpy
  ii = ihm
  icodcl(ifac,isca(ii))   = 3
  rcodcl(ifac,isca(ii),3) = 0.0D0  !zero flux of enthalpy
  !Electric potential
  if (ippmod(ielarc).ge. 2) then
    icodcl(ifac,ipotr)   = 1
    rcodcl(ifac,ipotr,1) = -pot_diff
    !call field_get_val_v(iprpfl(idjr(1)), djr)
    !zelcurr = djr(3,iel)
    !call field_get_val_s(iprpfl(idjr(3)), djr3)
    iel = ifabor(ifac)
    surface = surfbn(ifac)
    elcurr = elcurr + cpro_curz(iel) * surface
    !elcou = elcou + cpro_cur3(iel) * surfac(3,ifac)
    ray = sqrt((cdgfbo(1,ifac)**2)+ (cdgfbo(2,ifac)**2))
    elcurr1 = elcurr1 + (jmax * exp((-1.0D0)*bb*ray)* surface) !I don't know what is this
  end if
end do
if (irangp.ge.0) then
  call parsom (elcurr)
  call parsom (elcurr1)
end if
elcurr = ABS(elcurr)
write(nfecra,1009)elcurr
write(nfecra,1010)elcurr1
!--------
! Formats
!--------
    
 1009 format(/,'elcurr = ',E14.5)
 1010 format(/,'elcurr1= ',E14.5)
 1011 format(/,'Inlet Velocity = ',E14.5)
! 1010  format(/,' Nx   = ',E14.5,/,          ' Ny = ',E14.5,/,          ' Nz = ',E14.5)
!----
! End
!----

deallocate(lstelt)  ! temporary array for boundary faces selection

return
end subroutine cs_user_boundary_conditions
