#include <civlc.cvh>
#include <stdio.h>
#include <comm.cvh>
#include <assert.h>
#include <seq.cvh>

#define ANY_SRC -1
#define NPROCS 3
$scope root = $here;
$gcomm gcomm;

void process(int place){
  $comm comm = $comm_create($here, gcomm, place);
  $message msg;

  if (place == 0){
    for (int i = 1; i < NPROCS; i++) {
      int msg_size;
      int buf;

      msg = $comm_dequeue(comm, ANY_SRC, 0);
      msg_size = $message_size(msg);
      $message_unpack(msg, &buf, msg_size);
      assert(buf >= 1 && buf < NPROCS);
      printf("root get %d\n", buf);	
    }
  } else {
    int size = sizeof(int);

    msg = $message_pack(place, 0, 0, &place, size);
    $comm_enqueue(comm, msg);
  }
  $comm_destroy(comm);
}

void main(){
  $message junkMsgs[];

  $seq_init(&junkMsgs, 0, NULL);	
  gcomm = $gcomm_create(root, NPROCS);
  $parfor(int i : 0 .. (NPROCS-1))
    process(i);
  $gcomm_destroy(gcomm, &junkMsgs);
}
