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

typedef int (*FUNC)();
static ChInterp_t interp;
static int isvar = 0;
static void *FUNC_chdl_funptr;
static int FUNC_chdl_funarg(int i, int j)
{
   int retval;
   int k=1;
   int x=5;
   float f = 10;
   double d = 20;

   if(isvar) {
     ChVaList_t arglist;

     arglist = Ch_VarArgsCreate(interp);
     Ch_VarArgsAddArg(interp, &arglist, CH_INTTYPE, x);
     Ch_VarArgsAddArg(interp, &arglist, CH_FLOATTYPE, f);
     Ch_VarArgsAddArg(interp, &arglist, CH_DOUBLETYPE, d);
     Ch_CallFuncByAddr(interp, FUNC_chdl_funptr, &retval, i, j, arglist);
     Ch_VarArgsDelete(interp, arglist);
   }
   else
     Ch_CallFuncByAddr(interp, FUNC_chdl_funptr, &retval, i, j, k);

   return retval;
}

int chvaisfuncvararg(FUNC f, int i, int j)
{
     return f(i, j);
}

EXPORTCH int chvaisfuncvararg_chdl(void *varg)
{
   ChVaList_t ap;
   int i;
   int j;
   int count, num;
   int retval=-1;

   Ch_VaStart(interp, ap, varg);
   count = Ch_VaCount(interp, ap);
   printf("Total Args passed to chvaisfuncvararg_chdl() in C code = %d\n", count); 
   num = Ch_VaFuncArgNum(interp, ap);
   printf("Passed pointer to func in chvaisfuncvararg_chdl has %d arg\n", num);
   if(Ch_VaIsFuncVarArg(interp, ap)) {
     isvar = 1;
     printf("Passed pointer to func in chvaisfuncvararg_chdl has varaible number arg\n");
   }
   FUNC_chdl_funptr = Ch_VaArg(interp, ap, void *);
   i = Ch_VaArg(interp, ap, int);
   j = Ch_VaArg(interp, ap, int);

   if(FUNC_chdl_funptr != NULL) {
      retval = chvaisfuncvararg(FUNC_chdl_funarg, i, j);
   }
   else {
      printf("passed fun argument to chvaisfuncvararg_chdl() is NULL\n");
   }

   Ch_VaEnd(interp, ap);
   return retval;
}

