# include "data.h"

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

  char filename[1024], buffer[20], type[16];
  int N, Source, Nsource, IsImage;
  
  if (N = get_argument (argc, argv, "--help")) {
    fprintf (stderr, "USAGE: jpeg [-name file] [-g | -i] [-n device] [-ppm]\n");
    return (FALSE);
  }

  /* image type */
  strcpy (type, "PNGF");
  if (N = get_argument (argc, argv, "-ppm")) {
    remove_argument (N, &argc, argv);
    strcpy (type, "PPMF");
  }

  /* file name */
  filename[0] = 0;
  if (N = get_argument (argc, argv, "-name")) {
    remove_argument (N, &argc, argv);
    strcpy (filename, argv[N]);
    remove_argument (N, &argc, argv);
  }

  /* display source */
  Nsource = -1;
  if (N = get_argument (argc, argv, "-n")) {
    remove_argument (N, &argc, argv);
    Nsource = atof (argv[N]);
    remove_argument (N, &argc, argv);
  }
  if (N = get_argument (argc, argv, "-g")) {
    remove_argument (N, &argc, argv);
    SetImageDevice (FALSE);
  }  
  if (N = get_argument (argc, argv, "-i")) {
    remove_argument (N, &argc, argv);
    SetImageDevice (TRUE);
  }  
  IsImage = GetCurrentDevice ();
  if (IsImage) {
    if (!GetImage (&Source, &Nsource)) return (FALSE);
    if (!filename[0]) strcpy (filename, "Ximage.jpg");
    strcpy (type, "JPEG");
  } else {
    if (!GetGraph (NULL, &Source, &Nsource)) return (FALSE);
    if (!filename[0]) strcpy (filename, "Xgraph.png");
  }

  strcpy (buffer, type);
  write (Source, buffer, 4);
  sprintf (buffer, "LEN: %11d", strlen(filename));
  write (Source, buffer, 16);
  write (Source, filename, strlen(filename));
  read (Source, buffer, 4);

  return (TRUE);
}

/* jpeg -g converts graph to png
   jpeg converts image to jpeg */
