subroutine mat_files(lunit,iname,status)
integer :: lunit ! logical unit number
! if LUNIT is zero, return
! if LUNIT = standard input, return
! if LUNIT = standard output, return
! if LUNIT is positive, open the unit to file name INAME
! if LUNIT is negative, close the unit number
integer :: iname(GG_LINELEN) ! INAME = FILE NAME, 1 character per word
! how to know length of iname?
character(len=1024) :: name
character(len=*),optional :: status
character(len=20) :: status_local
integer :: ios
if(present(status))then
status_local=status
else
status_local='UNKNOWN'
endif
G_FILE_OPEN_ERROR=.false.
select case(lunit)
case(0) ! error catcher
case(stdin) ! if unit is standard input return
case(stdout) ! if unit is standard output return
case(8) ! diary file
call mat_buf2str(name,iname,GG_LINELEN)
call journal('O',trim(name)) ! open up trail file
case(:-1)
if(lunit.eq.-8)then
call journal('O','') ! close trail file
else ! if LUNIT is negative, close the unit
ios=0
flush(unit=-lunit,iostat=ios)
if(-lunit.ne.STDIN)then
close(unit=-lunit,iostat=ios)
endif
endif
case default ! ALL OTHER FILES
call mat_buf2str(name,iname,GG_LINELEN)
if(lunit.ne.STDIN)then
open(unit=lunit,file=name,status=status_local,iostat=ios) ! open a file
if(ios.ne.0)then ! general file open failure
call journal('OPEN failed on file '//name)
G_FILE_OPEN_ERROR=.true. ! set the flag a file error occurred
G_RIO=G_INPUT_LUN ! set current file to read input lines from/to G_INPUT_LUN
else
G_FILE_OPEN_ERROR=.false. ! set the flag a file error did not occur
endif
endif
end select
end subroutine mat_files