#!/bin/sh

if [ x"$1" = x"-tcl" ]; then
  DOTCL=1
else
  DOTCL=0
fi

awk '
BEGIN{
  dotcl='$DOTCL'
  if( dotcl == 0 ){
    printf("#include <mainlib.h>\n\n")
  }
  else{
    printf("#include <tclmainlib.h>\n\n")
  }
  printf("\n");
  j = 0
}
{
  for(i=1; i<=NF; i++){
    name[j] = $i
    printf("int %s_main _PRx((int argc, char **argv));\n", $i)
    j++
  }
}
END{
  if( dotcl == 0 ){
    printf("\n")
    printf("void *funtoolsMainLibInit(void)\n")
    printf("{\n")
    printf("  MainLib ml;\n")
    printf("  if( !(ml=MainLibNew()) )\n");
    printf("     return NULL;\n");
    for(i=0; i<j; i++){
      printf("  if( !MainLibAdd(ml, \"funtools\", \"%s\", %s_main, MAINLIB_ARGV) )\n", name[i], name[i])
      printf("     return NULL;\n");
    }
    printf("  return ml;\n");
    printf("}\n")
    printf("\n")
  }
  else{
    printf("\n")
    printf("#include <tcl.h>\n")
    printf("\n")
    printf("int Tclfun_Init (void *vinterp)\n")
    printf("{\n")
    printf("  Tcl_Interp *interp = (Tcl_Interp *)vinterp;\n")
    printf("\n")
    for(i=0; i<j; i++){
      printf("  Tcl_CreateObjCommand(interp, \"%s\", MainLibProcess_Tcl,\n", name[i])
      printf("    (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL);\n")
    }
    printf("  Tcl_CreateObjCommand(interp, \"mainlib\", MainLibProcess_Tcl,\n")
    printf("    (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL);\n")
    printf("  Tcl_CreateObjCommand(interp, \"mainlibcleanup\", MainLibProcessCleanup_Tcl,\n")
    printf("    (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL);\n")
    printf("  Tcl_CreateObjCommand(interp, \"mainlibload\", MainLibLoad_Tcl,\n")
    printf("    (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL);\n")
    printf("  Tcl_PkgProvide(interp, \"tclfun\", \"1.0\");\n")
    printf("  return(TCL_OK);\n")
    printf("}\n")
    printf("\n")
  }
}
'
