/*
 * This software is copyrighted as noted below.  It may be freely copied,
 * modified, and redistributed, provided that the copyright notice is
 * preserved on all copies.
 *
 * There is no warranty or other guarantee of fitness for this software,
 * it is provided solely "as is".  Bug reports or fixes may be sent
 * to the author, who may or may not act on them as he desires.
 *
 * You may not include this software in a program or other software product
 * without supplying the source, or without informing the end-user that the
 * source is available for no extra charge.
 *
 * If you modify this software, you should include a notice giving the
 * name of the person performing the modification, the date of modification,
 * and the reason for such modification.
 */
/*
 * aliasgamma.c - perform a gamma correction.
 *
 * Author:      Raul Rivero
 *              Mathematics Dept.
 *              University of Oviedo
 * Date:        Thu Jan 16 1992
 * Copyright (c) 1992, Raul Rivero
 *
 */

#include <lug.h>
#include <lugfnts.h>

extern int LUGverbose;

gamma_correction(inbitmap, outbitmap, gamma)
bitmap_hdr *inbitmap, *outbitmap;
double gamma;
{
  register int i;
  byte *r, *g, *b;
  byte *end;
  byte gammatable[256];

  if ( inbitmap->magic != LUGUSED )
    error( 19 );

  copy_bitmap( inbitmap, outbitmap );

  /*
   * Create the gamma correction table.
   */
  for ( i = 0; i < 256; i++ ) {
    gammatable[i] = (byte) (255. * pow( i/255., 1./gamma ) + .5);
  }

  VPRINTF(stderr, "Performing gamma correction\n");
  if ( outbitmap->depth > 8 ) {
    /*
     * 24 bits images haven't cmap, then we need
     * change each component directly.
     */
    /* Pointers to components */
    r = outbitmap->r;
    g = outbitmap->g;
    b = outbitmap->b;
    /* A pointer to the end */
    end = r + outbitmap->xsize * outbitmap->ysize;

    while ( r < end ) {
      *r++ = gammatable[*r];
      *g++ = gammatable[*g];
      *b++ = gammatable[*b];
    }
  }else {
    /*
     * A image with a cmap, we only need change
     * this cmap.
     */
    /* Pointer to cmap */
    r = outbitmap->cmap;

    /* A pointer to the end */
    end = r + 3 * outbitmap->colors;

    while ( r < end ) {
      *r++ = gammatable[*r];
    }
  }
}
