/*
** Astrolog (Version 3.05) File: xdriver.c
** Initially programmed 10/23-29/1991.
**
** IMPORTANT: The planetary calculation routines used in this program
** have been Copyrighted and the core of this program is basically a
** conversion to C of the routines created by James Neely as listed in
** Michael Erlewine's 'Manual of Computer Programming for Astrologers',
** available from Matrix Software. The copyright gives us permission to
** use the routines for our own purposes but not to sell them or profit
** from them in any way.
**
** IMPORTANT: the graphics database and chart display routines used in
** this program are Copyright (C) 1991-1993 by Walter D. Pullen. Permission
** is granted to freely use and distribute these routines provided one
** doesn't sell, restrict, or profit from them in any way. Modification
** is allowed provided these notices remain with any altered or edited
** versions of the program.
*/

#include "astrolog.h"

#ifdef GRAPH

#ifdef X11
/* Size of the Astrolog X11 icon. These values are defined in xdata.c too. */

#define icon_width 63
#define icon_height 32
#endif

/* Macros to allocate a bitmap from free memory. */

#ifdef NOPC
#define BITMAPSIZE sizeof(bitmapstruct)
#else
#define BITMAPSIZE ((long)(BITMAPX >> 1)*(BITMAPY))
#endif

/* Global variables. */

#ifdef MSC
#define HIRESMODE _MAXRESMODE
#define LORESMODE _ERESCOLOR
struct videoconfig config;
int xscreen = HIRESMODE;
#endif


/*
*******************************************************************************
** X routines
*******************************************************************************
*/

#ifdef X11
/* Allocate a color from the present colormap. Given a string like "red" or */
/* "blue" allocate this color and return a value specifying it.             */

color XMakeColor(name)
char *name;
{
  XColor col;
  XParseColor(disp, cmap, name, &col);
  XAllocColor(disp, cmap, &col);
  return col.pixel;
}
#endif


/* Set up all the colors used by the program, i.e. the foreground and   */
/* background colors, and all the colors in the object arrays, based on */
/* whether or not we are in monochrome and/or reverse video mode.       */

XColorInit()
{
  int i;

#ifdef X11
  cmap = XDefaultColormap(disp, screen);
  for (i = 0; i < 16; i++)
    rgbind[i] = XMakeColor(rgbname[i]);
#endif
  on  = mainansi[!xreverse];
  off = mainansi[xreverse];
  hilite = xcolor ? mainansi[2] : on;
  gray   = xcolor ? mainansi[3] : on;
  for (i = 0; i <= 6; i++)
    maincolor[i]    = xcolor ? mainansi[i]    : on;
  for (i = 0; i <= 7; i++)
    rainbowcolor[i] = xcolor ? rainbowansi[i] : on;
  for (i = 0; i < 4; i++)
    elemcolor[i]    = xcolor ? elemansi[i]    : on;
  for (i = 0; i <= ASPECTS; i++)
    aspectcolor[i]  = xcolor ? aspectansi[i]  : on;
  for (i = 0; i <= TOTAL; i++)
    objectcolor[i]  = xcolor ? objectansi[i]  : on;
#ifdef WIN
  if (!xbitmap) {
#ifdef X11
    XSetBackground(disp, gc,   rgbind[off]);  /* Initialize X window colors. */
    XSetForeground(disp, pmgc, rgbind[off]);
#endif
    Xcolor(on);
  }
#endif
}


#ifdef WIN
/* This routine opens up and initializes a window and prepares it to be */
/* drawn upon, and gets various information about the display, too.     */

