/*
   This code implements the testmodel program. This program can be
   used to test user metamodels. It will build the metamodel based on
   a few fixed points, and then calculate the function value for a few
   other points.

   Syntax:
      testmodel <name>
   
   (where <name> is the name of the metamodel, without the umm_ prefix
    and any platform-specific suffix)

   Livermore Software Technology Corporation (LSTC) holds the copyright
   for this code. LSTC hereby grants anyone the right to create and
   distribute derivative work based on this code under their own terms.
   
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
   GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
   BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE.

*/

#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>


# define SHAREDOBJECT HMODULE
# define EX_USAGE 1
# /* unix-style functions as defines for win32 */
# define dlopen(fn,flags) LoadLibrary(fn)
# define dlclose FreeLibrary
# define dlsym GetProcAddress
# define getcwd(buf,siz) GetCurrentDirectory(siz,buf)
#else

# include <dlfcn.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <unistd.h>
# include <stdlib.h>
# include <sysexits.h>

# define SHAREDOBJECT void*
#endif

# include <stdio.h>
#include <time.h>
#include <string.h>
#include "UserMetaModel.h"

#if defined(__gnu_linux__)
#  if defined(__i686__)
#    define ARCH "i686"
#  elif defined(__i586__)
#    define ARCH "i586"
#  elif defined(__i386__)
#    define ARCH "i386"
#  elif defined(__x86_64__)
#    define ARCH "x86_64"
#  elif defined(__ia64__)
#    define ARCH "ia64"
#  elif defined(__alpha__)
#    define ARCH "alpha"
#  elif defined(__mips__)
#    define ARCH "mips"
#  elif defined(__mipsel__)
#    define ARCH "mipsel"
#  elif defined(__m68k__)
#    define ARCH "m68k"
#  else
#    error "Unsupported architecture :-("
#  endif
#elif defined (_WIN32)
/* don't define anything' */
#else
#  error "Unsupported platform :-("
#endif

typedef void (*UMM_Init_fn)(UserMetaModel*);
typedef void (*UMM_CleanUp_fn)(UserMetaModel*);
typedef int (*UMM_GetConstantCount_fn)(UserMetaModel*, int);
typedef void (*UMM_Build_fn)(UserMetaModel*, double **,
                             double *,int);
typedef double (*UMM_FuncVal_fn)(UserMetaModel* , double *);
typedef double (*UMM_FuncGrad_fn)(UserMetaModel* , int , double *);

void (*UMM_Init)(UserMetaModel*);
void (*UMM_CleanUp)(UserMetaModel*);
double (*UMM_FuncVal)(UserMetaModel* , double *);
double (*UMM_FuncGrad)(UserMetaModel* , int , double *);
int (*UMM_GetConstantCount)(UserMetaModel*, int);
void (*UMM_Build)(UserMetaModel*, double **,
		  double *,int);


char* find_shared_object(const char* name)
{
#ifdef _WIN32
  HANDLE f;
  WIN32_FIND_DATA fd;
  char *n;

  n=malloc(strlen(name)+16);
  sprintf(n,"umm_%s_win32.dll",name);
  f = FindFirstFile(n,&fd);
  if (f == INVALID_HANDLE_VALUE) {
    free(n);
    return NULL;
  }
  FindClose(f);
  return n;
#else
  char *so;
  struct stat sb;
  char machine[16];
  
  so = malloc(strlen(name)+64);
  strcpy(machine,ARCH);

 tryname:
  sprintf(so,"./umm_%s_linux_%s.so",name,machine);
  
  if (stat(so,&sb)==0)
    return so;

  /* if iX86, try stepping back to previous architecture */
  if (machine[0]=='i' && machine[1]>'3' && 0 == strcmp("86",machine+2)) {
    machine[1]--;
    goto tryname;
  }
  
  return NULL;
#endif
}
#ifdef _WIN32
char* dlerror()
{
  static char buffer[256];
  FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), buffer,
    sizeof(buffer), NULL);
  return buffer;
}
#endif

UserMetaModel* CreateUserMetaModel() {
  UserMetaModel *ret = calloc(1,sizeof(UserMetaModel));
  static char cwd[1024];

  ret->size_lsopt = sizeof(UserMetaModel);
  getcwd(cwd,sizeof(cwd));
  ret->ummpath = cwd;
  return ret;
}

void HandleAnyError(UserMetaModel* mm)
{
  if (mm->error) {
    if (mm->error_message) {
      printf("%s\n",mm->error_message);
      if (mm->error & UMM_MUSTFREE)
	free(mm->error_message);
    } else
      printf("MetaModel returned an unspecified %s.\n",
	     mm->error & UMM_ERROR ? "error": "warning");

    if (mm->error & UMM_ERROR)
      exit(EXIT_FAILURE);
  }
}

