! ************************************************************** ! 
    program openf
! ************************************************************** !
!  Purpose: This is a driver routine used to open files in a 
!           location defined by a given system enviroment 
!           variable (envstring) with a given unit number (unitnum) 
!           with a file name (ctemp)
! 
!  Limitations: 
!           ctemp   <= clen (30)    -File name
!           workdir <= slen (70)    -Working directory 
!           cffoo   <= dlen (100)   -Filename + Working dir.
!
!  ERRORS: Written in unit number 1 (FORCED)
!
! ************************************************************** !
    implicit none
    integer, parameter :: slen = 70
    integer, parameter :: clen = 30 
    integer, parameter :: dlen = 100
    integer, parameter :: elen = 100
    integer :: envlen
    integer :: wlen
    integer :: ios
    integer :: flg
    integer :: unitnum
    character(len=clen) :: ctemp
    character(len=slen) :: workdir
    character(len=slen) :: envstring
    character(len=dlen) :: cffoo
    character(len=elen) :: errorstr

    character(len=dlen),external :: dir
    external envarc
    external fbuff
    unitnum = 1
    ctemp = "foo"
    envstring = 'STDOUT'

    envlen = len_trim(envstring)
    call envarc( envstring, envlen, workdir, slen, flg, errorstr, elen )
    if(flg.eq.-1) then
      write(1,*) 'ERROR - sub. openf: incompatible string length ',flg
      call fbuff() 
      stop
    endif
    if(flg.eq.-2) then
      write(1,*) 'ERROR - sub. openf: env. var does not exist ',flg
      call fbuff()
      stop
    endif
    if(flg.eq.-3) then
      write(1,*) 'ERROR - sub. openf: envarc mkdir error  ',errorstr,' ',flg
      call fbuff()
      stop
    endif
    if(flg.eq.-4) then
      write(1,*) 'ERROR - sub. openf:Problem mkdir ',errorstr,' ',flg
      call fbuff()
      stop
    endif
    if(flg.eq.-99) then
      write(1,*) 'ERROR - sub. openf:TRAP -99 '
      call fbuff()
      stop
    endif

    wlen = len_trim(workdir)
    if(workdir(wlen:wlen).ne."/") workdir(wlen+1:wlen+1)="/"
    cffoo=dir(workdir,ctemp)
    open(unit=unitnum,file=cffoo,iostat=ios)
    if(ios /= 0)then
      write(1,*) 'ERROR - sub. openf opening file ',cffoo
      call fbuff()
      stop
    endif
    write(1,*) 'FILE OPENED:',cffoo
    call fbuff()
    end
