/*
 * 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.
 */
/*
 * heightfield.c - convert a bitmap to Rayshade's heightfield
 *
 * Author:      Raul Rivero
 *              Mathematics Dept.
 *              University of Oviedo
 * Date:        Thu Aug 27 1992
 * Copyright (c) 1992, Raul Rivero
 *
 */

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

/*
 * Sorry but I will not comment this program.
 */

write_hf_file( name, image )
char *name;
bitmap_hdr *image;
{
  FILE *handle;

  /* Open the file descriptor */
  if ( name != NULL )
    handle = Fopen( name, "wb" );
  else handle = stdout;

  /* Write the bitmap */
  write_hf( handle, image, (double) 0.5 );

  /* Close the file */
  Fclose( handle );

}

write_hf_file_scale( name, image, scale )
char *name;
bitmap_hdr *image;
double scale;
{
  FILE *handle;

  /* Open the file descriptor */
  if ( name != NULL )
    handle = Fopen( name, "wb" );
  else handle = stdout;

  /* Write the bitmap */
  write_hf( handle, image, scale );

  /* Close the file */
  Fclose( handle );

}

write_hf( handle, bitmap, scale )
FILE *handle;
bitmap_hdr *bitmap;
double scale;
{
  register int i, j;
  int totalsize;
  float *buffer, *ptr;
  byte *r;

  if ( bitmap->xsize != bitmap->ysize ) {
    fprintf( stderr, "Sorry, not squared image\n" );
    exit( 1 );
  }

  totalsize = bitmap->xsize * bitmap->ysize * sizeof( float );
  ptr = buffer = (float *) Malloc( totalsize );
  r = bitmap->r;
  for ( i = 0; i < bitmap->ysize; i++ ) {
    for ( j = 0; j < bitmap->xsize; j++ ) {
      *ptr++ = ((float) *r++ / 255.) * scale;
    }
  }

  Fwrite( &(bitmap->xsize), sizeof(int), 1, handle );
  Fwrite( buffer, totalsize, 1, handle );

  free( buffer );
}
