! Example taken from
! The Complete Compendium on Cooperative Computing using Coarrays.
! by Andrew Vaught
! http://www.g95.org/compendium.pdf
!

module myjob
  implicit none
  type input
    !...
  end type input
  type output
    !...
  end type output
contains
  subroutine run(in, out)
    type(input), intent(in) :: in
    type(output), intent(out) :: out
    !...
  end subroutine run
  subroutine load_inputs(inputs)
    type(input), allocatable, intent(out) :: inputs(:)
    !...
  end subroutine load_inputs
  subroutine save_output(outputs)
    type(output) :: outputs(:)
    !...
  end subroutine save_output
end module myjob

program runall
  use myjob
  implicit none
  type input_ptr
    type(input), allocatable :: p(:)
  end type input_ptr
  type output_ptr
    type(output), allocatable :: p(:)
  end type output_ptr
  integer :: j, t, next_job[*] = 1
  type(input_ptr) :: in_ptr[*]
  type(output_ptr) :: out_ptr[*]

  if (this_image() == 1) then
    call load_inputs(in_ptr % p)
    allocate(out_ptr % p(ubound(in_ptr % p, 1)))
    SYNC IMAGES(*)
  else
    SYNC IMAGES(1)
  endif
  t = ubound(in_ptr[1] % p, 1) ! t = Number of jobs
  do
    CRITICAL
      j = next_job[1]
      if (j <= t) next_job[1] = j + 1
    END CRITICAL
    if (j > t) exit
    call run(in_ptr[1] % p(j), out_ptr[1] % p(j))
  enddo
  if (this_image() == 1) then
    SYNC IMAGES(*)
    call save_output(out_ptr % p)
    deallocate(in_ptr % p, out_ptr % p)
  else
    SYNC IMAGES(1)
  endif
end program runall
