#include "sopnamsp.h"
#include "machdefs.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <fstream>

#include <string>
#include <vector>

#include <typeinfo>

#include "tarrinit.h"
#include "array.h"
#include "sambainit.h"
#include "skyinit.h"

#include "pexceptions.h"
#include "cxxcmplnk.h"
#include "pdlmgr.h"
#include "timing.h"

/*!
  \ingroup PrgUtil
  \file runcxx.cc
  \brief \b runcxx: Compile and run simple C++ code using SOPHYA 

  \verbatim
  csh> runcxx -h
  PIOPersist::Initialize() Starting Sophya Persistence management service
  SOPHYA Version  1.6 Revision 6 (V_Mai2003) -- Jun 25 2003 12:01:04 cxx
  runcxx : compiling and running of a piece of C++ code
    Usage: runcxx [-compopt CompileOptions] [-linkopt LinkOptions]
                  [-tmpdir TmpDirectory] [-f C++CodeFileName]
                  [-inc includefile] [-inc includefile ...]
                  [-import modulename] [-import modulename ...]
                  [-uarg UserArg1 UserArg2 ...]
   if no file name is specified, read from standard input
   modulenames: SkyMap, Samba, SkyT, FitsIOServer, 
                LinAlg, IFFTW, XAstroPack
  \endverbatim
*/

typedef void (* DlFunctionOfVecStr) (vector<string> & args, int & rc);

static void Usage(bool fgerr);
static int  GetInput(string & codeflnm);
static int  FillCxxFile(string & codeflnm, string & cxxfile, 
			vector<string> & inc1, vector<string> & inc2);

/* --Fonction-- */
void Usage(bool fgerr)
{
  if (fgerr) 
    cout << " runcxx : Argument Error ! " << endl; 
  else
    cout << " runcxx : compiling and running of a piece of C++ code " << endl;
 
  cout << "   Usage: runcxx [-compopt CompileOptions] [-linkopt LinkOptions] \n"
       << "                 [-tmpdir TmpDirectory] [-f C++CodeFileName] \n"
       << "                 [-inc includefile] [-inc includefile ...] \n"
       << "                 [-import modulename] [-import modulename ...] \n"
       << "                 [-uarg UserArg1 UserArg2 ...] \n"
       << "   if no file name is specified, read from standard input \n" 
       << "   modulenames: SkyMap, Samba, SkyT, FitsIOServer, \n"
       << "                LinAlg, IFFTW, XAstroPack \n"
       << endl;

  exit(0);
}



