/*
 *      Axis.c
 *
 *      The AthenaTools Plotter Widget Set - Version 6.0
 *
 *      klin, Tue Jul  7 13:59:47 1992
 *      klin, Sat Aug 15 10:31:50 1992, patchlevel 4
 *                                      Changed <At/..> to <X11/At/..>.
 */
static char SCCSid[] = "@(#) Plotter V6.0  92/08/15  Axis.c";

/*

Copyright 1991 by Burdett, Buckeridge & Young Ltd.

All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of the firms, institutes
or employers of the authors not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

THE AUTHORS AND THEIR FIRMS, INSTITUTES OR EMPLOYERS DISCLAIM ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE AUTHORS AND THEIR FIRMS,
INSTITUTES OR EMPLOYERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

*/

/*
 * The simplest form of numeric axis.  This class calculates
 * endpoints, ticInterval, tic labels and positions, then lets the
 * AxisCore superclass handle all that mucking about with pixels.
 */

#include <X11/At/AxisP.h>

static void AxisInitialize P((AtAxisWidget, AtAxisWidget));
static void AxisDestroy P((AtAxisWidget));
static Boolean AxisSetValues P((AtAxisWidget, AtAxisWidget, AtAxisWidget));

static void AxisRangeProc P((AtAxisCoreWidget, double *, double *, double *, int *));
static void AxisCalcProc P((AtAxisCoreWidget));

/* The resources */

static double one = 1.0;
#define off(field) XtOffsetOf (AtAxisRec, axis.field)
static XtResource resources[] = {
  {
       XtNautoScale, XtCAutoScale,
       XtRBoolean, sizeof(Boolean),
       off(auto_scale), XtRImmediate, (XtPointer) True
  },
  {
       XtNroundEndpoints, XtCRoundEndpoints,
       XtRBoolean, sizeof(Boolean),
       off(round_endpoints), XtRImmediate, (XtPointer) True
  },
  {
       XtNticDensity, XtCTicDensity,
       XtRInt, sizeof(int),
       off(tic_density), XtRImmediate, (XtPointer) 0
  },
  {
       XtNsubticDensity, XtCTicDensity,
       XtRInt, sizeof(int),
       off(subtic_density), XtRImmediate, (XtPointer) 0
  },
  {
       XtNticMultiplier, XtCTicMultiplier,
       XtRDouble, sizeof(double),
       off(tic_multiplier), XtRDouble, (XtPointer) &one
  },
  {
       XtNticFormat, XtCTicFormat,
       XtRString, sizeof(String),
       off(tic_format), XtRImmediate, "%.1f"
  }
};
#undef off

AtAxisClassRec atAxisClassRec = {
  { /* core fields */
     /* superclass              */      (WidgetClass) &atAxisCoreClassRec,
     /* class_name              */      "AtAxis",
     /* widget_size             */      sizeof(AtAxisRec),
     /* class_initialize        */      NULL,
     /* class_part_initialize   */      NULL,
     /* class_inited            */      FALSE,
     /* initialize              */      (XtInitProc) AxisInitialize,
     /* initialize_hook         */      NULL,
     /* pad                     */      NULL,
     /* pad                     */      NULL,
     /* pad                     */      0,
     /* resources               */      resources,
     /* num_resources           */      XtNumber(resources),
     /* xrm_class               */      NULLQUARK,
     /* pad                     */      FALSE,
     /* pad                     */      FALSE,
     /* pad                     */      FALSE,
     /* pad                     */      FALSE,
     /* destroy                 */      (XtWidgetProc) AxisDestroy,
     /* pad                     */      NULL,
     /* pad                     */      NULL,
     /* set_values              */      (XtSetValuesFunc) AxisSetValues,
     /* set_values_hook         */      NULL,
     /* pad                     */      NULL,
     /* get_values_hook         */      NULL,
     /* pad                     */      NULL,
     /* version                 */      XtVersion,
     /* callback_private        */      NULL,
     /* pad                     */      NULL,
     /* pad                     */      NULL,
     /* pad                     */      NULL,
     /* pad                     */      NULL
     },
  { /* atPlot fields */
     /* draw                    */      XtInheritDraw,
     /* draw_icon               */      XtInheritDrawIcon,
     /* drawPS                  */      XtInheritDrawPS,
     /* draw_iconPS             */      XtInheritDrawIconPS,
     /* recalc                  */      XtInheritRecalc
  },
  { /* Axis fields */
     /* range_proc              */      (AtAxisRangeProc) AxisRangeProc,
     /* calc_proc               */      (AtAxisCalcProc) AxisCalcProc
  }
};