void XBegin()
{
#ifdef X11
  disp = XOpenDisplay(dispname);
  if (!disp) {
    fprintf(stderr, "%s: Can't open display.\n", appname);
    Terminate(1);
  }
  screen = DefaultScreen(disp);
  bg = BlackPixel(disp, screen);
  fg = WhitePixel(disp, screen);
  hint.x = hint.width = chartx; hint.y = hint.height = charty;
  hint.min_width = BITMAPX1; hint.min_height = BITMAPY1;
  hint.max_width = BITMAPX;  hint.max_height = BITMAPY;
  hint.flags = PPosition | PSize | PMaxSize | PMinSize;
  /*wmhint = XGetWMHints(disp, window);
  wmhint->input = True;
  XSetWMHints(disp, window, wmhint);*/
  depth = DefaultDepth(disp, screen);
  if (depth < 5) {
    xmono = TRUE;      /* Is this a monochrome monitor? */
    xcolor = FALSE;
  }
  root = RootWindow(disp, screen);
  if (xroot)
    window = root;     /* If -XB in effect, we'll use the root window. */
  else
    window = XCreateSimpleWindow(disp, DefaultRootWindow(disp),
      hint.x, hint.y, hint.width, hint.height, 5, fg, bg);
  pixmap = XCreatePixmap(disp, window, chartx, charty, depth);
  icon = XCreateBitmapFromData(disp, DefaultRootWindow(disp),
    icon_bits, icon_width, icon_height);
  if (!xroot)
    XSetStandardProperties(disp, window, appname, appname, icon, xkey, 0,
      &hint);

  /* We have two graphics workareas. One is what the user currently sees in */
  /* the window, and the other is what we are currently drawing on. When    */
  /* done, we can quickly copy this to the viewport for a smooth look.      */

  gc = XCreateGC(disp, window, 0, 0);
  XSetGraphicsExposures(disp, gc, 0);
  pmgc = XCreateGC(disp, window, 0, 0);
  XColorInit();                            /* Go set up colors. */
  if (!xroot)
    XSelectInput(disp, window, KeyPressMask | StructureNotifyMask |
      ExposureMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask);
  XMapRaised(disp, window);
  XSync(disp, 0);
  XFillRectangle(disp, pixmap, pmgc, 0, 0, chartx, charty);
#else
  _setvideomode(xscreen);
  if (_grstatus()) {
    fprintf(stderr, "%s: Can't enter graphics mode.\n", appname);
    Terminate(1);
  }
  _getvideoconfig((struct videoconfig far *) &config);
  if (config.numcolors < 16) {
    xmono = TRUE;
    xcolor = FALSE;
  }
  _remapallpalette((long far *) rgb);
  _setactivepage(0);
  _clearscreen(_GCLEARSCREEN);
  _setvisualpage(0);
  XColorInit();
#endif
}


/* Add a certain amount of time to the current hour/day/month/year quantity */
/* defining the present chart. This is used by the chart animation feature. */
/* We can add or subtract anywhere from 1 to 9 seconds, minutes, hours,     */
/* days, months, years, decades, centuries, or millenia in any one call.    */
/* This is mainly just addition to the appropriate quantity, but we have    */
/* to check for overflows, e.g. Dec 30 + 3 days = Jan 2 of Current year + 1 */

void AddTime(mode, num)
int mode, num;
{
  real toadd, h, m, j;

  toadd = (real)num;
  h = floor(F);
  m = FRACT(F)*100.0;
  if (mode == 1)
    m += 1.0/60.0*(real)toadd;    /* Add seconds. */
  else if (mode == 2)
    m += 1.0*(real)toadd;         /* add minutes. */

  /* Add hours, either naturally or if minute value overflowed. */

  if (m < 0.0 || m >= 60.0 || mode == 3) {
    if (m >= 60.0) {
      m -= 60.0; toadd = Sgn(toadd);
    } else if (m < 0.0) {
      m += 60.0; toadd = Sgn(toadd);
    }
    h += 1.0*(real)toadd;
  }

  /* Add days, either naturally or if hour value overflowed. */

  if (h >= 24.0 || h < 0.0 || mode == 4) {
    if (h >= 24.0) {
      h -= 24.0; toadd = Sgn(toadd);
    } else if (h < 0.0) {
      h += 24.0; toadd = Sgn(toadd);
    }
    D += 1.0*(real)toadd;
  }

  /* Add months, either naturally or if day value overflowed. */

  if (D > (j = (real)DayInMonth((int) M, (int) Y)) ||
      D < 1.0 || mode == 5) {
    if (D > j) {
      D -= j; toadd = Sgn(toadd);
    } else if (D < 1.0) {
      D += (real)DayInMonth(Mod12(((int) M) - 1), (int) Y); toadd = Sgn(toadd);
    }
    M += 1.0*(real)toadd;
  }

  /* Add years, either naturally or if month value overflowed. */

  if (M > 12.0 || M < 1.0 || mode == 6) {
    if (M > 12.0) {
      M -= 12.0; toadd = Sgn(toadd);
    } else if (M < 1.0) {
      M += 12.0; toadd = Sgn(toadd);
    }
    Y += 1.0*(real)toadd;
  }
  if (mode == 7)
    Y += 10.0*(real)toadd;      /* Add decades.   */
  else if (mode == 8)
    Y += 100.0*(real)toadd;     /* Add centuries. */
  else if (mode == 9)
    Y += 1000.0*(real)toadd;    /* Add millenia.  */
  F = h+m/100.0;                /* Recalibrate hour time. */
}


