subroutine nubeam_avg_bsource(numid,il_wrkpath)
! working with files related to beam ion birth source
! concatenate all  files from nubeam run as standalone program called from transp
!
  use nbi_com,only : workpath,runid,n_outtim,nbs_step
  use nbi_mpi_com
  use logmod
  use netcdf
  use execsystem  ! includes logmod

  implicit none

  integer, intent(in) :: numid
  logical, intent(in) :: il_wrkpath 
  character*9 cstep
  character*150 :: suffix_in,suffix_out  ! birth source filenames
                                                    ! files with "suffix_in" need to be concatenated
                                                    ! 
                                                    ! files with "suffix__out" will be created and incorparated
                                                    ! data will be written
  character*300 :: fname_av
  character*300 :: path_myidd0
  character*300, dimension(:), allocatable :: fname
  character*300 :: zcmd,fname_av0

  integer,dimension(:),allocatable :: icd_f
  integer :: ierr,icdf,i,ii,mpierr,i_err,ierr1
  logical :: il_conc

  ! manage fast ion birth source files
  call nbi_mpi_com_init
  if(myidd.ne.0.) return
  if(numid.le.0) return

  if(il_wrkpath) then
     suffix_in='_birth'
     suffix_out='_nubeam_birth'
  else
     suffix_in='_nubeam_birth'
     suffix_out='_birth'
  endif
  ierr=0
  
  if(numid.eq.1.and.(il_wrkpath)) then
     !this is call from nubeam_comp_exec
     !just rename the file
     ! file  ==  <runid>_nubeam_birth.cdf<nn>  --  to write data
     write(cstep,'(i5)') n_outtim
     call nbi_loc_cwd_myidd(workpath,path_myidd0,il_wrkpath)
     fname_av0=trim(path_myidd0)//trim(runid)//trim(suffix_in)//'.cdf'//trim(adjustl(cstep))
     fname_av=trim(path_myidd0)//trim(runid)//trim(suffix_out)//'.cdf'//trim(adjustl(cstep))
     zcmd='mv '//trim(fname_av0)//' '//trim(fname_av)
     i_err=jsystem(zcmd)
     return
  endif

  nbs_step=n_outtim
  if(nbs_step.le.0) return
  ! checking if is is a restar then check if file exists
  ! file  ==  <runid>_nubeam_birth.cdf<nn>  --  to write data
  write(cstep,'(i5)') numid
  call nbi_loc_cwd_myidd(workpath,path_myidd0,il_wrkpath)
  fname_av=trim(path_myidd0)//trim(runid)//trim(suffix_out)//'.cdf'//trim(adjustl(cstep))
  if(.not.il_wrkpath) then
     path_myidd0=trim(path_myidd0)//trim(workpath)
  endif
  ierr= nf90_open(trim(fname_av),nf90_nowrite,icdf) 

  if(ierr.eq.0) then
     !nothing to do, get ready for next outtim
     ierr= nf90_close(icdf)
     zcmd='rm -f '//trim(path_myidd0)//trim(runid)//trim(suffix_in)//'*'
     i_err=jsystem(zcmd)
     nbs_step=0 
     n_outtim=0
     call nbi_fld_state_update(trim(workpath)//trim(runid)//'_nbi_fld_state.cdf') ! see update
     return
  endif

  if(allocated(icd_f)) deallocate(icd_f)
  allocate(icd_f(nbs_step))

  if(allocated(fname)) deallocate(fname)
  allocate(fname(nbs_step))

  fname_av0=trim(path_myidd0)//trim(runid)//trim(suffix_in)//'.cdf' 
  ! avereged procedure needed
  ! in case of restar -- check if filew concatenated already 
  ! trying to open file
  ! <runid>_birth_cpu_<myidd>_<numprocd>.cdf
  il_conc=.false.

  ! checking if there are files to concatenate
  
  i_err=0
  
  do i=1,nbs_step
     write(cstep,'(i5)') i
     fname(i)=trim(fname_av0)//trim(adjustl(cstep))
     ! trying to open file
     ! <runid>_birth.cdf<nn>
     ierr1 = nf90_open(trim(fname(i)),nf90_nowrite,icd_f(i))   
     if(ierr1.ne.0) then
        call warnlog(' nubeam_avg_bsource: data missing or error to open file'//trim(fname(i)))
        i_err=i_err+1
     endif
  enddo
  !check if all files are missing.
  if(i_err.gt.0.and.i_err.ne.nbs_step) then
     ! some files have been missed -- exit
     call errorlog(' nubeam_avg_bsource: some files have been missed')
     call bad_exit("nubeam_avg_bsource : data missing or file open failed")
  elseif(i_err.eq.nbs_step) then !all files are missed or delted due to 
     !fname_av has been moved to myidd=0 directory. 
     il_conc=.true.
  elseif(i_err .eq.0) then
     il_conc=.false.
  endif
  i_err=0
  if(.not.il_conc) then
     !all files are present and opened, need to be concatenate
     !files need to be concatenated here, over all nbs_step, on each cpu
     if(nbs_step.eq.1) then
        i_err=nf90_close(icd_f(1))
        zcmd='mv '//trim(fname(1))//' '//trim(fname_av)
        i_err=jsystem(zcmd)
        if(i_err.ne.0) then
           call errorlog(' nubeam_avg_bsource: error to move file on myidd=',myidd)
           call fdelete(fname(1),i_err)
           call bad_exit("nubeam_avg_bsource: error to move file")
        endif
     else
        !if file "fname_av" exists it will be overwritten.
        call nbi_bsource_conct(nbs_step,icd_f,trim(fname_av),ierr)
        
        if(ierr.ne.0) then
           call errorlog(' nubeam_avg_bsource: error to concatenate files on myidd=',myidd)
           do ii=1,nbs_step
              !close  opened files before exit
              ierr=nf90_close(icd_f(ii))
           enddo
           call bad_exit("nubeam_avg_bsource: unable to concatenate files on cpu")
        endif
     endif
     
     !cleanup : close all files and delete them
     do ii=1,nbs_step
        ierr=nf90_close(icd_f(ii)) 
        call fdelete(fname(ii),ierr)
     enddo
     il_conc=.true.
     
     if(allocated(icd_f)) deallocate(icd_f)
     if(allocated(fname)) deallocate(fname)
  endif
! prepare nubeam to start new step 
  nbs_step=0 
  n_outtim=0
  !update nbs_step and n_outtim in states file (in case of  nubeam_comp_exec it already has been written)
  call nbi_fld_state_update(trim(workpath)//trim(runid)//'_nbi_fld_state.cdf') ! see update

     

end subroutine nubeam_avg_bsource
