MODULE moduleMeshInput0D
  !Creates a 0D mesh. mostly used for testing collisional processes.
  !This mesh consists on 1 node and 1 volume in which all particles are located.
  !No boundary conditions and no pusher should be applied to this geometry.
  !Output should go to a single file (per species) in which each row represents an iteration.
  !In principle, no EM field is applied.

  CONTAINS
    !Inits the 0D mesh
    SUBROUTINE init0D(self)
      USE moduleMesh
      USE moduleMeshOutput0D
      IMPLICIT NONE

      CLASS(meshGeneric), INTENT(inout), TARGET:: self

        IF (ASSOCIATED(meshForMCC, self)) self%printColl => printColl0D
        SELECT TYPE(self)
        TYPE IS(meshParticles)
          self%printOutput => printOutput0D
          self%printEM     => printEM0D
          self%readInitial => readInitial0D

        END SELECT
        self%readMesh => read0D

    END SUBROUTINE init0D

    !Reads a 0D mesh file.
    !No reading is actually done as the 0D mesh is a fixed one
    SUBROUTINE read0D(self, filename)
      USE moduleMesh
      USE moduleMesh0D
      IMPLICIT NONE

      CLASS(meshGeneric), INTENT(inout):: self
      CHARACTER(:), ALLOCATABLE, INTENT(in):: filename ! NOTE: Required by interface but unused
      REAL(8):: r(1:3)

      !Allocates one node
      self%numNodes = 1
      ALLOCATE(self%nodes(1:1))
      !Allocates one volume
      self%numCells = 1
      ALLOCATE(self%cells(1:1))
      !Allocates matrix K
      SELECT TYPE(self)
      TYPE IS(meshParticles)
        ALLOCATE(self%K(1:1, 1:1))
        ALLOCATE(self%IPIV(1:1, 1:1))
        self%K = 0.D0
        self%IPIV = 0.D0

      END SELECT

      !Creates the node
      ALLOCATE(meshNode0D:: self%nodes(1)%obj)
      r = 0.D0
      CALL self%nodes(1)%obj%init(1, r)

      !Creates the volume
      ALLOCATE(meshCell0D:: self%cells(1)%obj)
      CALL self%cells(1)%obj%init(1, (/ 1/), self%nodes)

    END SUBROUTINE read0D

    SUBROUTINE readInitial0D(filename, density, velocity, temperature)
      IMPLICIT NONE

      CHARACTER(:), ALLOCATABLE, INTENT(in):: filename
      REAL(8), ALLOCATABLE, INTENT(out), DIMENSION(:):: density
      REAL(8), ALLOCATABLE, INTENT(out), DIMENSION(:,:):: velocity
      REAL(8), ALLOCATABLE, INTENT(out), DIMENSION(:):: temperature
      REAL(8):: dummy
      INTEGER:: stat

      ALLOCATE(density(1:1))
      ALLOCATE(velocity(1:1, 1:3))
      ALLOCATE(temperature(1:1))

      OPEN(10, file = TRIM(filename))
      
      !Finds the last line of data
      stat = 0
      DO WHILE (stat==0)
        READ(10, *, iostat = stat)

      END DO

      !Go back two line
      BACKSPACE(10)
      BACKSPACE(10)

      !Reads data
      READ(10, *) dummy, density(1), velocity(1, 1:3), dummy, temperature(1)

    END SUBROUTINE readInitial0D

END MODULE moduleMeshInput0D
