# include "data.h"

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

  int N, APPLY;
  int Ngraph, Xgraph;
  Graphdata graphmode;
  Vector *xvec, *yvec;

  xvec = yvec = NULL;

  APPLY = FALSE;
  if ((N = get_argument (argc, argv, "-a"))) {
    remove_argument (N, &argc, argv);
    APPLY = TRUE;
  }

  Ngraph = -1;
  if ((N = get_argument (argc, argv, "-n"))) {
    remove_argument (N, &argc, argv);
    Ngraph = atof (argv[N]);
    remove_argument (N, &argc, argv);
  }
  if (!GetGraph (&graphmode, &Xgraph, &Ngraph)) return (FALSE);

  if (argc == 1) {
    gprint (GP_ERR, "limits: %f %f %f %f [-a] [-n Xgraph]\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 (Xgraph, &graphmode);
  return (TRUE);
}
