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

static ChInterp_t interp;
static void ptfun1_1_chdl_funarg();
static void *ptfun1_1_chdl_funptr; 

EXPORTCH void ptfun1_1_setHandle_chdl(void *varg){
  ChVaList_t ap;
  funcHandle handle_ch, handle_c;

  Ch_VaStart(interp, ap, varg);
  /* get and save the Ch function pointer */
  handle_ch = Ch_VaArg(interp, ap, funcHandle);   
  ptfun1_1_chdl_funptr = (void *)handle_ch;
  printf("\nin ptfun1_1_setHandle_chdl(), Ch function pointer is %p\n", 
          handle_ch);

  /* replace the Ch function pointer with the C one */
  if(handle_ch == NULL) { /* NULL pointer will not replaced */
    handle_c = NULL;
  }  
  else {
    handle_c = (funcHandle)ptfun1_1_chdl_funarg;
  }  

  printf("in ptfun1_1_setHandle_chdl(), \
the corresponding C function pointer is %p\n\n", handle_c);
  ptfun1_1_setHandle(handle_c);

  Ch_VaEnd(interp, ap);
}

EXPORTCH funcHandle ptfun1_1_getHandle_chdl(void *varg){
  ChVaList_t ap;
  funcHandle retval_c = NULL, retval_ch = NULL;

  Ch_VaStart(interp, ap, varg);

  retval_c = ptfun1_1_getHandle();
  if(retval_c == ptfun1_1_chdl_funarg) { /* check the consistency */
    retval_ch = (funcHandle)ptfun1_1_chdl_funptr;
  }

  printf("in ptfun1_1_getHandle_chdl(), \
the returned C function pointer %p\n", retval_c);
  printf("in ptfun1_1_getHandle_chdl(), \
Ch function pointer to be returned is %p\n\n", retval_ch);

  Ch_VaEnd(interp, ap);
  return retval_ch;
}

/**** C functions to replace Ch callback functions ****/
static void ptfun1_1_chdl_funarg() {
  Ch_CallFuncByAddr(interp, ptfun1_1_chdl_funptr, NULL);
}
