#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>

#include "sopnamsp.h"
#include "histinit.h"
#include "array.h"
#include "cxxcmplnk.h"
#include "pdlmgr.h"
#include "timing.h"

int main(int narg, char *arg[])
{
  if (narg < 3) {
    cout << " tcxxcmpldynl : test of  CxxCompilerLinker and PDynLinkMgr classes \n " 
	 << " Usage tcxxcmpldynl nomCC nomFunc \n" 
	 << "       For test, tcxxcmpldynl exacmplnk.cc exacmplnk \n" << endl;
    exit(0);
  }
  try {
    SophyaInit();
    InitTim();

    string flnm = arg[1];
    string oname, soname;
    int rc;

    CxxCompilerLinker cxx(true, false, false);
    cxx.SetVerbose(true);
    rc = cxx.Compile(flnm, oname);
    cout << " RC from cxx.Compile() = " << rc << " oname= " << oname << endl;
    rc = cxx.BuildSO(oname, soname);
    cout << " RC from cxx.BuildSO() = " << rc << " soname= " << soname << endl;
    PrtTim(" End of Compile-Link ");

    string funcname = arg[2];
    PDynLinkMgr dyl(soname, false);
    DlFunction f = dyl.GetFunction(funcname);  
    if (f != NULL) {
      cout << " DlFunction f linked OK - calling f() ... " << endl;
      f();
    } 
    else {
      cout << " ERROR linking DlFunction f !!! " << endl;
    }
  } 
 
  catch (PThrowable & exc) {
    cerr << " Catched Exception " << (string)typeid(exc).name()
         << " - Msg= " << exc.Msg() << endl;
  }
  catch (...) {
    cerr << " some other exception was caught ! " << endl;
  }

  PrtTim(" End of tcxxcmpldynl ");
}
