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

double sum1(int count, ...) {
  void *handle, *fptr;
  int vacount, i;
  va_list ap;
  double d1, d2, retval = 0;

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

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

  va_start(ap, count);
  vacount = va_count(ap);
  // for-loop is used to call the chdl function multiple times 
  for(i = 0; i < vacount; i++) { 
    d1 = retval;
    d2 = va_arg(ap, double);
    dlrunfun(fptr, &retval, sum1, 2, d1, d2);
  }
  va_end(ap);

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