/* Hey, emacs, this is -*- C -*- code.  */

/* read.c - read an image

Copyright (C) 1992 D P Gymer

This is free software; you can redistribute it and/or modify it under the
   terms of the GNU General Public License as published by the Free Software
   Foundation; either version 2 of the License, or (at your option) any later
   version.

This program is distributed in the hope that it will be useful, but WITHOUT
   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
   more details.  */

/* $Id: read.c,v 0.3.2.0 1992/06/11 22:30:07 dpg Alpha dpg $ */

#include <stdio.h>
#include <stdlib.h>

#include "view.h"

/* Delete unused colors from the palette.  We don't alter the number
   assignments, since this would force us to scan the entire image.  */
static void
remove_redundant_colors (PALETTE **palp)
{
  while (*palp)
    {
      PALETTE *this = *palp;

      if (this->count)
	palp = &this->next;
      else
	{
	  *palp = this->next;
	  free (this);
	}
    }
}

typedef struct
{
  int (*function) (FILE *, const char *, MAP *);
  const char *name;
} IMAGE_TYPE;

/* List of functions used to test for image types and load them if a match is
   found.  */
static IMAGE_TYPE image_types[]=
{
  {maybe_read_gif, "GIF"},
  {maybe_read_pnm, "pbmplus anymap"},
  {maybe_read_uxface, "uncompressed X-Face"},
  {maybe_read_degas, "Atari Degas"},
  {0, 0}
};

/* Read a map.  */
MAP *
read_map (FILE *fp, const char *file)
{
  IMAGE_TYPE *type = image_types;
  MAP *map = 0;

  while (type->function && !last_sig)
    {
      map = alloc_map ();
      fseek (fp, 0, SEEK_SET);
      if (!(*type->function) (fp, file, map))
	break;
      ++type;
      free_map (map);
      map = 0;
    }

  if (!last_sig)
    {
      if (!*type->function)
	{
	  view_message ("unrecognised format", "`%s'", file);
	  rc = 1;
	}
      else
	{
	  view_message (type->name, "`%s'; size: %dx%d type", file, map->width, map->height);
	  remove_redundant_colors (&map->palette);
	}
    }

  return map;
}
