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

typedef int (*FUNC)(int num, ...);
extern int func1(FUNC);

static ChInterp_t interp;
static void *func_chdl_funptr;
static int func_chdl_funarg(int num, ...) {
    int retval;
    int j;
    float f;
    double d;
    ChVaList_t ap_ch, ap;

    va_start(ap, num);
    ap_ch = Ch_VarArgsCreate(interp);
    if(num>=1) {
      j = va_arg(ap, int);
      Ch_VarArgsAddArg(interp, &ap_ch, CH_INTTYPE, j);
    }
    if(num>=2) {
      d = va_arg(ap, double);
      Ch_VarArgsAddArg(interp, &ap_ch, CH_DOUBLETYPE, d);
    }
    Ch_CallFuncByAddr(interp, func_chdl_funptr, &retval, num, ap_ch);  
    Ch_VarArgsDelete(interp, ap_ch);
    return retval;
}

EXPORTCH int func1_chdl(void *varg)
{
   ChVaList_t ap;
   int count, num;
   int retval;

   Ch_VaStart(interp, ap, varg);
   count = Ch_VaCount(interp, ap);
   printf("Total args passed to func1_chdl() in C code = %d\n", count); 
   num = Ch_VaFuncArgNum(interp, ap);
   if(num == INT_MAX)
     printf("Passed pointer to func in func1_chdl has variable number arg\n");
   else 
     printf("Passed pointer to func in func1_chdl has %d arg\n", num);
   func_chdl_funptr = Ch_VaArg(interp, ap, void *);

   if(func_chdl_funptr != NULL) {
      retval = func1(func_chdl_funarg);
   }
   else {
      printf("passed fun argument to func1_chdl() is NULL\n");
   }

   Ch_VaEnd(interp, ap);
   return retval;
}

