#include "synctest.h"

void synctest_moduleinit(void) {}

void synctest_init(void) 
{
  CProxy_synctest_main::ckNew();
}

synctest_main::synctest_main(void) 
{
  count = 0;
  for (int i=0;i<NUMCHILDREN;i++) {
    synctest_InitMsg *s_im = new synctest_InitMsg;
    s_im->initValue = i+1;
    s_im->myMain = thishandle;
    CProxy_synctest_child::ckNew(s_im);
  }
}

void synctest_main::reply(synctest_ReplyMsg *s_rm) 
{
  children[count] = s_rm->childID;
  delete s_rm;
  count++;
  if (count == NUMCHILDREN) {
    CProxy_synctest_main mainproxy(thishandle);
    mainproxy.doTest();
  } 
}

void synctest_main::doTest(void)
{
  int sum = 0;
  synctest_SyncRecvMsg *childValue;

  for (int i=0;i<NUMCHILDREN;i++) {
    CProxy_synctest_child childproxy(children[i]);
    childValue = childproxy.test(new synctest_SyncSendMsg);
    sum = sum + childValue->value;
    delete childValue;
  }
  if (sum != (NUMCHILDREN * (NUMCHILDREN + 1))/2) {
    CkError("synctest failed!\n");
  }
  delete this;
  finishTest();
}

synctest_child::synctest_child(synctest_InitMsg *s_im)
{
  value = s_im->initValue;
  myMain = s_im->myMain;
  delete s_im;
  CProxy_synctest_main mainproxy(myMain);
  synctest_ReplyMsg *myReply = new synctest_ReplyMsg;
  myReply->childID = thishandle;
  mainproxy.reply(myReply);
}

synctest_SyncRecvMsg *synctest_child::test(synctest_SyncSendMsg *s_ssm)
{
  if (s_ssm->check() == 0)
    CkError("Message to sync method corrupted!");
  delete s_ssm;
  synctest_SyncRecvMsg *returnMsg = new synctest_SyncRecvMsg;
  returnMsg->value = value;
  return returnMsg;
}
  
#include "synctest.def.h"
