#include <hpcxx_rts.h>
#include <iostream.h>
#include <unistd.h>
#include <sys/param.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"

// Globals
static HPCxx_GlobalPtr<CFakeData> gp_; 
char hostname[MAXHOSTNAMELEN];
HPCxx_Sync<int> x;

// This function releases the main procees waiting on a sync variable;
int Kill(int i) 
{
  cout << "Kill Function" << endl;
  x = i;
  return 0;
}

// Function to access the global pointer
HPCxx_GlobalPtr<CFakeData> GetGP() 
{
  cout << "Accessing Global Pointer" << endl;
  return gp_;
}

// Attach Callback -- Invoked when a client attaches
void attach(void *noting) {
  cout << "Got Attach Request!" << endl;
}
  
// Main
int main(int argc, char** argv) {
  HPCxx_Group*         g;
  CFakeData             class_data;
  int                  port = 0;

  cout << "Slave Started!" << endl;
  
  class_data.Init(5); // Initialize the array to 5

  hpcxx_init(argc, argv, g);  
  hpcxx_registerClass((CFakeData *)NULL);
  HPCxx_GlobalPtr<CFakeData> gp(&class_data);

  gp_ = gp;  // Bind the global GP to the local GP.  So others can get access to it.

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

  if ((port = hpcxx_allowAttach(port,attach,NULL)) == -1) {
    cerr << "Not allowed access to port " << port << endl;
    exit(1);
  }
  gethostname(hostname,MAXHOSTNAMELEN);
  
  if (!WriteUrlToFile("./url.out",hostname,port)) {
    cerr << "Error: Can't write url file!" << endl;
    exit(1);
  }

  int sync_val = 1;
  x.read(sync_val); // Wait to be released
  
  cout << "Slave All done... bye bye. " << endl;
  hpcxx_exit(g);
}