void BuildUserMetaModel(UserMetaModel *mm) {

  double p0[] = { 0};
  double p1[] = { 1};
  double p2[] = { 2};
  double p3[] = { 3};
  double *x_case_good[] = {p0,p1,p2,p3};
  double funcvals_good[] = { 0,1,4,9 };

  	char cstring[256];
	time_t t;

    time(&t);
    srand((unsigned int)t);
	printf("%f sdjfkj",rand());

  /*double p0[] = { -1,-1};
  double p1[] = { -1, 1};
  double p2[] = { 1 ,-1};
  double p3[] = { 1 , 1};
  double *x_case_good[] = {p0,p1,p2,p3};
  double funcvals_good[] = { 1,2,3,4 };*/
  mm->numvar = 1;
  
  mm->error = UMM_NOERROR;
  mm->num_constants = UMM_GetConstantCount(mm,4);
  HandleAnyError(mm);
  mm->constants = (double*)malloc(sizeof(double)*mm->num_constants);
  UMM_Build(mm,x_case_good,funcvals_good,4);
  HandleAnyError(mm);
}

void CalcPoint(UserMetaModel* mm, double x)
{
  double v;
  double p[1];
  printf("f(%5.2f) = ",x);
  p[0]=x;
  mm->error = UMM_NOERROR;
  v = UMM_FuncVal(mm,p);
  HandleAnyError(mm);
  printf("%f\n",v);
}

int main(int argc, char **argv)
{
  char *fn;
  SHAREDOBJECT doh;
  UserMetaModel *mm;

  if (argc<2) {
    printf("Syntax: %s <modulename>\n", argv[0]);
    exit(EX_USAGE);
  }

  printf("Looking for module '%s'...\n",argv[1]);
  fn = find_shared_object(argv[1]);
  if (!fn) {
    printf("Module not found.\n");
    exit(EXIT_FAILURE);
  }
  printf("Found as %s\n",fn);

  doh = dlopen(fn,RTLD_LAZY);
  free(fn);
  if (!doh) {
    printf("Couldn't open shared object (dlopen failed): %s\n",dlerror());
    exit(EXIT_FAILURE);
  }
  
  UMM_Init = (UMM_Init_fn)dlsym(doh,"UserMetaModel_Init");
  if (!UMM_Init) {
    printf("Couldn't load UserMetaModel_Init symbol (dlsym failed):\n  %s\n",dlerror());
    exit(EXIT_FAILURE);   
  }

  UMM_GetConstantCount = (UMM_GetConstantCount_fn)dlsym(doh,"UserMetaModel_GetConstantCount");
  if (!UMM_GetConstantCount) {
    printf("Couldn't load UserMetaModel_GetConstantCount symbol (dlsym failed):\n  %s\n",dlerror());
    exit(EXIT_FAILURE);   
  }

  UMM_Build = (UMM_Build_fn)dlsym(doh,"UserMetaModel_Build");
  if (!UMM_Build) {
    printf("Couldn't load UserMetaModel_Build symbol (dlsym failed):\n  %s\n",dlerror());
    exit(EXIT_FAILURE);   
  }

  UMM_CleanUp = (UMM_CleanUp_fn)dlsym(doh,"UserMetaModel_CleanUp");
  if (!UMM_CleanUp) {
    printf("Couldn't load UserMetaModel_CleanUp symbol (dlsym failed):\n  %s\n",dlerror());
    exit(EXIT_FAILURE);   
  }

  UMM_FuncVal = (UMM_FuncVal_fn)dlsym(doh,"UserMetaModel_FuncVal");
  if (!UMM_FuncVal) {
    printf("Couldn't load UserMetaModel_FuncVal symbol (dlsym failed):\n  %s\n",dlerror());
    exit(EXIT_FAILURE);   
  }

  mm=CreateUserMetaModel();
  
  printf("Initializing...\n");
  UMM_Init(mm);
  HandleAnyError(mm);

  printf("Building MetaModel...\n");
  BuildUserMetaModel(mm);
  printf("Testing MetaModel '%s'\n",mm->description);

  CalcPoint(mm,0);
  CalcPoint(mm,1);
  CalcPoint(mm,4);
  CalcPoint(mm,6);

  printf("Cleaning up...\n");
  UMM_CleanUp(mm);
  free(mm->constants);
  free(mm);
  dlclose(doh);
  return 0;
}
