/*****************************************************************
 * fbpalet.c: FBM Release 1.0 25-Feb-90 Michael Mauldin
 *
 * Copyright (C) 1989,1990 by Michael Mauldin.  Permission is granted
 * to use this file in whole or in part for any purpose, educational,
 * recreational or commercial, provided that this copyright notice
 * is retained unchanged.  This software is available to all free of
 * charge by anonymous FTP and in the UUNET archives.
 *
 * fbpalet.c: Replace one image's color map with another image's.
 *	      The color index plane is not modifed by this action.
 *
 *	      Includes option for removing duplicates.  That is
 *	      Suppose both color 1 and color 127 are both <0,0,0>
 *	      (pure black)...with the -d option, all uses of color
 *	      127 get converted to color 1.  The colormap is not
 *	      modified by this action.
 *
 * USAGE
 *     % fbpalet < image1 > image2
 *
 * EDITLOG
 *     LastEditDate = Mon Jun 25 00:03:55 1990 - Michael Mauldin
 *     LastFileName = /usr2/mlm/src/misc/fbm/fbpalet.c
 *
 * HISTORY
 * 25-Jun-90  Michael Mauldin (mlm@cs.cmu.edu) Carnegie Mellon
 *	Package for Release 1.0
 *
 * 01-May-90  Michael Mauldin (mlm) at Carnegie-Mellon University
 *     Created.
 *****************************************************************/

# include <stdio.h>
# include <math.h>
# include "fbm.h"

# define USAGE \
  "Usage: fbpalet [ -m<mapname ] [ -d ] [ -<type> ] < image > image"

#ifndef lint
static char *fbmid =
"$FBM fbpalet.c <1.0> 25-Jun-90  (C) 1989,1990 by Michael Mauldin, source \
code available free from MLM@CS.CMU.EDU and from UUNET archives$";
#endif

int debug = 0;
int removedup = 0;
double expon = 1.0;

main (argc, argv)
char *argv[];
{ FBM image;
  FBM mapimage;
  int outtype = DEF_8BIT;
  char *fname = NULL;
  char *mapname = NULL;

  /* Get the options */
  while (--argc > 0 && (*++argv)[0] == '-')
  { while (*++(*argv))
    { switch (**argv)
      {
	case 'D':	debug++; break;
	case 'd':	removedup++; break;
        case 'm':	mapname = *argv+1; SKIPARG; break;
	case 'A':	outtype = FMT_ATK; break;
	case 'B':	outtype = FMT_FACE; break;
	case 'F':	outtype = FMT_FBM; break;
	case 'G':	outtype = FMT_GIF; break;
	case 'I':	outtype = FMT_IFF; break;
	case 'L':	outtype = FMT_LEAF; break;
	case 'M':	outtype = FMT_MCP; break;
	case 'P':	outtype = FMT_PBM; break;
	case 'S':	outtype = FMT_SUN; break;
	case 'T':	outtype = FMT_TIFF; break;
	case 'X':	outtype = FMT_X11; break;
	case 'Z':	outtype = FMT_PCX; break;
	default:        fprintf (stderr, "%s\n", USAGE);
                        exit (1);
      }
    }
  }

  /* Clear the memory pointers so alloc_fbm won't be confused */
  image.cm  = image.bm  = (unsigned char *) NULL;
  mapimage.cm = mapimage.bm = (unsigned char *) NULL;

  /* Read the image */
  if (read_bitmap (&image, fname))
  { 
    if (image.hdr.planes == 1 && image.hdr.clrlen == 0)
    { fprintf (stderr, "fbpalet only works on color images\n");
    }

    /* Read the mapimage */
    if (mapname && read_bitmap (&mapimage, mapname))
    { 
      if (mapimage.hdr.planes == 1 && mapimage.hdr.clrlen == 0)
      { fprintf (stderr, "fbpalet only works on mapped color images\n");
        exit (0);
      }

      if (dup_clr (&mapimage, &image) &&
          write_bitmap (&image, stdout, outtype))
      { exit (0); }
    }

    /* Still call dup_clr to transform duplicate colors */
    else if (mapname == NULL)
    { if (dup_clr (NULL, &image) &&
          write_bitmap (&image, stdout, outtype))
      { exit (0); }
    }
    
  }

  exit (1);
}

/****************************************************************
 * dup_clr: Copy colormap from input to output
 *	    Duplicates are removed, even if input image is NULL.
 ****************************************************************/

dup_clr (input, output)
FBM *input, *output;
{ register int i, j, clrlen;
  register unsigned char *ic, *oc;
  unsigned char *r, *g, *b;
  unsigned char cmap[256];
  int changes = 0, colors;

  /*-------- First copy over the new colormap --------*/
  if (input)
  { clrlen = input->hdr.clrlen;

    /* If output image has another color map, free the old one */
    if (output->hdr.clrlen != input->hdr.clrlen)
    { if (output->hdr.clrlen > input->hdr.clrlen)
      { fprintf (stderr,
		"fbpalet: warning, new color map is smaller (%d vs %d)\n",
		input->hdr.clrlen, output->hdr.clrlen);
      }

      if (output->hdr.clrlen > 0) free (output->cm);
      output->cm = (unsigned char *) malloc (input->hdr.clrlen);
    }

    /* Replace colormap */
    output->hdr.clrlen = clrlen;
    ic = input->cm;
    oc = output->cm;
  
    for (i=0; i < clrlen; i++)
    { *oc++ = *ic++; }
  }

  /*-------- Now map duplicate colors to lowest index --------*/

  if (!removedup) return (1);

  clrlen = output->hdr.clrlen;
  colors = clrlen / 3;

  /* CMAP will compute transform of body of image */
  for (i=0; i<colors; i++) { cmap[i] = i; }

  r = output->cm;
  g = r + colors;
  b = g + colors;

  for (i=1; i<colors; i++)
  { for (j=0; j<i; j++)
    { if (r[i] == r[j] && g[i] == g[j] && b[i] == b[j])
      { cmap[i] = j;

	if (debug)
	{ fprintf (stderr, "Dup: %3d -> %3d <%3d,%3d,%3d>\n",
		   i, j, r[i], g[i], b[i]);
	}

        changes++;
	break;
      }
    }
  }

  if (changes)
  { fprintf (stderr, "fbpalet: %d duplicated colormap entries\n", changes); }

  /* Change indices of duplicated colors */
  if (changes)
  { ic = output->bm;
    oc = ic + output->hdr.plnlen * output->hdr.planes;

    for (; ic<oc; ic++)
    { *ic = cmap[*ic]; }
  }

  return (1);
}
