/*
 * gcc -Wall -I/usr/local/include -g tcl-convertto-double.c \
       -L/usr/local/lib -ltcl8.5 -Wl,-rpath,/usr/local/lib
 */

#include <tcl.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>

char* default_test[] = {
  "100", "200", "300"
};

int main(int argc, char** argv) {
  Tcl_Interp* interp = Tcl_CreateInterp();
  Tcl_Obj** values;
  Tcl_ObjType* doubleType = Tcl_GetObjType("double");
  int rc, i, testc;
  char** tests = 0;

  if (--argc > 0) {
    tests = ++argv;
    testc = argc;
  } else {
    tests = default_test;
    testc = sizeof(default_test) / sizeof(char*);
  }

  if ((values = (Tcl_Obj**) Tcl_Alloc(sizeof(Tcl_Obj*) * testc)) == NULL) {
    return 1;
  }

  for (i = 0; *tests; tests++, i++) {
    values[i] = Tcl_NewStringObj(*tests, strlen(*tests));
  }

  for (i = 0; i < testc; i++) {

    if ((rc = Tcl_ConvertToType(interp, values[i], doubleType)) != TCL_OK) {
      fprintf(stderr, "conversion error for %s\n", values[i]->bytes);
      return 1;
    }

    /* This fails under Tcl8.5 */
    assert(values[i]->typePtr == doubleType);
    
    printf("doubleValue = %f type=%s bytes=%s\n"
	   , values[i]->internalRep.doubleValue
	   , values[i]->typePtr->name
	   , values[i]->bytes);
  }
  return 0;
}
