/*
 * 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.
 */
/*
 * cut.c - cut a image with a given virtual window.
 *
 * Author:      Raul Rivero
 *              Mathematics Dept.
 *              University of Oviedo
 * Date:        Sun Jan 12 1992
 * Copyright (c) 1992, Raul Rivero
 *
 */

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

extern int LUGverbose;

cut_bitmap( inbitmap, outbitmap, xini, yini, xsize, ysize)
bitmap_hdr *inbitmap, *outbitmap;
int xini, yini;
int xsize, ysize;
{
  register i, j;
  int xend, yend;
  byte *r, *g, *b;
  byte *rptr, *gptr, *bptr;
  int totalsize;
  int directcolor = ( inbitmap->depth < 24 ? 0 : 1 );

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

  VPRINTF(stderr, "Cutting the image\n");

  /*
   * Where is the end of new image ?
   */
  xend = xsize + xini;
  yend = ysize + yini;
  if ( xend > inbitmap->xsize || yend > inbitmap->ysize)
    error( 12 );

  /*
   * Fill new header and allocate memory.
   */
  outbitmap->magic = LUGUSED;
  outbitmap->xsize = xsize;
  outbitmap->ysize = ysize;
  outbitmap->depth = inbitmap->depth;
  outbitmap->colors = inbitmap->colors;
  totalsize = xsize * ysize;
  r = outbitmap->r = (byte *) Malloc( totalsize );
  g = outbitmap->g = (byte *) Malloc( totalsize );
  b = outbitmap->b = (byte *) Malloc( totalsize );

  /*
   * Set pointers to the first active row.
   */
  rptr= inbitmap->r + yini * inbitmap->xsize;
  if ( directcolor ) {
    gptr= inbitmap->g + yini * inbitmap->xsize;
    bptr= inbitmap->b + yini * inbitmap->xsize;
  }

  for ( i = 0; i < ysize; i++ ) {
    for ( j = 0; j < inbitmap->xsize; j++ ) {
      if ( j < xend && j >= xini ) {
        *r++ = *rptr++;
        if  ( directcolor ) {
          *g++ = *gptr++;
          *b++ = *bptr++;
        }
      }else {
        rptr++;
        if ( directcolor )
          gptr++, bptr++;
      }
    }
  }

}
