/*
 * 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.
 */
/*
 * tobw.c - inverse a cmap/component.
 *
 * Author:      Raul Rivero
 *              Mathematics Dept.
 *              University of Oviedo
 * Date:        Tue Mar 03 1992
 * Copyright (c) 1992, Raul Rivero
 *
 */

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

extern int LUGverbose;

toinverse(inbitmap, outbitmap)
bitmap_hdr *inbitmap;
bitmap_hdr *outbitmap;
{
  int totalsize;
  int directcolor;

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

  VPRINTF(stderr, "Converting to inverse cmap\n");
  directcolor = ( inbitmap->depth < 24 ? 0 : 1 );

  /*
   * Fill new header ...
   */
  outbitmap->magic = LUGUSED;
  outbitmap->xsize = inbitmap->xsize;
  outbitmap->ysize = inbitmap->ysize;
  outbitmap->depth = inbitmap->depth;
  outbitmap->colors = ( 1 << outbitmap->depth );
  totalsize = outbitmap->xsize * outbitmap->ysize;
  /* One component => r */
  outbitmap->r = (byte *) Malloc( totalsize );

  if ( !directcolor ) {
    /*
     * If the image has less than 24 planes then we only
     * need convert its palette.
     */
    outbitmap->cmap = (byte *) cmap_to_inverse( inbitmap );
    /* Copy the raster information */
    bcopy( inbitmap->r, outbitmap->r, totalsize );
  }else {
    /*
     * We have a real color image.
     */

    /* Allocate space, ... */
    outbitmap->g = (byte *) Malloc( totalsize );
    outbitmap->b = (byte *) Malloc( totalsize );

    /* ... copy each component ... */
    bcopy( inbitmap->r, outbitmap->r, totalsize );
    bcopy( inbitmap->g, outbitmap->g, totalsize );
    bcopy( inbitmap->b, outbitmap->b, totalsize );

    /* ... and inverse it. */
    inverse( outbitmap->r, totalsize );
    inverse( outbitmap->g, totalsize );
    inverse( outbitmap->b, totalsize );
  }
}

byte *cmap_to_inverse( image )
bitmap_hdr *image;
{
  byte *buffer;

  if ( image->depth > 8 )
    error( 11 );

  buffer = (byte *) Malloc ( 3 * image->colors );
  bcopy( image->cmap, buffer, 3 * image->colors );

  /* Convert that buffer to its inverse */
  inverse( buffer, 3 * image->colors );

  return buffer;
}

inverse( buffer, size )
byte *buffer;
int size;
{
  while ( size-- )
    *buffer++ = (byte) ABS( *buffer - 255 );
}
