/*
 * main.c Michael Saunby M.Saunby@reading.ac.uk
 *
 * release 1.1
 * A JPEG viewer using the Independent JPEG Group's library
 * from release 4 of their code.
 *
 */

#include "jinclude.h"
#include <stdlib.h>
#include <ctype.h>
#include <signal.h>


#include "jversion.h"		/* for version message */


/*
 * This routine gets control after the input file header has been read. It
 * must determine what output file format is to be written, and make any
 * other decompression parameter changes that are desirable.
 */

METHODDEF void
d_ui_method_selection (decompress_info_ptr cinfo)
{
  if (cinfo->jpeg_color_space == CS_GRAYSCALE)
    cinfo->out_color_space = CS_GRAYSCALE;

  jselwham8 (cinfo);
}



static external_methods_ptr emethods;	/* for access to free_all */

GLOBAL void
signal_catcher (int signum)
{
  if(emethods != NULL)
  {
  emethods->trace_level = 0;	/* turn off trace output */
  (*emethods->free_all) ();	/* clean up memory allocation & temp files */
  }
  Quit ("Error processing JPEG file", 25);
}


int
main (int argc, char **argv)
{
  struct Decompress_info_struct cinfo;
  struct Decompress_methods_struct dc_methods;
  struct External_methods_struct e_methods;
  int c;
  char namebuffer[256];
  extern int JPEG_restart;


  /* Initialize the system-dependent method pointers. */
  cinfo.methods = &dc_methods;
  cinfo.emethods = &e_methods;
  jselerror (&e_methods);	/* error/trace message routines */
  jselmemmgr (&e_methods);	/* memory allocation routines */
  dc_methods.d_ui_method_selection = d_ui_method_selection;

  /* Now OK to enable signal catcher. */
  emethods = &e_methods;

  signal (SIGINT, signal_catcher);
  signal (SIGTERM, signal_catcher);

  do
    {
      /* Set up default JPEG parameters. */
      j_d_defaults (&cinfo, TRUE);

      if (Startup (namebuffer) == NULL)
	{
	  /* Probably user cancelled, so no error requester */
	  Cleanup ();
	  exit (EXIT_FAILURE);
	}
      if ((cinfo.input_file = fopen (namebuffer, "rb")) == NULL)
	{
	  Quit ("cannot open file", 25);
	}
      jselrjfif (&cinfo);

      jpeg_decompress (&cinfo);
      fclose(cinfo.input_file);
  } while (JPEG_restart);

  Cleanup ();
  exit (EXIT_SUCCESS);
  return 0;
}
