/* Copyright (c) 2001-2009 by SoftIntegration, Inc. All Rights Reserved */
#include<dlfcn.h>
#include<array.h>

int callchvla_Nd(int (*fun)(array int &a)) {
  void *handle, *fptr;
  int retval;

  handle = dlopen("libcallchvla.dl", RTLD_LAZY);
  if(handle == NULL) {
     printf("Error: %s(): dlopen(): %s\n", __func__, dlerror());
     return -1;
  }
  fptr = dlsym(handle, "callchvla_Nd_chdl");
  if(fptr == NULL)  {
     printf("Error: %s(): dlsym(): %s\n", __func__, dlerror());
     return -1;
  }
  dlrunfun(fptr, &retval, callchvla_Nd, fun);
  if(dlclose(handle)!=0) {
     printf("Error: %s(): dlclose(): %s\n", __func__, dlerror());
     return -1;
  }
  return retval;
}

int sumNd(array int &a) { /* function to be called from C space */
  int i, totnum = 1, retval = 0;
  int dim = (int)shape(shape(a)); 
  array int ext[dim];

  ext = shape(a);
  for(i = 0; i < dim; i++) {
    printf("ext[%i] = %d\n", i, ext[i]);
    totnum *= ext[i];
  }
  array int aa [totnum];
  aa = (array int [totnum])a;
  for(i = 0; i < totnum; i++) {
     retval += aa[i];
  }
  return retval;
}

int main() {
  int sum_ret;
  int a[3][4] = { 1, 2, 3, 4,
                  5, 6, 7, 8,
                  9, 10, 11, 12};

  sum_ret = sumNd(a);
  printf("sumNd has been called from Ch space and returned %d\n\n", sum_ret);
  callchvla_Nd(sumNd); 
  return 0;
}