WidgetClass atAxisWidgetClass = (WidgetClass)&atAxisClassRec;

/*****************************************************************
 *
 * The core member procs
 */

static void AxisInitialize(req, new)
AtAxisWidget req, new;
{
     new->axis.tic_density = Max(-5, Min(5, new->axis.tic_density));
     new->axis.subtic_density = Max(-5, Min(5, new->axis.subtic_density));
     new->axis.tic_format = XtNewString(new->axis.tic_format);
     *SCCSid = *SCCSid;         /* Keep gcc quiet */
}

static void AxisDestroy(w)
AtAxisWidget w;
{
     XtFree(w->axis.tic_format);
}

static Boolean AxisSetValues(old, req, new)
AtAxisWidget old, req, new;
{
#define Changed(fld)      (old->axis.fld != new->axis.fld)
     Boolean renum = False;

     if (Changed(tic_density) || Changed(subtic_density)) {
	  new->axis.tic_density = Max(-5, Min(5, new->axis.tic_density));
	  new->axis.subtic_density = Max(-5, Min(5, new->axis.subtic_density));
	  renum = True;
     }
     if (Changed(tic_format) || Changed(tic_multiplier)) {
	  renum = True;
     }
     if (Changed(tic_format)) {
	  XtFree(old->axis.tic_format);
	  new->axis.tic_format = XtNewString(new->axis.tic_format);
     }

     if (Changed(auto_scale) && new->axis.auto_scale) {
	  renum = True;
     }
     if (Changed(round_endpoints)) {
	  renum = True;
	  if (!new->axis.round_endpoints) {
	       /* XXXXXXXXXXXXXXX HACK !!!! XXXXXXXXXXXXX */
	       /*
		* We need to force the parent to throw away all the
		* extant bounding boxes, as the endpoints on this axis
		* just decreased.  We do this by faking a call to
		* AtPlotterPlotDataChanged, with a bogus bbox.
		*/
	       static BoundingBox bb = { 1.0, 0.0, 0.0, 0.0};
	       AtPlotterPlotDataChanged((AtPlotWidget)new, &bb,
					False);
	  }
     }

     if (renum) {
	  new->axiscore.numbers_changed = True;
	  AtPlotterRescaleRequired((AtPlotWidget)new);

     }
     return False;
}

/*****************************************************************
 *
 * The Axis member functions
 */

/*
 * This internal routine uses the tic density to calculate the
 * tic_interval, given the size of the axis.  Assume the min/max has
 * been rounded.
 */
static double CalcTicInterval P((AtAxisWidget, double, double));
static double CalcTicInterval(aw, min, max)
AtAxisWidget aw;
double min, max;
{
     AtAxisCorePart *ac = &aw->axiscore;
     int len = ac->vertical ? ac->y1 - ac->y2 : ac->x2 - ac->x1;
     int th, nt, nst;
     double mag, flr, d, sizeticratio;
     int mult;
     double ret;

     if (len <= 0) return 1;    /* Hasn't been set yet */

     if (!aw->axis.auto_scale) return ac->tic_interval;

     /*
      * Make some assumptions about the height of the labels for
      * vertical axes or the width for horizontal axes.  For vertical
      * ones, we assume that any label will be the same height, so we
      * use that, else we assume a 4:1 aspect ratio if we know the max
      * width, else we punt.For horizontal labels, the maxwidth is
      * what we want, else we guess on the width of label[0], else we
      * punt.
      */
     if (ac->vertical) {
	  if (ac->num_tics > 0 && ac->tic_label_text) {
#ifdef TRACE
	       fprintf(stderr, "Guessing height from saved text\n");
#endif
	       th =  AtTextHeight(ac->tic_label_text[0]);
	  } else
	       th = ac->actual_num_width ? ac->actual_num_width >> 2 : 10;
     } else {
	  /* Horizontal */
	  if (ac->actual_num_width)
	       th = ac->actual_num_width;
	  else if (ac->num_tics > 0 && ac->tic_label_text) {
#ifdef TRACE
	       fprintf(stderr, "Guessing height from saved text\n");
#endif
	       th =  AtTextWidth(ac->tic_label_text[0]);
	  } else th = 10;
     }


     nt = len / (th * .75 * (8 - aw->axis.tic_density));
     if (nt < 1) nt = 1;
     if (nt < 2 && min * max < 0) nt = 2; /* Stops an infinite loop... */
     nst = (len / nt) / (8 - aw->axis.subtic_density);

     mag = log10(fabs(max - min));
     flr = floor(mag);
     sizeticratio = pow(10.0, mag-flr)/ nt;

     d = 1.0;

     /*
      * The ratio thresholds were calculated to split the difference
      * in the resulting number of ticks
      */
     while(1){
	  if (sizeticratio > 2.857*d){
	       mult = 5;
	       break;
	  }
	  if (sizeticratio > 1.333*d){
	       mult = 2;
	       break;
	  }
	  if (sizeticratio > 0.6666*d){
	       mult = 1;
	       break;
	  }
	  d /= 10.0;
     }
     ret = mult * d * pow(10.0,flr);
     /*
      * now figure out subtics.
      * if it makes sense to do 5 or 10 subdivision, do it.
      * otherwise do a power of 2
      */
     switch (mult) {
     case 1:
	  if (nst >= 10) nst = 9;
	  else if (nst >= 5) nst = 4;
	  else if (nst >= 2) nst = 1;
	  else nst = 0;
      break;
     case 2:
	  if (nst >= 8) nst = 7;
	  else if (nst >= 4) nst = 3;
	  else if (nst >= 2) nst = 1;
	  else nst = 0;
	  break;
    case 5:
	  if (nst >= 10) nst = 9;
	  else if (nst >= 5) nst = 4;
	  else if (nst >= 2) nst = 1;
	  else nst = 0;
	  break;
     }
     aw->axis.subtics_per_tic = nst;
     return ret;
}