/* --Main-- */
int main(int narg, char *arg[])
{
  //SambaInitiator smbinit;

  SophyaInit();
  InitTim();

  if ((narg > 1) && (strcmp(arg[1],"-h") == 0) ) Usage(false);


  // Decoding options   
  string codefile;
  string compoption;
  string linkoption;
  string tmpdir;

  bool fgco = false;
  bool fglo = false;
  bool fgcofn = false;
  bool fgtmp = false;

  vector<string> uarg;
  vector<string> inc1;
  vector<string> inc2;
  
  cout << " runcxx: Decoding command line options ... " << endl;
  for (int k=1; k<narg; k++)   {
    if (strcmp(arg[k], "-compopt") == 0)  {
      if (k == narg-1) Usage(true);
      fgco = true;  k++;
      compoption = arg[k];
    }
    else if (strcmp(arg[k], "-linkopt") == 0) {
      if (k == narg-1) Usage(true);
      fglo = true;  k++;
      linkoption = arg[k];
    }
    else if (strcmp(arg[k], "-tmpdir") == 0) {
      if (k == narg-1) Usage(true);
      fgtmp = true;  k++;
      tmpdir = arg[k];
    }
    else if (strcmp(arg[k], "-f") == 0) {
      if (k == narg-1) Usage(true);
      fgcofn = true;  k++;
      codefile = arg[k];
    }
    else if (strcmp(arg[k], "-inc") == 0) {
      if (k == narg-1) Usage(true);
      k++; inc2.push_back(arg[k]);
    }
    else if (strcmp(arg[k], "-import") == 0) {
      if (k == narg-1) Usage(true);
      k++; 
      if (strcmp(arg[k], "SkyMap") == 0)  inc1.push_back("skymap.h");
      else if (strcmp(arg[k], "Samba") == 0)  inc1.push_back("samba.h");
      else if (strcmp(arg[k], "SkyT") == 0)  inc1.push_back("skyt.h");
      else if (strcmp(arg[k], "FitsIOServer") == 0)  inc1.push_back("fitsioserver.h");
      else if (strcmp(arg[k], "LinAlg") == 0 )  inc1.push_back("intflapack.h");
      else if (strcmp(arg[k], "IFFTW") == 0)  inc1.push_back("fftwserver.h");
      else if (strcmp(arg[k], "XAstroPack") == 0)  inc1.push_back("xastropack.h");
    }

    else if (strcmp(arg[k], "-uarg") == 0) {
      if (k == narg-1) Usage(true);
      for(int kk=k+1; kk<narg; kk++)
	uarg.push_back(arg[kk]);
      break;
    }
    else Usage(true);
  }

  // Checking TMPDIR
  if (!fgtmp) {  // TMPDIR pas defini par option de ligne de commande
    char* varenv;
    if ( (varenv=getenv("TMPDIR")) != NULL )  { 
      tmpdir = varenv;
      fgtmp = true;
    }
  }
  if (tmpdir.length() > 0)
    if (tmpdir[tmpdir.length()-1] != '/') tmpdir += '/';
  
  int rc = 0;

  try {

    if (!fgcofn) {  // Pas de fichier specifie - Lecture de fichier sur stdin
      codefile = tmpdir + "aucode.icc";
      rc = GetInput(codefile);
    }
    string flnm;
    if (rc == 0) {
      flnm = tmpdir + "acxxrun.cc";
      rc = FillCxxFile(codefile, flnm, inc1, inc2);
    }

    PrtTim(" End of FillCxxFile ");

    string oname, soname;
    if (rc == 0) {
      CxxCompilerLinker cxx;
      if (fgtmp) cxx.SetTmpDir(tmpdir);
      if (fgco) cxx.AddCompileOptions(compoption);
      if (fglo) cxx.AddLinkOptions(linkoption);
      cxx.SetVerbose(true);

      rc = cxx.Compile(flnm, oname);
      cout << " RC from cxx.Compile() = " << rc << " oname= " << oname << endl;
      if (rc == 0) {
	rc = cxx.BuildSO(oname, soname);
	cout << " RC from cxx.BuildSO() = " << rc << " soname= " << soname << endl;
      }
      PrtTim(" End of Compile-Link ");
    }
    if (rc == 0) {
      string funcname = "runcxx_usercode";
      if (fgtmp) PDynLinkMgr::SetTmpDir(tmpdir);
      PDynLinkMgr dyl(soname);
      DlFunction f = dyl.GetFunction(funcname);  
      if (f != NULL) {
	cout << "DlFunctionOfVecStr  f linked OK - calling f(uarg) ... \n" << endl;
	DlFunctionOfVecStr fvs = (DlFunctionOfVecStr)f;
	int rcu = 0;
	fvs(uarg, rcu);
	cout << "\n RC from UserCode() = " << rcu << endl;
	rc = rcu;
      } 
      else {
	cout << " ERROR linking DlFunction f !!! " << endl;
      }
    }
  } 
 
  catch (PThrowable & exc) {
    cerr << " Catched Exception " << (string)typeid(exc).name()
         << " - Msg= " << exc.Msg() << endl;
  }
  catch (std::exception & sex) {
    cerr << " Catched std::exception " << (string)typeid(sex).name()
         << " - Msg= " << sex.what() << endl;
  }
  catch (...) {
    cerr << " some other exception was caught ! " << endl;
  }

  PrtTim(" End of runcxx ");
  return(rc);
}

