#include <stdio.h>

#include "hello.decl.h"

CkChareID mid;
CProxy_Hello arr;
int nElem;

class HiMsg : public CMessage_HiMsg
{
  int data;
	 char foo[32];
};

class main : public Chare
{
public:
  main(CkMigrateMessage *m) {}
  main(CkArgMsg* m)
  {
    if(m->argc < 2) {
      CkAbort("Usage: hello <nElements>\n");
    }
    nElem = atoi(m->argv[1]);
    delete m;
    CkPrintf("Running Hello on %d processors for %d elements\n",
	     CkNumPes(),nElem);
    mid = thishandle;

    arr = CProxy_Hello::ckNew();

    for (int y=0;y<nElem;y++)
		 arr(37,y,2*y+1).insert();
    arr.doneInserting();

    arr(37,0,2*0+1).SayHi(new HiMsg);
  };

  void maindone(void)
  {
    CkPrintf("All done\n");
    CkExit();
  };
};

class Hello : public ArrayElement3D
{
public:
  Hello(CkMigrateMessage *m) {}
  Hello()
  {
    CkPrintf("Hello %d created\n",thisIndex.y);
  }

  void SayHi(HiMsg *m)
  {
    CkPrintf("Hi from element %d\n",thisIndex.y);
    if (thisIndex.y < nElem-1) {
      int y=thisIndex.y+1;
      arr(37,y,2*y+1).SayHi(m);
    } else {
      CProxy_main mproxy(mid);
      mproxy.maindone();
      delete m;
    }
  }
};

#include "hello.def.h"
