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

double sum2(int param, ...) {
  void *dlhandle, *fptr;
  va_list ap;
  int count, ii, ii2;
  float ff, ff2;
  double dd, dd2, retval = 0;

  /* load the dynamically loaded library */
  dlhandle = dlopen("libhello.dl", RTLD_LAZY);
  if(dlhandle == NULL) {
    fprintf(_stderr, "Error: %s(): dlopen(): %s\n",
                      __func__, dlerror());
    return -1;
  }

  /* get the address by function name */
  fptr = dlsym(dlhandle, "sum2_chdl");
  if(fptr == NULL) {
    printf("Error: %s(): dlsym(): %s\n", __func__, dlerror());
    return -1;
  }

  va_start(ap, param);
  count = va_count(ap);
  if(count == 0)
      dlrunfun(fptr, &retval, sum2, param);

  if(count >= 1) {
      ii = va_arg(ap, int);
      if(count == 1)
        dlrunfun(fptr, &retval, sum2, param, ii);
  }

  if(count >= 2) {
      ii2 = va_arg(ap, int);
      if(count == 2)
        dlrunfun(fptr, &retval, sum2, param, ii, ii2);
  }

  if(count >= 3) {
      ff = va_arg(ap, float);
      if(count == 3)
        dlrunfun(fptr, &retval, sum2, param, ii, ii2, ff);
  }

  if(count >= 4) {
      ff2 = va_arg(ap, float);
      if(count == 4)
        dlrunfun(fptr, &retval, sum2, param, ii, ii2, ff, ff2);
  }

  if(count >= 5) {
      dd = va_arg(ap, double);
      if(count == 5)
        dlrunfun(fptr, &retval, sum2, param, ii, ii2, ff, ff2, dd);
  }

  if(count >= 6) {
      dd2 = va_arg(ap, double);
      if(count == 6)
        dlrunfun(fptr, &retval, sum2, param, ii, ii2, ff, ff2, dd, dd2);
  }

  va_end(ap);
  return retval;
}
