/*****************************************************************
 * fbhalf.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.
 *
 * fbhalf.c: Take an 8bit gray image, resize it to a maximum total
 *	      number of pixels, optionally sharpen it with a digital
 *	      Laplacian filter, and halftone it using one of three
 *	      standard algorithms.  Output the result in PBM format.
 *
 * USAGE
 *	% fbhalf [ -args ]  [ size ] < 8bit > 1bit
 *
 *	size	Choose a width and height as large as possible so that
 *		width is a factor of 8 and width*height <= size (default
 *		is width and height of original 8bit file, ignoring aspect
 *		ratio).
 *
 *	-f	Do Floyd-Steinberg halftoning (the default algorithm)
 *	-b<int>	Do Blue noise halftoning (-b50 or 50% noise is default)
 *	-c<int>	Do Constained average halftoning (-c4 is the default)
 *	-s<int>	Sharpen the image with a given beta (-s2.0 is default)
 *	-t<int>	Use a threshhold of <int> to halftone (127 is default)
 *
 *	-C<int>,-N<int>
 *		Clean up image by flipping isolated pixels.  A pixel is
 *		isolated if there are fewer than C like pixels in the
 *		nearby NxN square.
 *
 * EDITLOG
 *	LastEditDate = Mon Jun 25 00:02:44 1990 - Michael Mauldin
 *	LastFileName = /usr2/mlm/src/misc/fbm/fbhalf.c
 *
 * HISTORY
 * 25-Jun-90  Michael Mauldin (mlm@cs.cmu.edu) Carnegie Mellon
 *	Package for Release 1.0
 *
 * 03-May-89  Michael Mauldin (mlm) at Carnegie Mellon University
 *	Beta release (version 0.93) mlm@cs.cmu.edu
 *
 *  8-Sep-88  Michael Mauldin (mlm) at Carnegie-Mellon University
 *	Created.
 *****************************************************************/

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

# define USAGE\
"Usage: fbhalf [ -fbct<parm> ] [-s<sharpen> ] [ -<type> ]\n\
              [ -C<clean> -N<nbr>] [ size ] < 8bit > 1bit"

#ifndef lint
static char *fbmid =
"$FBM fbhalf.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

main (argc, argv)
char *argv[];
{ int w, h, ow = -1, oh = -1, size = -1, alg = 'b';
  int clean = -1, nbr = 5, outtype = DEF_1BIT;
  double beta = -1e9, parm = -1e9;
  char *title, *credits;
  FBM input, resized, sharpened, halftoned, cleaned, *image;

  /* Clear pointers */
  input.bm     = input.cm     = (unsigned char *) NULL;
  resized.bm   = resized.cm   = (unsigned char *) NULL;
  sharpened.bm = sharpened.cm = (unsigned char *) NULL;
  halftoned.bm = halftoned.cm = (unsigned char *) NULL;
  cleaned.bm   = cleaned.cm   = (unsigned char *) NULL;

  if (read_bitmap (&input, (char *) NULL))
  {
    if (input.hdr.bits != 8 || input.hdr.physbits != 8)
    { fprintf (stderr,
	       "Can't handle images with %d bits and %d physbits per pixel\n",
	       input.hdr.bits, input.hdr.physbits);
      exit (1);
    }

    if (input.hdr.title[0]) title = input.hdr.title;
    if (input.hdr.credits[0]) credits = input.hdr.credits;

    /* Get the options */
    while (--argc > 0 && (*++argv)[0] == '-')
    { while (*++(*argv))
      { switch (**argv)
        { case 's':	if (argv[0][1]) { beta = atof (*argv+1); SKIPARG; }
			else		beta = 2.0;
			break;
			
	  case 'f':	alg = 'f'; parm = 0.0; break;
			
	  case 'b':	alg = 'b';
			if (argv[0][1])	{ parm = atof (*argv+1); SKIPARG; }
			break;
			
	  case 'c':	alg = 'c';
			if (argv[0][1])	{ parm = atof (*argv+1); SKIPARG; }
			break;
			
	  case 't':	alg = 't';
			if (argv[0][1])	{ parm = atoi (*argv+1); SKIPARG; }
			else		{ parm = 127; }
			break;
			
	  case 'C':	if (argv[0][1])	{ clean = atoi (*argv+1); SKIPARG; }
	  		else		{ clean = 10; }
			break;
			
	  case 'N':	if (argv[0][1])	{ nbr = atoi (*argv+1); SKIPARG; }
	  		else		{ nbr = 5; }
			
			if (clean < 0)	{ clean = 10; }
			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 'R':	outtype = FMT_RLE; 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", USAGE);
			exit (1);
        }
      }
    }
    
    if (argc > 0)	size = atoi (argv[0]);

    /* Default parms for algorithms */
    if (parm <= -1e9)
    { if      (alg == 'b') parm = 50.0;
      else if (alg == 'c') parm = 4.0;
      else if (alg == 't') parm = 128.0;
    }

    /* Determine output height & width (oh*ow <= size) */
    h = input.hdr.rows;
    w = input.hdr.cols;

    if (size < 0)
    { oh = h; ow = w; }
    else
    { ow = sqrt ((double) size * w / (h * input.hdr.aspect));
      ow &= ~7;			/* Make width multiple of 8 */
      oh = ow * input.hdr.aspect * h / w;
    }

    fprintf (stderr,
	     "Halftone \"%s\" size [%dx%d] => %d pixels\n",
	     input.hdr.title[0] ? input.hdr.title : "(untitled)",
	     ow, oh, ow*oh);

    /* Start with image in variable 'input' */
    image = &input;

    /* If necessary, resize it */
    if (w != ow || h != oh)
    { if (extract_fbm (image, &resized, 0, 0, w, h, ow, oh, title, credits))
      { free_fbm (image);
	image = &resized;
      }
      else
      { exit (1); }
    }

    /* Sharpen the image if requested */    
    if (beta > -1e9)
    { if (sharpen_fbm (image, &sharpened, beta))
      { free_fbm (image);
	image = &sharpened;
      }
      else
      { exit (1); }
    }
    
    /* Now use the appropriate algorithm to halftone it */
    switch (alg)
    { case 'b':	bluenoise_fbm (image, &halftoned, parm); break;
      case 'c': constravg_fbm (image, &halftoned, parm); break;
      case 't': thesh_fbm (image, &halftoned, (int) parm); break;
      default:	floyd_fbm (image, &halftoned);
    }

    /* free_fbm (image); */
    image = &halftoned;

    if (clean >= 0)
    { if (!clean_fbm (image, &cleaned, clean, 1, nbr))
      { exit (1); }

      free_fbm (image);
      image = &cleaned;      
    }

    if (write_bitmap (image, stdout, outtype)) exit (0);
  }
  
  exit (1);
}
