# include "data.h"

int plot (int argc, char **argv) {
  
  int kapa, N, Npts;
  Graphdata graphmode;
  Vector *xvec, *yvec, *dxmvec, *dxpvec, *dymvec, *dypvec;

  if (!style_args (&graphmode, &argc, argv, &kapa)) return FALSE;

  /* decide on error bars */
  dxmvec = dxpvec = dymvec = dypvec = NULL;
  if ((N = get_argument (argc, argv, "-dx"))) {
    remove_argument (N, &argc, argv);
    if ((dxmvec = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);    
    remove_argument (N, &argc, argv);
  }
  if ((N = get_argument (argc, argv, "+dx"))) {
    remove_argument (N, &argc, argv);
    if ((dxpvec = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);    
    remove_argument (N, &argc, argv);
  }
  if ((N = get_argument (argc, argv, "-dy"))) {
    remove_argument (N, &argc, argv);
    if ((dymvec = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);    
    remove_argument (N, &argc, argv);
  }
  if ((N = get_argument (argc, argv, "+dy"))) {
    remove_argument (N, &argc, argv);
    if ((dypvec = SelectVector (argv[N], OLDVECTOR, TRUE)) == NULL) return (FALSE);    
    remove_argument (N, &argc, argv);
  }

  if (argc != 3) {
    gprint (GP_ERR, "USAGE: plot <x> <y> [style]\n");
    return (FALSE);
  }

  /* set errorbar mode (these are NOT sticky) */
  graphmode.etype = 0;
  if ((dymvec != NULL) && (dypvec == NULL)) dypvec = dymvec;
  if ((dypvec != NULL) && (dymvec == NULL)) dymvec = dypvec;
  if ((dypvec != NULL) || (dymvec != NULL)) graphmode.etype |= 0x01;
  if ((dxmvec != NULL) && (dxpvec == NULL)) dxpvec = dxmvec;
  if ((dxpvec != NULL) && (dxmvec == NULL)) dxmvec = dxpvec;
  if ((dxpvec != NULL) || (dxmvec != NULL)) graphmode.etype |= 0x02;
  
  /* find vectors */
  if ((xvec = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
  if ((yvec = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
  if (xvec[0].Nelements != yvec[0].Nelements) {
    gprint (GP_ERR, "vectors %s and %s not the same length\n", argv[1], argv[2]);
    return (FALSE);
  }
  Npts = xvec[0].Nelements;
  if (Npts == 0) return (TRUE);

  if (!KapaPrepPlot (kapa, Npts, &graphmode)) return (FALSE);
  
  KapaPlotVector (kapa, Npts, xvec[0].elements, "x");
  KapaPlotVector (kapa, Npts, yvec[0].elements, "y");
  if (graphmode.etype & 0x01) {
    KapaPlotVector (kapa, Npts, dymvec[0].elements, "dym");
    KapaPlotVector (kapa, Npts, dypvec[0].elements, "dyp");
  }
  if (graphmode.etype & 0x02) {
    KapaPlotVector (kapa, Npts, dxmvec[0].elements, "dxm");
    KapaPlotVector (kapa, Npts, dxpvec[0].elements, "dxp");
  }
  return (TRUE);
}