/* Print a list of every key that one can press in an X window to do a */
/* certain function, and a description of what it does. This list gets */
/* displayed whenever one presses the 'H' or '?' key in the window.    */

void DisplayKeys()
{
  sprintf(string, "\n%s window keypress options (version %s):", appname,
    VERSION);
  Prints(string);
  Prints(" Press 'H' or '?' to display this list of key options.");
  Prints(" Press 'p' to toggle pause status on or off.");
  Prints(" Press 'x' to toggle fg/bg colors on screen.");
  Prints(" Press 'm' to toggle color/monochrome display on screen.");
  Prints(" Press 'T' to toggle header info on current chart on screen.");
  Prints(" Press 'i' to toggle status of the minor chart modification.");
  Prints(" Press 'l' to toggle labeling of object points in chart.");
  Prints(" Press 'v' to display current chart positions on text screen.");
  Prints(" Press 'R' to toggle restriction status of minor objects.");
  Prints(" Press 'C' to toggle restriction status of minor house cusps.");
  Prints(" Press 'u' to toggle restriction status of uranian planets.");
  Prints(" Press 'U' to toggle restriction status of fixed stars.");
  Prints(" Press 's', 'h', 'f', 'F' to toggle status of sidereal zodiac,");
  Prints("        heliocentric charts, domal charts, and decan charts.");
  Prints(" Press 'O' and 'o' to recall/store a previous chart from memory.");
#ifdef X11
  Prints(" Press 'B' to dump current window contents to root background.");
#else
  Prints(" Press 'B' to resize chart display to full size of screen.");
#endif
  Prints(" Press 'Q' to resize chart display to a square.");
  Prints(" Press '<' and '>' to decrease/increase the scale size of the");
  Prints("       glyphs and the size of world map.");
  Prints(" Press '[' and ']' to decrease/increase tilt in globe display.");
  Prints(" Press 'N' to toggle animation status on or off. Charts will");
  Prints("       be updated to current status and globe will rotate.");
  Prints(" Press '!'-'(' to begin updating current chart by adding times.");
  Prints("       !: seconds, @: minutes, #: hours, $: days, %: months,");
  Prints("       ^: years, &: years*10, *: years*100, (: years*1000.");
  Prints(" Press 'r' to reverse direction of time-lapse or animation.");
  Prints(" Press '1'-'9' to set rate of animation to 'n' degrees, etc.");
#ifdef MSC
  Prints(" Press '1'-'9' to determine section of chart to show if clipped.");
#endif
  Prints(" Press 'V','L','A','Z','S','W','G','P' to switch to normal (_v),");
  Prints("       astro-graph (_L), grid (_g), local (_Z), space (_S),");
  Prints("       world (_XW), globe (_XG), and polar (_XP) modes.");
  Prints(" Press '0' to toggle between _Z & _Z0, and _XW & _XW0 modes.");
#ifdef MSC
  Prints(" Press 'tab' to toggle between graphics resolutions.");
#endif
  Prints(" Press 'q' to terminate the window and program.");
#ifdef X11
  Prints("\n Left   mouse button: Draw lines on chart in window.");
  Prints(" Middle mouse button: Print coordinates of pointer on world map.");
  Prints(" Right  mouse button: Terminate the window and program.");
#endif
}


/* These macros are used by the 'o' and 'O' keys to save chart information. */

#define STOREX  MonX = Mon; DayX = Day; YeaX = Yea; TimX = Tim; ZonX = Zon; \
  LonX = Lon; LatX = Lat
#define RECALLX Mon = MonX; Day = DayX; Yea = YeaX; Tim = TimX; Zon = ZonX; \
  Lon = LonX; Lat = LatX

/* This routine gets called after an X window is brought up and displayed   */
/* on the screen. It loops, processing key presses, mouse clicks, etc, that */
/* the window receives, until the user specifies they want to exit program. */