/*
 * The range proc
 */
static void AxisRangeProc(acw, minp, maxp, tip, nwp)
AtAxisCoreWidget acw;
double *minp, *maxp, *tip;
int *nwp;
{
     AtAxisWidget aw = (AtAxisWidget)acw;
     double nti, ti, mn, mx;

     mn = *minp;
     mx = *maxp;

     nti = CalcTicInterval(aw, mn, mx);
     do {
	  ti = nti;
	  if (aw->axis.round_endpoints) {
	       mn = floor(*minp / ti) * ti;
	       mx = ceil(*maxp / ti) * ti;
	  }
     } while (aw->axis.round_endpoints &&
	      (nti = CalcTicInterval(aw, mn, mx)) != ti);

     /* Accept the actual_num_width that is passed in */

     *minp = mn;
     *maxp = mx;
     *tip = ti;
}




/*
 * The calc proc
 */
static void AxisCalcProc(acw)
AtAxisCoreWidget acw;
{
     AtAxisCorePart *ac = &acw->axiscore;
     AtAxisWidget aw = (AtAxisWidget)acw;
     int i;
     double l, h, sti;
     char lbl[1000];

     /* Calculate the real tics, NOT including endpoints */
     l = ceil(ac->min / ac->tic_interval) * ac->tic_interval;
     h = floor(ac->max / ac->tic_interval) * ac->tic_interval;

     /* Now include the endpoints */
     ac->num_tics = 1 + (h - l) / ac->tic_interval;
     if (h < ac->max) ac->num_tics++;
     if (l > ac->min) ac->num_tics++;

     ac->tic_values =
	  (double *)XtMalloc(sizeof (double) * ac->num_tics);
     ac->tic_label_string =
	  (String *)XtMalloc(sizeof (String) * ac->num_tics);

     for (i = 0, l = ac->min, h = ac->max * 1.0001; l < h; i++) {
	  assert(i < ac->num_tics);
	  ac->tic_values[i] = l;
	  sprintf(lbl, aw->axis.tic_format, l * aw->axis.tic_multiplier);
	  ac->tic_label_string[i] = XtNewString(lbl);
	  l += ac->tic_interval;
	  if (!i && !aw->axis.round_endpoints)
	       l = floor(l / ac->tic_interval) * ac->tic_interval;
	  else if (!aw->axis.round_endpoints && l > h &&
		   i == ac->num_tics - 2) /* next one is last! */
	       l = ac->max;
     }

     assert(i == ac->num_tics);

     /*
      * Make subtics ever tho there are real tics (so setting
      * ticLenght = 0 doesn't leave ugly gaps!
      */
     sti = ac->tic_interval / (aw->axis.subtics_per_tic + 1);
     h = floor(ac->max / sti) * sti;
     l = ceil(ac->min / sti) * sti;

     ac->num_subtics = (h - l) / sti + 1;

     ac->subtic_values = (double *)XtMalloc(sizeof (double) *
					    ac->num_subtics);
     h *= 1.0001;               /* Increas a little bit b/c of roundoff */
     for (i = 0; l <= h; i++, l += sti) {
	  assert(i < ac->num_subtics);
	  ac->subtic_values[i] = l;
     }
     assert(i == ac->num_subtics);
}
