#include "kanjiquiz.h"
#include "parse.h"

void quit(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
  exit(0);
}

static Widget TopShell;
static int cached = 0;

Widget GetTopShell(Widget w)
{

  if (cached)
    return TopShell;

  while (w && !XtIsWMShell (w))
    w = XtParent (w);
  cached = 1;
  return w;
}

void SetTopShell(Widget w)
{
  TopShell = w;
  cached = 1;
}

void DestroyShell(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
  Widget shell = (Widget)client_data;

  XtPopdown (shell);
  XtDestroyWidget (shell);
}

void DestroySLData(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
  sublesson *sub, *copy;

  sub = (sublesson *)client_data;
  copy = sub;
  while (copy != NULLSL) {
    free (copy->data);
    copy = copy->next; }
  sub->data = NULLSLDATA;
}

XmString MakeMixedString(char *str, char *sbf, char *dbf)
{
  XmString retval, retval2, temp;
  char txt[MAXLENGTH*MAXMEM]="";
  char c;
  int index = 0, jis = 0;

  c =str[index];
  retval = XmStringCreateLtoR ("", sbf);
  while ((c != '\0') && (index < ((MAXLENGTH * MAXMEM) + 1))) {
    if (c == '\033') {
      if (jis == 1) {
	jis = 0;
	temp = XmStringCreate (txt, dbf); }
      else {
	jis = 1;
	temp = XmStringCreateLtoR (txt, sbf); }
      retval2 = XmStringConcat (retval, temp);
      XmStringFree (retval);
      XmStringFree (temp);
      retval = XmStringCopy (retval2);
      XmStringFree (retval2);
      strcpy (txt, "");
      index += 3;
      c = str[index];  }
    else {
      strncat(txt, str+index, 1);
      index++;
      c = str[index];  }
  }
  if (strcmp (txt, "") != 0) {
    if (jis == 1) {
      temp = XmStringCreateLtoR (txt, dbf); }
    else {
      temp = XmStringCreateLtoR (txt, sbf); }
    retval2 = XmStringConcat (retval, temp);     
    XmStringFree (retval);
    XmStringFree (temp);
    retval = XmStringCopy (retval2);
    XmStringFree (retval2); }
  return (retval);
}


void downCase(char *str)
{
  int i, j;

  for (i=0; i<strlen(str); i++) {
    j = (int)str[i];
    if ((j > 64) && (j < 91)) {
      str[i] += 32;
    }
  }
}
 
int checkFile(char *fn)
{
  int fd, retval;
  char *fullFileName;

  fullFileName = (char *)malloc(strlen(KQDATADIR)+strlen(fn)+2);
  sprintf (fullFileName, "%s/%s", KQDATADIR, fn);

  fd = open(fullFileName, O_RDONLY);

  if (fd < 0) {
    retval = 0; }
  else {
    retval = 1; }

  close(fd);
  free(fullFileName);
  return retval;
}

void map_dialog(widget, client_data, call_data)
Widget widget;
XtPointer client_data;
XtPointer call_data;
{
  Position xpos=100, ypos=100;
  Dimension w, h;

  XtVaGetValues (widget, XmNwidth, &w,
		         XmNheight, &h,
		         NULL);

  if ((xpos + w) >= WidthOfScreen (XtScreen (widget)))
    xpos = 0;
  if ((ypos + h) >= HeightOfScreen (XtScreen (widget)))
    ypos = 0;
  
  XtVaSetValues (widget, XmNx, xpos,
		         XmNy, ypos,
		         NULL);
}





