#include "groupcast.h"

void groupcast_moduleinit(void) {}

void groupcast_init(void) 
{
  CProxy_groupcast_main::ckNew();
}

groupcast_main::groupcast_main(void) 
{
  count = 0;
  groupcast_SimpleMsg *sm = new groupcast_SimpleMsg;
  sm->mainhandle = thishandle;
  CProxy_groupcast_group::ckNew(sm);
}

void groupcast_main::reply(groupcast_SimpleMsg *em) {
  gid = em->gid;
  delete em;
  count++;
  if (count == CkNumPes()) {
    CProxy_groupcast_group groupproxy(gid);
    groupcast_BCMsg *g_bcm = new groupcast_BCMsg;
    groupproxy.doBroadcast(g_bcm);
  } else if (count == CkNumPes()*2) {
      delete this;
      finishTest();
  }
}

groupcast_group::groupcast_group(groupcast_SimpleMsg *sm) {
  myMain = sm->mainhandle;
  sm->gid = thisgroup;
  CProxy_groupcast_main mainproxy(myMain);
  mainproxy.reply(sm);
}

void groupcast_group::doBroadcast(groupcast_BCMsg *bcm) {
  if (!bcm->check()) {
    CkError("Broadcasted message fails check.\n");
    finishTest();
    return;
  }
  delete bcm;
  CProxy_groupcast_main mainproxy(myMain);
  groupcast_SimpleMsg *g_em = new groupcast_SimpleMsg;
  mainproxy.reply(g_em);
}

#include "groupcast.def.h"
