#include <hpcxx_rts.h>
#include <iostream.h>

#include <HPCxx_Sync.cc>
#include <hpcxx_invoke.cc>
#include <hpcxx_register.cc>
#include <HPCxx_GlobalPtr.cc>
#include <hpcxx_invokeImpl.cc>
#include <HPCxx_GlobalRefImpl.cc>

#include "FakeData.h"
#include "util.h"

typedef unsigned short ushort;

// Globals
char host[60];
ushort port = 0;

// Stub -- Never called in this context
int Kill(int i) {
  return 0;
}

// Stub -- Never called in this context
HPCxx_GlobalPtr<CFakeData> GetGP() 
{
  return NULL;
}


int main(int argc, char** argv) {
  HPCxx_Group* g;
  CFakeData    class_data;
  int ret = 0, param1 = 0;

  class_data.Init(1); // Init the array to 1

  cout << "Master Started. " << endl;

  hpcxx_init(argc, argv, g);  
  hpcxx_registerClass((CFakeData *)NULL);
  HPCxx_GlobalPtr<CFakeData> gp(&class_data); // I guess you must preallocate space?

  // Register out functions
  hpcxx_id_t kill_id = hpcxx_register(Kill,20);
  hpcxx_id_t get_gp  = hpcxx_register(GetGP,21);

  if (!ReadUrlFile("./url.out",host,&port))
    exit(1);
  
  /* Get the other processes context ID */
  HPCxx_ContextID *remote = hpcxx_grabContext(host, port);

  if (remote == NULL) {
    cout << "Error attaching to other process!" << endl;
    exit(1);
  }

  cout << "Invoking Remote Function!" << endl;
  hpcxx_invoke(*remote, gp, get_gp);  // Get the global pointer in the other context.
  cout << "Got Global Pointer!  Attempting to Read...." << endl;

  class_data.Print();
  gp.read(&class_data,1);
  class_data.Print();


  hpcxx_invoke(*remote, ret, kill_id, param1);
  hpcxx_destroyContextID(remote);
  cout << "Master All done.... bye bye." << endl;
  hpcxx_exit(g);
}

