#include "charm++.h"
#include <stdlib.h>

#include "main.h"

extern "C" {
#include "simplemsg.h"
};

CkChareID mainhandle;

main::main(CkArgMsg*)
{
  int i, j;
  CkGetChareID(&mainhandle);
  // create Test chare
  CProxy_Testcharm *testChare = new CProxy_Testcharm(new Msg, 0);
  // generate random message order
  CkPrintf("generating random message order\n");
  msgOrder = new int[NMSGS];
  genRandom = new unsigned char[NMSGS];
  for(i=0;i<NMSGS;i++)
    genRandom[i] = (unsigned char) 0;
  for(i=0;i<NMSGS;i++) {
    // CPrintf("generating: %d\r", i);
    while(1) {
      int next = (rand()%NMSGS);
      if(genRandom[next]==(unsigned char)1)
	continue;
      msgOrder[i] = next;
      genRandom[next] = 1;
      break;
    }
  }
  delete[] genRandom;
  CkPrintf("generated random message order\n");
  // Now send all messages
  starttests = CmiTimer();
  for(i=0;i<NMSGS;i++) {
    Msg *msg = new Msg;
    CkSetRefNum(msg, msgOrder[i]);
    msg->data = msgOrder[i];
    testChare->teststart(msg);
  }
}

void main::testend(Msg *msg)
{
  double endtests = CmiTimer();
  int i;
  if(msg->data==1) {
    CProxy_Testsdag *testChare = new CProxy_Testsdag(msg, 0);
    msg = new Msg;
    testChare->teststart(msg);
    CkPrintf("Charm++ test took %lf seconds\n", (endtests-starttests));
    starttests = CmiTimer();
    for(i=0;i<NMSGS;i++) {
      msg = new Msg;
      CkSetRefNum(msg, msgOrder[i]);
      msg->data = msgOrder[i];
      testChare->entry1(msg);
    }
  } else if(msg->data==2) {
    CProxy_Testthreads *testChare = new CProxy_Testthreads(msg, 0);
    CkPrintf("Sdag++ test took %lf seconds\n", (endtests-starttests));
    starttests = CmiTimer();
    for(i=0;i<NMSGS;i++) {
      SMsg *smsg = new SMsg;
      smsg->data = msgOrder[i];
      CsmTVSend(0, 1, &msgOrder[i], (void *)smsg, sizeof(SMsg));
    }
  } else {
    CkPrintf("Threads test took %lf seconds\n", (endtests-starttests));
    delete msg;
    CkExit();
  }
}

#include "main.def.h"