/* --Fonction-- */
int  GetInput(string & codeflnm)
{
  cout << " runcxx/GetInput() : Type in your C++ code, \n" 
       << "     end with a blanck line OR <Cntl>D " << endl;
  int line = 0;
  ofstream os(codeflnm.c_str(),ios::out); 
  os << "\n" ; 
  bool fg = true;
  char buff[512];
  char * ret;
  while (fg) {
    printf("L%d ? ", line+1);
    fflush(stdout);
    buff[0] = '\0';
    ret = fgets(buff, 512, stdin);
    buff[511] = '\0';
    if (ret && ( (buff[0] != '\0') && (buff[0] != '\n') && (buff[0] != '\r')) ) { 
      os << buff << endl;  line++;
    }
    else fg = false;
  }
  os << "\n" ; 
  cout << " \n Total " << line << " lines copied to file " <<  codeflnm << endl;
  if (line > 0) return(0);
  else return(1);
}

/* --Fonction-- */
int  FillCxxFile(string & code, string & cxxfile, 
		 vector<string>& inc1, vector<string>& inc2)
{
  ofstream os(cxxfile.c_str(),ios::out); 
  
  os<<"#include \"machdefs.h\" \n"<<endl;

  os<<"//---- System et stdc++ include files \n"
    <<"#include <stdio.h> \n"
    <<"#include <stdlib.h> \n"
    <<"#include <math.h> \n"
    <<"#include <ctype.h> \n"
    <<"#include <string.h> \n"
    <<"#include <iostream> \n"
    <<"#include <fstream> \n"
    <<"#include <complex> \n"
    <<endl

    <<"#include <typeinfo> \n"
    <<"#include <string> \n"
    <<"#include <vector> \n"
    <<"#include <map> \n"
    <<"#include <functional> \n"
    <<"#include <list> \n"
    <<endl
    
    <<"//---- Sophya include files \n"
    <<"#include \"sopnamsp.h\" \n"
    <<"#include \"basetools.h\" \n"
    <<"#include \"systools.h\" \n"
    <<"#include \"sutils.h\" \n"
    <<"#include \"ntools.h\" \n"
    <<"#include \"array.h\" \n"
    <<"#include \"histats.h\" \n"
    <<endl;
  
  int ki;
  for(ki=0; ki<inc1.size(); ki++)
    os << "#include \"" << inc1[ki] << "\" \n" ;
  os << endl;
  for(ki=0; ki<inc2.size(); ki++)
    os << "#include \"" << inc2[ki] << "\" \n" ;
  os << endl;

  os<<"//---- function for Adding and displaying Objects  " << endl;
  os<<"//---- compatibility with piapp cxxexecutor  " << endl;
  os<<"void Keep_Object(AnyDataObj & obj, string const & nom) \n{ \n" 
    <<"  POutPersist pos(nom); \n"
    <<"  pos.PutObject(obj); \n"
    <<"} \n" << endl;

  os<<"//---- Objects and variables saving"<<endl
    <<"#define KeepObj(obj) Keep_Object(obj, #obj);"<<endl
    <<endl;

  os<<"//---- Displaying objects and command execution"<<endl;
  os<<"#define DisplayObj(obj, att) " 
    <<" cout << \"DisplayObj() available only in piapp \" << endl; " << endl;
  os<<"#define ExecuteCommand(cmd) "
    <<" cout << \"ExecuteCommand() available only in piapp \" << endl; " << endl;


  os << "extern \"C\" { \n" 
     << " void runcxx_usercode(vector<string>& arg, int & rc); \n" 
    //     << " void runcxx_usercode(); \n"
     << " } \n " << endl;
  
  os << "// ---- User Code function ----- \n" 
     << " void runcxx_usercode(vector<string>& arg, int & rc) \n" 
    //     << " void runcxx_usercode() \n" 
     << "{ \n"
     << "#include \"" << code << "\" \n"
     << "} \n" << endl;

  return(0);
}

