/*****************************************************************
 * flthre.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.
 *
 * flthre.c: 
 *
 * CONTENTS:
 *	thesh_fbm (input, output, thresh)
 *
 * EDITLOG
 *	LastEditDate = Mon Jun 25 00:18:08 1990 - Michael Mauldin
 *	LastFileName = /usr2/mlm/src/misc/fbm/flthre.c
 *
 * HISTORY
 * 25-Jun-90  Michael Mauldin (mlm@cs.cmu.edu) Carnegie Mellon
 *	Package for Release 1.0
 *
 * 16-Jun-89  Michael Mauldin (mlm) at Carnegie Mellon University
 *	Bug fix from Dave Cohrs <dave@cs.wisc.edu>
 *
 * 07-Mar-89  Michael Mauldin (mlm) at Carnegie Mellon University
 *	Beta release (version 0.9) mlm@cs.cmu.edu
 *
 * 10-Dec-88  Michael Mauldin (mlm) at Carnegie-Mellon University
 *	Created.
 *****************************************************************/


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

/*****************************************************************
 * thesh_fbm: Threshhold halftoning
 *****************************************************************/

# define RAND(RN) (((seed = 1103515245 * seed + 12345) >> 12) % (RN))

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

thesh_fbm (input, output, thresh)
FBM *input, *output;
register int thresh;
{ register unsigned char *bmp, *obm;
  register int i, j, rowlen, w, h, outrow;

  if (input->hdr.planes != 1)
  { fprintf (stderr, "thesh_fbm: can't halftone color images\n");
    return (0);
  }

  fprintf (stderr, "Threshhold halftoning, thesh %d\n", thresh);

  /* Allocate output */
  free_fbm (output);
  output->hdr = input->hdr;
  output->hdr.bits = 1;
  output->hdr.physbits = 8;
  outrow = 16 * ((input->hdr.cols + 15) / 16); /* Pad to even byte boundary */
  output->hdr.rowlen = outrow;
  output->hdr.plnlen = outrow*output->hdr.rows;
  alloc_fbm (output);

  w = input->hdr.cols;
  h = input->hdr.rows;
  rowlen = input->hdr.rowlen;
  
  /* Now do threshholding */
  for (j=0; j<h; j++)
  { /* scan left to right */
    bmp = &input->bm[j*rowlen];
    obm = &output->bm[j*outrow];

    for (i=1; i<w; i++)
    { obm[i] = bmp[i] > thresh ? WHITE : BLACK; }
  }
  
  return (1);
}