void XSpin()
{
#ifdef X11
  int xupdate = FALSE, xevent = TRUE;
#else
  int xupdate = TRUE, xevent = FALSE;
#endif
  int xbreak = FALSE, xpause = FALSE, xnew = FALSE, xcorner = 7,
    buttonx = 0, buttony = 0, dir = 1, length, i;
  real MonX, DayX, YeaX, TimX, ZonX, LonX, LatX, lon, lat;

  STOREX;
  while (!xbreak) {

#ifndef MSC
    /* First, make sure the window isn't too large or too small. */

    if (chartx < BITMAPX1) {
      chartx = BITMAPX1;
      xupdate = TRUE;
    } else if (chartx > BITMAPX) {
      chartx = BITMAPX;
      xupdate = TRUE;
    }
    if (charty < BITMAPY1) {
      charty = BITMAPY1;
      xupdate = TRUE;
    } else if (charty > BITMAPY) {
      charty = BITMAPY;
      xupdate = TRUE;
    }
#endif

    /* Some chart windows, like the world maps and aspect grids, should */
    /* always be a certian size, so correct if a resize was attempted.  */

    if (modex == 'l' || modex == 'w') {
      length = 360*SCALE+2;
      if (chartx != length) {
        chartx = length;
        xupdate = TRUE;
      }
      length = (90*2+1)*SCALE+2;
      if (charty != length) {
        charty = length;
        xupdate = TRUE;
      }
    } else if (modex == 'a') {
      if (chartx !=
        (length = (OBJECTS+(relation==1))*CELLSIZE*SCALE+1)) {
        chartx = length;
        xupdate = TRUE;
      } if (charty != length) {
        charty = length;
        xupdate = TRUE;
      }
    }

#ifdef MSC
    /* If in animation mode, ensure we are in the flicker free resolution. */

    if (xnow < 0 && xscreen == HIRESMODE) {
      xnow = -xnow;
      xscreen = LORESMODE;
      XBegin();
      chartx = config.numxpixels;
      charty = config.numypixels;
      if (chartx > charty)
        chartx = charty;
      chartx = (long)chartx * 480 / 350;
      xupdate = TRUE;
    }
#else
    if (xnow < 0)
      xnow = -xnow;
#endif

    /* Physically resize window if we've changed the size parameters. */

    if (xupdate) {
      xupdate = FALSE;
#ifdef X11
      XResizeWindow(disp, window, chartx, charty);
      XFreePixmap(disp, pixmap);
      pixmap = XCreatePixmap(disp, window, chartx, charty, depth);
#else
      if (config.numxpixels > chartx)
        buttonx = (config.numxpixels - chartx) >> 1;
      else {
        if (xcorner % 3 == 1)
          buttonx = 0;
        else if (xcorner % 3 == 0)
          buttonx = -chartx + config.numxpixels;
        else
          buttonx = -(chartx - config.numxpixels) / 2;
      }
      if (config.numypixels > charty)
        buttony = (config.numypixels - charty) >> 1;
      else {
        if (xcorner > 6)
          buttony = 0;
        else if (xcorner < 4)
          buttony = -charty + config.numypixels;
        else
          buttony = -(charty - config.numypixels) / 2;
      }
      _setviewport(buttonx, buttony, config.numxpixels, config.numypixels);
#endif
      xevent = TRUE;
    }

    /* Recast chart if the chart information has changed any. */

    if (xnew && (!xnow || xpause)) {
      xnew = FALSE;
      M = Mon; D = Day; Y = Yea; F = Tim; X = Zon; L5 = Lon; LA = Lat;
      CastChart(TRUE);
      xevent = TRUE;
    }
    if (xnow && !xpause)
      xevent = TRUE;

    /* Update the window if anything has changed since last time around. */

    if (xevent) {
      xevent = FALSE;

      /* If we're in animation mode, change the chart info appropriately. */

      if (xnow) {
        if (modex == 'w' || modex == 'g' || modex == 'p') {
          degree += dir;
          if (degree >= 360)      /* For animating globe display, add */
            degree -= 360;        /* in appropriate degree value.     */
          else if (degree < 0)
            degree += 360;
        } else {
          if (xnow == 10)
#ifdef TIME
            /* For the continuous chart update to present moment */
            /* animation mode, go get whatever time it is now.   */
            InputData("now")
#endif
              ;
          else {  /* Otherwise add on appropriate time vector to chart info. */
            M = Mon; D = Day; Y = Yea; F = Tim; X = Zon; L5 = Lon; LA = Lat;
            AddTime(xnow, dir);
          }
          Mon = M; Day = D; Yea = Y; Tim = F; Zon = X; Lon = L5; Lat = LA;
          CastChart(TRUE);
          if (relation) {
            for (i = 1; i <= total; i++)    /* Make sure animations    */
              planet2[i] = planet[i];       /* of relationship charts  */
            for (i = 1; i <= SIGNS; i++)    /* are reflected properly. */
              house2[i] = house[i];
          }
        }            /* Update window display with new chart. */
      }
#ifdef X11
      Xcolor(on);
      XFillRectangle(disp, pixmap, pmgc, 0, 0, chartx, charty);
#else
      if (config.numvideopages > 1)
        _setactivepage(_getactivepage() == 0);
      _clearscreen(_GCLEARSCREEN);
      DrawBlock(0, 0, chartx-1, charty-1, off);
#endif
      XChart();
#ifdef X11
      XSync(disp, 0);
      XCopyArea(disp, pixmap, window, gc, 0, 0, chartx, charty, 0, 0);
#else
      if (config.numvideopages > 1)
        _setvisualpage(_getactivepage());
#endif
    }

    /* Now process what's on the event queue, i.e. any keys pressed, etc. */

#ifdef X11
    if (XEventsQueued(disp, QueuedAfterFlush /*QueuedAfterReading*/ )) {
      XNextEvent(disp, &event);

      /* Restore what's on window if a part of it gets uncovered. */

      if (event.type == Expose && event.xexpose.count == 0) {
        XSync(disp, 0);
        XCopyArea(disp, pixmap, window, gc, 0, 0, chartx, charty, 0, 0);
      }
      switch (event.type) {

      /* Check for a manual resize of window by user. */

      case ConfigureNotify:
        chartx = event.xconfigure.width;
        charty = event.xconfigure.height;
        XFreePixmap(disp, pixmap);
        pixmap = XCreatePixmap(disp, window, chartx, charty, depth);
        xevent = TRUE;
        break;
      case MappingNotify:
        XRefreshKeyboardMapping(&event);
        break;

      /* Process any mouse buttons the user pressed. */

      case ButtonPress:
        buttonx = event.xbutton.x; buttony = event.xbutton.y;
        if (event.xbutton.button == Button1) {
          Xcolor(hilite);
          DrawPoint(buttonx, buttony, hilite);
          XSync(disp, 0);
          XCopyArea(disp, pixmap, window, gc, 0, 0, chartx, charty, 0, 0);
        } else if (event.xbutton.button == Button2 &&
          (modex == 'l' || modex == 'w') && degree == 0) {
          lon = 180.0-(real)(event.xbutton.x-1)/(real)(chartx-2)*DEGREES;
          lat =  90.0-(real)(event.xbutton.y-1)/(real)(charty-2)*181.0;
          printf("Mouse is at %s.\n", StringLocation(lon, lat, 60.0));
        } else if (event.xbutton.button == Button3)
          xbreak = TRUE;
        break;

      /* Check for user dragging any of the mouse buttons across window. */

      case MotionNotify:
        Xcolor(hilite);
        DrawLine(buttonx, buttony, event.xbutton.x, event.xbutton.y,
          hilite, 0);
        XSync(disp, 0);
        XCopyArea(disp, pixmap, window, gc, 0, 0, chartx, charty, 0, 0);
        buttonx = event.xbutton.x; buttony = event.xbutton.y;
        break;

      /* Process any keys user pressed in window. */

      case KeyPress:
        length = XLookupString(&event, xkey, 10, &key, 0);
        if (length == 1) {
          i = xkey[0];
#else
        if (kbhit()) {
          i = getch();
#endif
          switch (i) {
          case 'p':
            xpause = !xpause;
            break;
          case 'r':
            dir = -dir;
            break;
          case 'x':
            xreverse = !xreverse;
            XColorInit();
            xevent = TRUE;
            break;
          case 'm':
            if (!xmono) {
              xcolor = !xcolor;
#ifdef MSC
              _getvideoconfig((struct videoconfig far *) &config);
#endif
              XColorInit();
              xevent = TRUE;
            }
            break;
          case 'B':
#ifdef X11
            XSetWindowBackgroundPixmap(disp, root, pixmap);
            XClearWindow(disp, root);
#else
            chartx = config.numxpixels;
            charty = config.numypixels;
            xupdate = TRUE;
#endif
            break;
          case 'T':
            xtext = !xtext;
            xevent = TRUE;
            break;
          case 'i':
            bonus = !bonus;
            xevent = TRUE;
            break;
          case '<':
            if (scale > 100) {
              scale -= 100;
              xupdate = TRUE;
            }
            break;
          case '>':
            if (scale < 300) {
              scale += 100;
              xupdate = TRUE;
            }
            break;
          case '[':
            if (modex == 'g') {
              tilt = tilt > -90.0 ? tilt-11.25 : -90.0;
              xevent = TRUE;
            }
            break;
          case ']':
            if (modex == 'g') {
              tilt = tilt < 90.0 ? tilt+11.25 : 90.0;
              xevent = TRUE;
            }
            break;
          case 'Q':
            if (chartx > charty)
              chartx = charty;
            else
              charty = chartx;
#ifdef MSC
            if (xscreen == LORESMODE)
              chartx = (long)chartx * 480 / 350;
#endif
            xupdate = TRUE;
            break;
          case 'R':
            for (i = 11; i <= 15; i++)
              ignore[i] = !ignore[i];
            ignore[17] = !ignore[17]; ignore[20] = !ignore[20];
            xevent = TRUE;
            break;
          case 'C':
            operation ^= DASHC;
            for (i = C_LO; i <= C_HI; i++)
              ignore[i] = !ignore[i];
            xnew = TRUE;
            break;
          case 'u':
            operation ^= DASHu;
            for (i = U_LO; i <= U_HI; i++)
              ignore[i] = !ignore[i];
            xnew = TRUE;
            break;
          case 'U':
            universe = !universe;
            for (i = S_LO; i <= S_HI; i++)
              ignore[i] = !ignore[i];
            xnew = TRUE;
            break;
          case 's':
            operation ^= DASHs;
            xnew = TRUE;
            break;
          case 'h':
            centerplanet = centerplanet ? 0 : 1;
            xnew = TRUE;
            break;
          case 'f':
            operation ^= DASHf;
            xnew = TRUE;
            break;
          case 'F':
            operation ^= DASH3;
            xnew = TRUE;
            break;
          case 'o':
            STOREX;
            break;
          case 'O':
            RECALLX;
            xnew = TRUE;
            break;
          case 'l':
            label = !label;
            xevent = TRUE;
            break;
          case 'N':                      /* The continuous update animation. */
            xnow = xnow ? 0 : -10;
            break;
          case '!': xnow = -1; break;    /* These are the nine different     */
          case '@': xnow = -2; break;    /* "add time to chart" animations.  */
          case '#': xnow = -3; break;
          case '$': xnow = -4; break;
          case '%': xnow = -5; break;
          case '^': xnow = -6; break;
          case '&': xnow = -7; break;
          case '*': xnow = -8; break;
          case '(': xnow = -9; break;
          case 'V': modex = 'c'; xevent = TRUE; break;    /* Should we go    */
          case 'L': modex = 'l'; xevent = TRUE; break;    /* switch to a     */
          case 'A': modex = 'a'; xevent = TRUE; break;    /* new chart type? */
          case 'Z': modex = 'z'; xevent = TRUE; break;
          case 'S': modex = 's'; xevent = TRUE; break;
          case 'W': modex = 'w'; xevent = TRUE; break;
          case 'P': modex = 'p'; xevent = TRUE; break;
          case 'G': modex = 'g'; xevent = TRUE; break;
          case '0':
            exdisplay ^= DASHZ0 | DASHXW0;
            xevent = TRUE;
            break;
          case 'v':
#ifdef MSC
            _setvideomode(_DEFAULTMODE);
#endif
            ChartLocation(FALSE);
#ifdef MSC
            while (!kbhit());
            XBegin();
            xupdate = TRUE;
#endif
            break;
          case 'H': case '?':
#ifdef MSC
            _setvideomode(_DEFAULTMODE);
            _settextrows(43);
#endif
            DisplayKeys();
#ifdef MSC
            while (!kbhit());
            XBegin();
            xupdate = TRUE;
#endif
            break;
#ifdef MSC
          case '\t':
            if (xscreen == HIRESMODE)
              xscreen = LORESMODE;
            else
              xscreen = HIRESMODE;
            XBegin();
            chartx = config.numxpixels;
            charty = config.numypixels;
            if (chartx > charty)
              chartx = charty;
            if (xscreen == LORESMODE)
              chartx = (long)chartx * 480 / 350;
            xupdate = TRUE;
            break;
#endif
          case 'q': case ESCAPE: case '\3':
            xbreak = TRUE;
            break;
          default:
            if (i > '0' && i <= '9') {
#ifdef MSC
              if (xnow)
#endif
                /* Process numbers 1..9 signifying animation rate. */
                dir = (dir > 0 ? 1 : -1)*(i-'0');
#ifdef MSC
              else {
                /* If we aren't in animation mode, then 1..9 refers to the */
                /* clipping "quadrant" to use if chart size > screen size. */
                xcorner = i-'0';
                xupdate = TRUE;
              }
#endif
            }
          }  /* switch */
        }  /* if */
#ifdef X11
      default:
        ;
      }  /* switch */
    }  /* if */
#endif
  }  /* while */
}


/* This is called right before program termination to get rid of the window. */

void XEnd()
{
#ifdef X11
  XFreeGC(disp, gc);
  XFreeGC(disp, pmgc);
  XFreePixmap(disp, pixmap);
  XDestroyWindow(disp, window);
  XCloseDisplay(disp);
#else
  _setvideomode(_DEFAULTMODE);
#endif
}
#endif


/*
*******************************************************************************
** Main processing
*******************************************************************************
*/


/* Print a list of every command switch dealing with the graphics features  */
/* that can be passed to the program, and a description of what it does.    */
/* This is part of what the -H switch prints, if graphics were compiled in. */

void XDisplaySwitches()
{
  Prints(" _X: Create a graphics chart instead of displaying it as text.");
#ifdef WIN
  Prints(" _Xb: Create bitmap file instead of putting graphics on screen.");
#endif
  Prints(" _Xb[n,c,v,a,b]: Set bitmap file output mode to X11 normal,");
  Prints("     compacted, very compact, Ascii (bmtoa), or Windows bmp.");
  Prints(" _Xo <file>: Write output bitmap to specified file.");
#ifdef X11
  Prints(" _XB: Display X chart on root instead of in a separate window.");
#endif
  Prints(" _Xm: Create monochrome graphic instead of one in color.");
  Prints(" _Xr: Create chart graphic in reversed colors (white background).");
  Prints(" _Xw <hor> [<ver>]: Change the size of the chart graphic.");
  Prints(" _Xs <100,200,300>: Change the size of map or characters by n%.");
  Prints(" _Xi: Create chart graphic in slightly modified form.");
  Prints(" _XT: Inhibit display of chart info at bottom of graphic.");
  Prints(" _X1 <object>: Rotate wheel charts so object is at left edge.");
  Prints(" _X2 <object>: Rotate wheel charts so object is at top edge.");
#ifdef X11
  Prints(" _Xd <name>, _di[..] <name>: Open X window on specified display.");
#endif
  Prints(" _XW: Simply create an image of the world map.");
  Prints(" _XW0: Like _XW but do a non-rectangular Mollewide projection.");
  Prints(" _XP: Create just the world map, but from a polar projection.");
  Prints(" _XG [<degrees>]: Display the image of the world as a globe.");
#ifdef WIN
  Prints(" _Xn: Start up chart or globe display in animation mode.");
  Prints("Also, press 'H' while running for list of key press options.");
#endif
}


/* Process a command line switch passed to the program dealing with the      */
/* graphics features. This is just like the processing of each switch in the */
/* main program; however, here each switch has been prefixed with an 'X'.    */

int XProcess(argc, argv, pos)
int argc, pos;
char **argv;
{
  int i = 0, j;
  char c;

  switch (argv[0][pos]) {
  case 0:
    break;
  case 'W':
    if (argc > 1 && ((degree = atoi(argv[1])) || argv[1][0] == '0')) {
      i++;
      if (degree < 0 || degree > 359)
        BadVal("XW", degree);
    } else
      degree = 0;
    modex = 'w';
    if (argv[0][pos+1] == '0')
      exdisplay |= DASHXW0;
    autom = TRUE;
    break;
  case 'P':
    if (argc > 1 && ((degree = atoi(argv[1])) || argv[1][0] == '0')) {
      i++;
      if (degree < 0 || degree > 359)
        BadVal("XP", degree);
    } else
      degree = 0;
    modex = 'p';
    if (argv[0][pos+1] == '0')
      exdisplay |= DASHXP0;
    autom = TRUE;
    break;
  case 'G':
    if (argc > 1 && ((degree = atoi(argv[1])) || argv[1][0] == '0')) {
      i++;
      if (degree < 0 || degree > 359)
        BadVal("XG", degree);
      if (argc > 2 && ((tilt = atof(argv[2])) || argv[2][0] == '0')) {
        i++;
        if (tilt < -90.0 || tilt > 90.0)
          BadVal2("XG", tilt);
      }
    }
    modex = 'g';
    autom = TRUE;
    break;
  case 'b':
    c = CAP(argv[0][pos+1]);
    if (c == 'N' || c == 'C' || c == 'V' || c == 'A' || c == 'B')
      bitmapmode = c;
    xbitmap = TRUE;
    break;
#ifdef X11
  case 'B':
    xroot = TRUE;
    break;
#endif
  case 'm':
    xcolor = FALSE;
    break;
  case 'r':
    xreverse = TRUE;
    break;
  case 'w':
    if (argc <= 1)
      TooFew("Xw");
    chartx = atoi(argv[1]);
    if (argc > 2 && (charty = atoi(argv[2]))) {
      argc--; argv++;
      i++;
    } else
      charty = chartx;
    if (chartx < BITMAPY1 || chartx > BITMAPX)
      BadVal("Xw", chartx);
    if (charty < BITMAPY1 || charty > BITMAPY)
      BadVal("Xw", charty);
    i++;
    break;
  case 's':
    if (argc <= 1)
      TooFew("Xs");
    scale = atoi(argv[1]);
    if (scale >= 1 && scale <= 3)
      scale *= 100;
    else if (scale < 100 || scale > 300 || scale%100 > 0)
      BadVal("Xs", scale);
    i++;
    break;
  case 'i':
    bonus = TRUE;
    break;
  case 'T':
    xtext = FALSE;
    break;
  case '1':
    if (argc <= 1)
      TooFew("X1");
    xeast = atoi(argv[1]);
    if (xeast < 1 || xeast > TOTAL)
      BadVal("X1", xeast);
    i++;
    break;
  case '2':
    if (argc <= 1)
      TooFew("X2");
    xeast = atoi(argv[1]);
    if (xeast < 1 || xeast > TOTAL)
      BadVal("X2", xeast);
    xeast = -xeast;
    i++;
    break;
  case 'd':
    if (argc <= 1)
      TooFew("Xd");
    dispname = argv[1];
    i++;
    break;
#ifdef WIN
  case 'n':
    if (argc > 1 && (xnow = atoi(argv[1])))
      i++;
    else
      xnow = 10;
    if (xnow < 1 || xnow > 10)
      BadVal("Xn", xnow);
    break;
#endif
  case 'o':
    if (argc <= 1)
      TooFew("Xo");
    xbitmap = TRUE;
    for (j = 0; outputfile[j] = argv[1][j]; j++)
      ;
    i++;
    break;
  default:
    fprintf(stderr, "%s: Unknown switch -X%c\n", appname, argv[0][pos]);
    Terminate(1);
  }
  return i;    /* 'i' contains the value to be added to argc when we return. */
}


/* This is the main interface to all the graphics features. This routine     */
/* is called from the main program if any of the -X switches were specified, */
/* and it sets up for and goes and generates the appropriate graphics chart. */

void XAction()
{
  /* First figure out what graphic mode to generate the chart in, based on */
  /* various non-X command switches, e.g. -L combined with -X, -g combined */
  /* with -X, and so on, and determine the size the window is to be, too.  */

  if (modex == 'c' && (todisplay & DASHL) > 0)
    modex = 'l';
  else if (modex == 'c' && (todisplay & DASHg | todisplay & DASHm) > 0) {
    modex = 'a';
    chartx = charty = (OBJECTS + (relation == DASHr0))*CELLSIZE*SCALE + 1;
  } else if (modex == 'c' && (todisplay & DASHZ) > 0) {
    modex = 'z';
    /*if (!(exdisplay & DASHZ0)) {
      chartx = (360+12)*SCALE;
      charty = (90*2+12)*SCALE;
    }*/
  } else if (modex == 'c' && (todisplay & DASHS) > 0)
    modex = 's';
  if (modex == 'l' || modex == 'w') {
    chartx = 360*SCALE+2;
    charty = (90*2+1)*SCALE+2;
  }
  if (xbitmap) {                       /* Initialize bitmap or window. */
    Allocate(bm, BITMAPSIZE, bitmap);
    if (bm == NULL) {
      fprintf(stderr, "%s: Out of memory for bitmap.\n", appname);
      Terminate(1);
    }
    XColorInit();
  }
#ifdef WIN
  else
    XBegin();
#endif
  if (xroot || xbitmap)    /* Go draw the graphic chart. */
    XChart();
  if (xbitmap) {    /* Write bitmap to file if in that mode. */
    WriteFile();
    Deallocate(bm);
  }
#ifdef WIN
  else {
#ifdef X11
    if (xroot) {
      XSetWindowBackgroundPixmap(disp, root, pixmap);    /* Process -XB. */
      XClearWindow(disp, root);
    } else
#endif
      XSpin();    /* Window's up; process commands given to window now. */
    XEnd();
  }
#endif
}
#endif

/* xdriver.c */
