#if defined HAVE_CONFIG_H
#include "config.h"
#endif

!!@LICENSE
!
MODULE gridxc_debugXC

! Initializes output files for debug info. J.M.Soler. Jan'2008

USE gridxc_moreParallelSubs, only: nodeString    ! Returns a string with a node number
USE gridxc_moreParallelSubs, only: copyFile      ! Copies a file to another node
USE gridxc_io,             only: io_assign     ! Get and reserve an available IO unit

  implicit none

PUBLIC &
  setDebugOutputUnit,   &! Sets debug output unit and opens it for debug output
  closeDebugOutputFile, &! Close debug output file and copies it to node 0
  udebug                 ! Output file unit for debug info

PRIVATE ! Nothing is declared public beyond this point

  character(len=*),parameter:: filePrefix = 'debugXC' ! Prefix of file name
  character(len=32),    save:: fileName  ! Output file name
  integer,              save:: udebug=0  ! Output file unit for debug info

CONTAINS

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

subroutine setDebugOutputUnit(myNode)
  ! Sets debug output unit and opens file for debug output

  implicit none

  integer, intent(in) :: myNode

  ! If already initialized, do nothing
  if (udebug>0) return

  write(fileName,"(a,i0,a)") trim(filePrefix)//".",myNode,'.out'
  ! Find an available output unit
  call io_assign( udebug )

  ! Open file
  open( udebug, file=fileName )
end subroutine setDebugOutputUnit

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

#ifdef HAVE_MPI
subroutine closeDebugOutputFile(comm)
#else
subroutine closeDebugOutputFile()
#endif

  ! Closes debug output file and copies it to node 0

  implicit none

#ifdef HAVE_MPI
  integer, intent(in) :: comm
  integer             :: mpierr
#endif

  integer:: iNode
  character(len=32):: nodeFileName
  integer :: Nodes

  close( unit=udebug )

#ifdef HAVE_MPI
  call MPI_Comm_Size(comm,Nodes,mpierr)
#else
  Nodes = 1
#endif

  ! Copy all debug.out* files to root node. Notice that in each call to
  ! copyFile, only node iNode will actually send its file to node=0
  do iNode = 1,Nodes-1
    nodeFileName = filePrefix//'.node'//nodeString(iNode)
    call copyFile( srcNode=iNode, srcFile=nodeFileName, &
                   dstNode=0,     dstFile=nodeFileName, &
                   writeOption='overwrite' )
  end do

end subroutine closeDebugOutputFile

END MODULE gridxc_debugXC
