SUBROUTINE PrintGeomVasp(Title,geom,LatrLoc,FrozAt,IoUnit)

! this subroutine prints a cartesian geometry in the VASP POSCAR format

  Use Path_module
  Use Io_module

  IMPLICIT NONE

  CHARACTER(*), INTENT(IN) :: TITLE
  REAL(KREAL),INTENT(IN) :: LatrLoc(3,3),Geom(3*Nat)
  LOGICAL, INTENT(IN) :: FrozAt(Nat)
  INTEGER(KINT), INTENT(IN) :: IoUnit

  INTEGER(KINT) :: IGeom, Idx, Iat, I,J
  REAL(KREAL), ALLOCATABLE :: GeomTmpC2(:,:),GeomTmpC(:,:)
  REAL(KREAL) :: MRot(3,3)

  REAL(KREAL) :: X,Y,Z

  LOGICAL :: Debug

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

  debug=valid('printgeomvasp')
 if (debug) WRITE(*,*) '================ Entering PrintGeomVasp ===================='

  ALLOCATE(GeomTmpC2(Nat,3),GeomTmpC(3,Nat))

  GeomTmpC=reshape(Geom,SHAPE=(/3,Nat/),ORDER=(/2,1/))

     DO I=1,Nat
        Iat=Order(I)
!        if (debug) WRITE(*,*) "WriteVASP I,Order(I)",I,Iat
        GeomTmpC2(I,1:3)=GeomTmpC(1:3,Iat)
     END DO

     if (debug) THEN
        WRITe(*,*) Nat
        WRITe(*,*) "Original"
        DO I=1,Nat
           WRITE(*,'(1X,A4,3(1X,F12.6))') AtName(I), &
                x0_vasp(I),Y0_vasp(I),z0_vasp(I)
        END DO
        WRITE(*,*) Nat
        WRITe(*,*) "Before align"
        DO I=1,Nat
           WRITE(*,'(1X,A4,3(1X,F12.6))') AtName(I), &
                GeomTmpC2(I,1), GeomTmpC2(I,2), GeomTmpC2(I,3)
        END DO
     ENDIF


     IF ((COORD.EQ.'ZMAT').AND.(Nat.GE.4)) THEN
        Call  AlignPartial(Nat,x0_vasp,y0_vasp,z0_vasp,     &
             GeomTmpC2(1,1),GeomTmpC2(1,2),GeomTMPC2(1,3),       &
             FrozAt,MRot)
        if (debug) THEN
           WRITE(*,*) NAt
           WRITe(*,*) "Aligned ?"
           DO I=1,Nat
              WRITE(*,'(1X,A4,3(1X,F12.6))') AtName(I), &
                   GeomTmpC2(I,1), GeomTmpC2(I,2), GeomTmpC2(I,3)
           END DO
        ENDIF
     END IF

     ! We print the corresponding file
     WRITE(IOUNIT,'(A)') Trim(Title)
     WRITE(IOUNIT,'(1X,F18.14)') Vasp_Param
     WRITE(IOUNIT,'(3(1X,F21.16))')  Lat_a(1)/Vasp_param,Lat_a(2)/Vasp_param,Lat_a(3)/Vasp_param
     WRITE(IOUNIT,'(3(1X,F21.16))')  Lat_b(1)/Vasp_param,Lat_b(2)/Vasp_param,Lat_b(3)/Vasp_param
     WRITE(IOUNIT,'(3(1X,F21.16))')  Lat_c(1)/Vasp_param,Lat_c(2)/Vasp_param,Lat_c(3)/Vasp_param
     WRITE(IOUNIT,'(A)') TRIM(Vasp_Types)
     WRITE(IOUNIT,'(A)') TRIM(Vasp_comment)
     WRITE(IOUNIT,'(A)') TRIM(Vasp_direct)
     DO I=1,Nat
        X=0.
        Y=0.
        Z=0.
        DO J=1,3
           X=X+GeomTmpC2(I,J)*LatrLoc(1,J)
           Y=Y+GeomTmpC2(I,J)*LatrLoc(2,J)
           Z=Z+GeomTmpC2(I,J)*LatrLoc(3,J)
        END DO
        WRITE(IOUNIT,'(3F20.16,1X,3A4)') X,Y,Z,FFF(1:3,I)
     END DO

  DeALLOCATE(GeomTmpC2)
 if (debug) WRITE(*,*) '================  PrintGeomVasp OVER ===================='

END SUBROUTINE PrintGeomVasp
