SUBROUTINE Write_vasp(poscar)

  Use Path_module
  Use Io_module

  IMPLICIT NONE

  CHARACTER(SCHARS), INTENT(IN) :: poscar

  INTEGER(KINT) :: IGeom, Idx
  REAL(KREAL), ALLOCATABLE :: GeomTmpC(:), GeomTmp(:)
  CHARACTER(SCHARS) :: Line,Line2

  ! For VMD printing
  CHARACTER(SCHARS), PARAMETER :: FirstWord="mol "
  CHARACTER(LCHARS), PARAMETER :: LastWords=" type POSCAR first 0 last -1 step 1 filebonds 1 autobonds 1 waitfor all"

  CHARACTER(LCHARS) :: TITLE
  LOGICAL :: Debug

  INTERFACE
     function valid(string) result (isValid)
       CHARACTER(*), intent(in) :: string
       logical                  :: isValid
     END function VALID
  END INTERFACE

  debug=valid('write_vasp')
  if (debug) WRITE(*,*) '================ Entering Write_VASP ===================='

  ALLOCATE(GeomTmpC(3*Nat), GeomTmp(NCoord))

  Line2="00"
  DO IGeom=1,NGeomF
     WRITE(Line,'(I5)') IGeom-1
     Idx=2-Len_TRIM(ADJUSTL(Line))
     OPEN(IOTMP,File=TRIM(POSCAR) // "_" // Line2(1:Idx) // AdjustL(TRIM(Line)))
     ! we convert the coordinates into Cartesian coordinates
     SELECT CASE (Coord)
     CASE ('CART','HYBRID')
        GeomTmpC=Reshape(reshape(XyzGeomF(IGeom,:,:),(/Nat,3/),ORDER=(/2,1/)),(/3*Nat/))
     CASE ('ZMAT')
        GeomTmp=IntCoordF(IGeom,:)
        ! we have to generate the cartesian coordinates from the internal coordinates
        CAll Int2Cart(nat,indzmat,geomtmp,GeomTmpC)
     CASE ('MIXED')
        GeomTmp=IntCoordF(IGeom,:)
        CAll Mixed2Cart(nat,indzmat,geomtmp,GeomTmpC)
     END SELECT

     if (debug) WRITE(*,*) "Converting geom ",IGeom," into file ",Trim(POSCAR) // "_" // Line2(1:Idx) // AdjustL(TRIM(Line))

     WRITE(Title,'(A,I2,"/",I2)') Trim(Vasp_Title) // " - Geom ",IGeom-1,NGeomF-1

     Call PrintGeomVasp(Title,geomTmpC,Latr,FrozAtoms,IoTmp)

     CLOSE(IOTMP)
  END DO

  if (Vmd) THEN
     WRITE(IOOUT,*) "## Insert the following list into the Test_NEB_example.vmd file for an easy VMD use"

     Line2="00"
     WRITE(IOOUT,'(A)') TRIM(FirstWord) // " new " // TRIM(POSCAR) // "_00" // TRIM(LastWords)
     DO IGeom=2,NGeomF
        WRITE(Line,'(I5)') IGeom-1
        Idx=2-Len_TRIM(ADJUSTL(Line))
        WRITE(IOOUT,'(A)') TRIM(FirstWord) // " addfile " // TRIM(POSCAR) //  &
             "_" // Line2(1:Idx) // TRIM(ADJUSTL(Line)) // TRIM(LastWords)
     END DO
     WRITE(IOOUT,*) "## End of List"
  END IF

  if (debug) WRITE(*,*) '================  Write_VASP OVER ===================='
  DeALLOCATE(GeomTmpC, GeomTmp)

END SUBROUTINE Write_vasp
