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

int chcallfuncbyaddr_2(int (*func)(array int &a)) { /* a is array of assumed shape and data type */
  void *handle, *fptr;
  int retval;

  handle = dlopen("libch.dl", RTLD_LAZY);
  if(handle == NULL) {
     printf("Error: %s(): dlopen(): %s\n", __func__, dlerror());
     return -1;
  }

  fptr = dlsym(handle, "chcallfuncbyaddr_2_chdl");
  if(fptr == NULL)  {
     printf("Error: %s(): dlsym(): %s\n", __func__, dlerror());
     return -1;
  }

  dlrunfun(fptr, &retval, chcallfuncbyaddr_2, func);
 
  if(dlclose(handle)!=0) {
     printf("Error: %s(): dlclose(): %s\n", __func__, dlerror());
     return -1;
  }

  return retval;
}

int func(array int &a) {
  int j, k;
  int r = (int)shape(shape(a)), n;
  array int dim[r];

  dim = shape(a);
  n = dim[0];

  printf("In func():\n");

  if(r==1) { /* passed 1-dim array */
    int *p;

    p = (int *)&a;
    for(j=0; j<n; j++) {
      printf("p[%i] = %3d\n", j, p[j]);
      p[j] *= 2;
    }
  }
  else if(r==2) { /* passed 2-dim array */
    int (*p2)[:], m = dim[1];
    array int (*p3)[:];

    p2 = (int [n][m])a;
    for(j=0; j<n; j++) {
      for(k=0; k<m; k++) {
        printf("p2[%i][%i] = %3d ", j, k, p2[j][k]);
        p2[j][k] *= 2;
      }
      printf("\n");
    }
    p3 = (array int [:][:])a;
    p3 = 2*p3;  
  }
  return 0;
}

int main() {
  chcallfuncbyaddr_2(func);
}
