# include "Ximage.h"
# define DrawLine(X1,Y1,DX,DY) (fprintf (f, " %6.2f %6.2f %6.2f %6.2f L\n", X1, Y1, X1+DX, Y1+DY))

int PSFrame (KapaGraphWidget *graph, FILE *f) {
  
  int i, Nticks, P;
  double fx, fy, dfx, dfy, lweight;
  Graphic *graphic;
  TickMarkData *ticks;
  bDrawColor color;

  graphic = GetGraphic();

  /* each axis is drawn independently */
  fprintf (f, "1 setlinewidth\n");
  for (i = 0; i < 4; i++) {
    fx  = graph[0].axis[i].fx;
    fy  = graphic->dy - graph[0].axis[i].fy;
    dfx = graph[0].axis[i].dfx;
    dfy = -graph[0].axis[i].dfy;
    P = hypot (graph[0].axis[(i+1)%2].dfx, graph[0].axis[(i+1)%2].dfy);

    lweight = MAX (0, MIN (10, graph[0].axis[i].lweight));
    color = MAX (0, MIN (15, graph[0].axis[i].color));

    fprintf (f, "%.1f setlinewidth\n", lweight);
    fprintf (f, "%s setrgbcolor\n", KapaColorRGBString(color));
    // no need to init rot font

    if (graph[0].axis[i].isaxis) { 
      DrawLine (fx, fy, dfx, dfy); 
    }
    
    if (graph[0].axis[i].areticks) {
      ticks = CreateAxisTicks (&graph[0].axis[i], &Nticks);
      for (i = 0; i < Nticks; i++) {
	PSTick (graphic, &graph[0].axis[i], P, &ticks[i], i, f);
      }
      FREE (ticks);
    }      
  }
  return (TRUE);
}

void PSTick (Graphic *graphic, Axis *axis, int P, TickMarkData *tick, int naxis, FILE *f) {
  
  double x, y, dx, dy;
  int pos, dir, fontsize;
  double size, n, pad;
  char string[64], *fontname;

  double fx  = axis->fx;
  double fy  = graphic->dy - axis->fy;
  double dfx = axis->dfx;
  double dfy = -axis->dfy;

  double min = axis->min;
  double max = axis->max;

  double value = tick->value;

  pos = size = 0;

  if (tick->IsMajor) { 
    size = MAX (0.02, 7.0 / P); 
  } else {
    size = MAX (0.01, 4.0 / P); 
  }
  
  n = P / hypot(dfx, dfy);
  x = fx + (value-min)*dfx/(max - min);
  y = fy + (value-min)*dfy/(max - min);

  dir = ((naxis == 0) || (naxis == 1)) ? -1 : +1;
  dx = dir*size*dfy*n;	
  dy = dir*size*dfx*n;
  
  DrawLine (x, y, dx, dy);

  if (tick->IsLabel) {
    int xt, yt;

    fontname = GetRotFont (&fontsize);

    pad = !isnan(axis->ticktextPad) ? axis->ticktextPad*fontsize : 0.8*fontsize + 1.0;
    
    /* temporarily assume rectilinear axes */
    if (naxis == 0) { dx = 0; dy = +pad; pos = 1; }
    if (naxis == 2) { dx = 0; dy = -pad; pos = 7; }

    if (naxis == 1) { dy = 0; dx = -pad; pos = 3; }
    if (naxis == 3) { dy = 0; dx = +pad; pos = 5; }

    xt = fx + (value-min)*dfx/(max - min) + dx;
    yt = fy + (value-min)*dfy/(max - min) + dy;
    if (fabs(value) < 0.001) { value = 0.0; }
    sprintf (string, "%4g", value);
    PSRotText (f, xt, yt, string, pos, 0.0);
  }
}

  /* 
  dx = size*dfy*n;	
  dy = size*dfx*n;
  DrawLine (x, y, dx, dy);
  
  dx = -size*dfy*n;	
  dy = -size*dfx*n;
  DrawLine (x, y, dx, dy);
  */
  
