# include "data.h"

int limits (int argc, char **argv) {

  int N, APPLY, dX, dY;
  int kapa;
  char *name;
  Graphdata graphmode;
  Vector *xvec, *yvec;

  xvec = yvec = NULL;

  APPLY = FALSE;
  if ((N = get_argument (argc, argv, "-a"))) {
    remove_argument (N, &argc, argv);
    APPLY = TRUE;
  }
  name = NULL;
  if ((N = get_argument (argc, argv, "-n"))) {
    remove_argument (N, &argc, argv);
    name = strcreate (argv[N]);
    remove_argument (N, &argc, argv);
  }
  if (!GetGraph (&graphmode, &kapa, name)) return (FALSE);
  FREE (name);

  // XXX need an option to set the limits based on the current image bounds
  if ((N = get_argument (argc, argv, "-image"))) {
    remove_argument (N, &argc, argv);
    KapaGetImageRange (kapa, &graphmode.xmin, &graphmode.xmax, &graphmode.ymax, &graphmode.ymin, &dX, &dY);

    set_variable ("XMIN", graphmode.xmin);
    set_variable ("XMAX", graphmode.xmax);
    set_variable ("YMIN", graphmode.ymin);
    set_variable ("YMAX", graphmode.ymax);

    set_variable ("KAPA_XMIN", graphmode.xmin);
    set_variable ("KAPA_XMAX", graphmode.xmax);
    set_variable ("KAPA_YMIN", graphmode.ymin);
    set_variable ("KAPA_YMAX", graphmode.ymax);

    set_variable ("KAPA_XPIX", dX);
    set_variable ("KAPA_YPIX", dY);

    // if (!NoClear) KapaClearSections (kapa);
    SetGraph (&graphmode);
    KapaSetLimits (kapa, &graphmode);
    return (TRUE);
    // Set Region based on image
  }

  if (argc == 1) {
    gprint (GP_ERR, "limits: %f %f %f %f [-a] [-n device]\n",
	     graphmode.xmin, graphmode.xmax,
	     graphmode.ymin, graphmode.ymax);
    goto success;
  }

  if (argc == 3) { /* expect to see: limits x y */
    if ((xvec = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
    if ((yvec = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
    goto success;
  }
    
  if (argc == 4) { /* expect to see: limits x num num or limits num num y */
    if (ISNUM(argv[1][0]) && ISNUM(argv[2][0])) {
      if ((yvec = SelectVector (argv[3], OLDVECTOR, FALSE)) == NULL) goto error;
      graphmode.xmin = atof (argv[1]);
      graphmode.xmax = atof (argv[2]);
      goto success;
    }
    if (ISNUM(argv[2][0]) && ISNUM(argv[3][0])) {
      if ((xvec = SelectVector (argv[1], OLDVECTOR, FALSE)) == NULL) goto error;
      graphmode.ymin = atof (argv[2]);
      graphmode.ymax = atof (argv[3]);
      goto success;
    }
    goto error;
  }
  
  if (argc == 5) {
    graphmode.xmin = atof (argv[1]);
    graphmode.xmax = atof (argv[2]);
    graphmode.ymin = atof (argv[3]);
    graphmode.ymax = atof (argv[4]);
    goto success;
  }

  gprint (GP_ERR, "USAGE: limits [xrange] [yrange]\n");
  gprint (GP_ERR, " [range] may be either [min max] or a vector\n");
  return (FALSE);

 error:
  gprint (GP_ERR, "error in vectors\n");
  return (FALSE);

 success:
  SetLimits (xvec, yvec, &graphmode);
  if (APPLY) KapaSetLimits (kapa, &graphmode);
  return (TRUE);
}
