/*
 * $Id: my_Image.cxx,v 4.4 2004/06/04 07:53:21 hut66au Exp $
 *
 * Imview, the portable image analysis application
 * http://www.cmis.csiro.au/Hugues.Talbot/imview
 * ----------------------------------------------------------
 *
 *  Imview is an attempt to provide an image display application
 *  suitable for professional image analysis. It was started in
 *  1997 and is mostly the result of the efforts of Hugues Talbot,
 *  Image Analysis Project, CSIRO Mathematical and Information
 *  Sciences, with help from others (see the CREDITS files for
 *  more information)
 *
 *  Imview is Copyrighted (C) 1997-2001 by Hugues Talbot and was
 *  supported in parts by the Australian Commonwealth Science and 
 *  Industry Research Organisation. Please see the COPYRIGHT file 
 *  for full details. Imview also includes the contributions of 
 *  many others. Please see the CREDITS file for full details.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
 * */


/*------------------------------------------------------------------------
 *
 * Image drawing complementary functions.
 *
 * FL has good capabilities, but they can always be augmented.
 * Hugues Talbot	 4 Nov 1997
 *      
 *-----------------------------------------------------------------------*/
#include <FL/Fl_Object.H>
#include <FL/Fl_Image.H>
#include <FL/x.H>
#include <FL/fl_draw.H>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "imview.hxx"


// This variable used for synchronization.
volatile bool im_draw_finished = true; 

void freeOffScreenPixmap(Fl_RGB_Image *b)
{
    if (b && b->id) {
	fl_delete_offscreen((Fl_Offscreen)b->id);
	b->id = 0;
    }
	
    return;
}

void fl_draw_clipped(Fl_RGB_Image *b,	 /* Input image */
		     int ox,     /* x origin of where the image will be drawn in the window */
		     int oy,     /* y origin of where the image will be drawn in the window */
		     int x,	 /* x origin of the bounding box in the image */
		     int y,	 /* y origin of the bounding box in the image */
		     int w,	 /* width of the bounding box in the image */
		     int h) 	 /* height of the bounding box in the image */
{
/** draws a Fl_RGB_Image object clipped to a given bounding box

RETURN VALUE:	void 

DESCRIPTION:
The input Fl_RGB_Image is drawn, subject to the given bounding box.
The Fl_RGB_Image is *NOT* centered in the bounding box. It is expected
that x > 0, y > 0, w > 0, h > 0 and w and h are smaller than the
image's dimension.

HISTORY:
Hugues Talbot	 4 Nov 1997

TESTS:

REFERENCES:

KEYWORDS:

**/

    if (!b->id) { 
	dbgprintf("Creating an off-screen pixmap (w=%d, h=%d)\n",
		  b->w(), b->h());

#if defined(MACOSX_CARBON) || defined(WIN32)
        b->id = (void *)fl_create_offscreen(w,h); 
#else
        b->id = (unsigned)fl_create_offscreen(w,h);
#endif

	fl_begin_offscreen((Fl_Offscreen)b->id);
	fl_push_no_clip();
	if (b->d() == 1) {
	    dbgprintf("Call to fl_draw_image_mono\n");
	    // serious change in FLTK-1.1.x
	    fl_draw_image_mono((const uchar *)(b->data()[0]), 0, 0, b->w(), b->h(), b->d());
	} else {
	    dbgprintf("Call to fl_draw_image (colour)\n");
	    // serious change in FLTK-1.1.x
	    fl_draw_image((const uchar *)(b->data()[0]), 0, 0, b->w(), b->h(), b->d());
	}
	fl_pop_clip();
	fl_end_offscreen();
	dbgprintf("Offscreen buffer pointer: %p\n", b->id);
    } else {
	dbgprintf("Now using the off-screen pixmap\n");
    }

    // incorrect entries
    if (w < 0) w = 0;
    if (h < 0) h = 0;
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    if (w > b->w()) {
	w = b->w();
    } 
    if (h > b->h()) {
	h = b->h();
    }

    // somewhat subtle cases
    if (x+w > b->w()) {
	// adjust x
	x = b->w() - w;
    }
    if (y+h > b->h()) {
	// adjust y
	y = b->h() - h;
    }

    dbgprintf("Now displaying image: x=%d, y=%d, w=%d, h=%d, ox=%d, oy=%d, b->id:%p\n",
	      x,y,w,h,ox,oy, b->id);
    // equivalent to:
    // XCopyArea(fl_display, b->id, fl_window, fl_gc, x, y, w, h, ox, oy);
    fl_copy_offscreen(ox, oy, w, h, (Fl_Offscreen)b->id, x, y);
    im_draw_finished = true;
}


void fl_draw_clipped_nobuf(Fl_RGB_Image *b,	 /* Input image */
			   int ox,     /* x origin of where the image will be drawn in the window */
			   int oy,     /* y origin of where the image will be drawn in the window */
			   int x,	 /* x origin of the bounding box in the image */
			   int y,	 /* y origin of the bounding box in the image */
			   int w,	 /* width of the bounding box in the image */
			   int h)	 /* height of the bounding box in the image */
{
/** draws a Fl_RGB_Image object clipped to a given bounding box

RETURN VALUE:	void 

DESCRIPTION:
The input Fl_RGB_Image is drawn, subject to the given bounding box.
The Fl_RGB_Image is *NOT* centered in the bounding box. It is expected
that x > 0, y > 0, w > 0, h > 0 and w and h are smaller than the
image's dimension.

This functions doesn't use an off-screen pixmap. It is slower
to update but uses less memory.

HISTORY:
Hugues Talbot	 4 Nov 1997

TESTS:

REFERENCES:

KEYWORDS:

**/
    static uchar *buf = 0;
    int    d, i;

    d = b->d();  // image depth
    
    // incorrect entries
    if (w < 0) w = 0;
    if (h < 0) h = 0;
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    if (w > b->w()) {
	w = b->w();
    } 
    if (h > b->h()) {
	h = b->h();
    }
    
    // somewhat subtle cases
    if (x+w > b->w()) {
	// adjust x
	x = b->w() - w;
    }
    if (y+h > b->h()) {
	// adjust y
	y = b->h() - h;
    }
    

    if (buf) {
	free(buf);
	buf = 0;
    }
    // realloc buffer, don't care about old content.
    //dbgprintf("Display: b->w=%d, b->d=%d, d=%d, x=%d, y=%d, w=%d, h=%d\n",
    //	   b->w, b->d, d, x, y, w, h);
    buf = (uchar *)malloc(w * h * d * sizeof(uchar));
    for (i = 0 ; i < h ; i++) {
	memcpy(buf + i*w*d, b->data()[0] + d*x + (y+i) * b->w() * d, w * d);
    }

    if (d == 1) {
	dbgprintf("Call to fl_draw_image_mono\n");
	fl_draw_image_mono((const uchar *)buf, ox, oy, w, h, d, 0);
        im_draw_finished = true;
    } else {
	dbgprintf("Call to fl_draw_image\n");
	fl_draw_image((const uchar *)buf, ox, oy, w, h, d, 0);
        im_draw_finished = true;
    }
	
}


static void zoominwh(uchar *outbuf,	 /* output buffer  */
		     const uchar *inbuf,	 /* input buffer */
		     int ow,	 /* output buffer width */
		     int oh,	 /* output buffer height */
		     int iw,	 /* input buffer width */
		     int d,	 /* bytes per pixel in both buffers */
		     int x,	 /* x origin of bounding box in input buffer */
		     int y,	 /* y origin of BB  */
		     int w,	 /* width of BB */
		     int h)	 /* height of BB */
{
/** fast zoom in, both in width and height, on part of a buffer

RETURN VALUE:	static void 
no return value

DESCRIPTION:
This function takes a subset of an input buffer and zooms it in
to fit in the dimensions of the output buffer.

HISTORY:
written by Hugues Talbot	14 Nov 1997
TESTS:

REFERENCES:

KEYWORDS:

**/

    int    i, j, k, ii;
    int    ex, inc1x, inc2x;
    int    ey, inc1y, inc2y;
    uchar  *op;
    const  uchar *ip;
    
    inc1y = 2 * (h - oh);
    inc2y = 2 * h;
    ey = inc1y + h;  // 2*h - oh; would start in the middle of a pixel

    
    for (i = 0, ii = 0 ; i < oh ; i++) {
	if (i > 0) { 
	    // we cannot even think about duplicating lines if none are present
	    if (ey > 0) {
		// we have to work out a new line
		ey += inc1y;
		ii++;
	    } else {
		// we can simply duplicate the previous line
		memcpy(outbuf + i*ow*d, outbuf + (i-1)*ow*d, ow*d);
		ey += inc2y;
		continue;
	    }
	}
	op = outbuf + i*ow*d;
	ip = inbuf + d*x + (y+ii) * iw * d;
	// first pixel of the line
	for (k = 0 ; k < d ; k++) {
	    *op++ = *(ip + k);
	}
	// rest of the pixels along that line
	inc1x = 2 * (w - ow);
	inc2x = 2 * w;
	ex = inc1x + w; // 2*w - ow; would start in the middle of a pizel
	
	for (j = 1 ; j < ow ; j++) {
	    if (ex > 0) {
		ip += d;
		ex += inc1x;
	    } else {
		ex += inc2x;
	    }
	    // duplicate pixels
	    for (k = 0 ; k < d ; k++) {
		*op++ = *(ip + k);
	    }
	}
    }
}


static void zoominh_only(uchar *outbuf,	 /* output buffer  */
                         const uchar *inbuf,	 /* input buffer */
                         int ow,	 /* output buffer width */
                         int oh,	 /* output buffer height */
                         int iw,	 /* input buffer width */
                         int d,	 /* bytes per pixel in both buffers */
                         int x,	 /* x origin of bounding box in input buffer */
                         int y,	 /* y origin of BB  */
                         int w,	 /* width of BB */
                         int h)	 /* height of BB */
{
/** fast zoom in height, on part of a buffer

RETURN VALUE:	static void 
no return value

DESCRIPTION: This function zooms in part of the images in the vertical
direction only. This allows the zoom in function to be implemented in
a separable way: zoom h first and then w. This is also useful when the
user resizes the main window in such a way that one dimension is
zoomed in while the other is zoomed out.

HISTORY:
written by Hugues Talbot	30 Sep 2002.

TESTS:

REFERENCES:

KEYWORDS:

**/

    int    i, ii;
    int    ey, inc1y, inc2y;
    
    assert(oh > h); // we are zooming in
    assert(h > 0);   // the bounding box does not have 0 height

    inc1y = 2 * (h - oh);
    inc2y = 2 * h;
    ey = inc1y + h;  // 2*h - oh; would start in the middle of a pixel

    assert(ow == w); // width should be unchanged
    
    // first line special case:
    ii = 0;
    memcpy(outbuf, inbuf + d * (x + y * iw), ow*d);
    if (ey > 0) {
	ey += inc1y;
	++ii;
    } else { 
	ey += inc2y;
    }

    for (i = 1 ; i < oh ; ++i) {
        if (ey > 0) {
            // we have to work out a new line
            ey += inc1y;
            memcpy(outbuf + d * i*ow, 
                   inbuf + d* (x + (y+ii) * iw), 
                   ow*d);
            ++ii;
        } else {
            // we can simply duplicate the previous line
            memcpy(outbuf + i*ow*d, 
                   outbuf + (i-1)*ow*d, 
                   ow*d);
            ey += inc2y;
            continue;
        }
    }
}


static void zoominw_only(uchar *outbuf,	 /* output buffer  */
                         const uchar *inbuf,	 /* input buffer */
                         int ow,	 /* output buffer width */
                         int oh,	 /* output buffer height */
                         int iw,	 /* input buffer width */
                         int d,	 /* bytes per pixel in both buffers */
                         int x,	 /* x origin of bounding box in input buffer */
                         int y,	 /* y origin of BB  */
                         int w,	 /* width of BB */
                         int h)	 /* height of BB */
{
/** fast zoom in width on part of a buffer

RETURN VALUE:	static void 
no return value

DESCRIPTION: 

This function zooms on part of a buffer in the horizontal direction
only (does not zoom in height). This allows the zoom-in function to be
implemented in a separable way: zoom w first and then h (say). This is
also useful when the user resizes the main window in such a way that
one dimension is zoomed in while the other is zoomed out.

HISTORY:
written by Hugues Talbot	30 Sep 2002
TESTS:

REFERENCES:

KEYWORDS:

**/

    int    i, j, k;
    int    ex, inc1x, inc2x;
    int    ey, inc2y;
    uchar  *op;
    const  uchar *ip;
    
    assert( h == oh ); // must have same height

    inc2y = 2 * h; // = 2*h
    ey = h;  // = h 


    for (i = 0 ; i < oh ; ++i) {
	op = outbuf + i*ow*d;
	ip = inbuf + d*x + (y+i) * iw * d;
	// first pixel of the line
	for (k = 0 ; k < d ; ++k) {
	    *op++ = *(ip + k);
	}
	// rest of the pixels along that line
	inc1x = 2 * (w - ow);
	inc2x = 2 * w;
	ex = inc1x + w; // 2*w - ow; would start in the middle of a pizel
	
	for (j = 1 ; j < ow ; ++j) {
	    if (ex > 0) {
		ip += d;
		ex += inc1x;
	    } else {
		ex += inc2x;
	    }
	    // duplicate pixels
	    for (k = 0 ; k < d ; ++k) {
		*op++ = *(ip + k);
	    }
	}
    }
}

static void zoomoutw_smooth(uchar *outbuf,	 /* output buffer  */
			    const uchar *inbuf,	 /* input buffer */
			    int ow,	 /* width of the output buffer */
			    int d,	 /* number of bytes per pixel in both buffers */
			    int iw,	 /* width of the input buffer */
			    int x,	 /* x coord. bounding box in input buffer */
			    int y,	 /* y coord  BB                           */
			    int w,	 /* w width  BB */
			    int h)	 /* h height BB */
{
/** This function zooms out a buffer in the x direction

RETURN VALUE:	static void 

DESCRIPTION:
This function zooms out a buffer in the x direction. The algorithm
does nearest neighbour smoothing. 

HISTORY:
written by Hugues Talbot	14 Nov 1997

TESTS:

REFERENCES:

KEYWORDS:

**/

    int                     i, j, k;
    int                     *accum;
    int                     nbaccum;
    int                     ex, inc1x, inc2x;
    uchar                   *op;
    const uchar             *ip;
	
    accum = new int[d]; // dynamic array 
    // zoom out in the horizontal direction
    for (i = 0 ; i < h ; i++) {
	// set up the integer counters
	ex = 2*ow - w;
	inc1x = 2 * (ow - w);
	inc2x = 2 * ow;
	// set up the line pointers
	// output will be the intermediary buffer
	op = outbuf + i*ow*d; // same as above
	ip = inbuf + d * (x + (y+i) * iw) ; // line are not zoomed out yet.
	// work out what to write
	
	// -- first pixel
	for (k = 0 ; k < d ; k++)
	    accum[k] = 0;
	nbaccum = 0;
        // rest of the line
	for (j = 0 ; j < w ; j++) {
	    // fill in the accumulators
	    for (k = 0 ; k < d ; k++)
		accum[k] += *ip++; // ip is always advancing
	    nbaccum++;
	    
	    if (ex > 0) {
		// time has come to write out something;
		for (k = 0 ; k < d ; k++) {
		    *op++ = (int)(((double)(accum[k])/nbaccum) + 0.5); // write out the average
		    accum[k] = 0; // clear the accumulator
		}
		nbaccum = 0;
		ex += inc1x;
	    } else {
		ex += inc2x;
	    }
	}
    }
    
    delete[] accum;
}

static void zoomoutw(uchar *outbuf,	 /* output buffer  */
		     const uchar *inbuf,	 /* input buffer */
		     int ow,	 /* width of the output buffer */
		     int d,	 /* number of bytes per pixel in both buffers */
		     int iw,	 /* width of the input buffer */
		     int x,	 /* x coord. bounding box in input buffer */
		     int y,	 /* y coord  BB                           */
		     int w,	 /* w width  BB */
		     int h)	 /* h height BB */
{
/** This function zooms out a buffer in the x direction

RETURN VALUE:	static void 

DESCRIPTION:
This function zooms out a buffer in the x direction. No smoothing,
just sub-sampling.

HISTORY:
written by Hugues Talbot	14 Nov 1997

TESTS:

REFERENCES:

KEYWORDS:

**/

    int                     i, j, k;
    int                     ex, inc1x, inc2x;
    uchar                   *op;
    const uchar              *ip;
	
    // zoom out in the horizontal direction
    for (i = 0 ; i < h ; i++) {
	// set up the integer counters
	ex = 2*ow - w;
	inc1x = 2 * (ow - w);
	inc2x = 2 * ow;
	// set up the line pointers
	// output will be the intermediary buffer
	op = outbuf + i*ow*d; // same as above
	ip = inbuf + d * (x + (y+i) * iw) ; // line are not zoomed out yet.
	// work out what to write
	for (j = 0 ; j < w ; j++) {
	    if (ex > 0) {
		// time has come to write out something;
		for (k = 0 ; k < d ; k++) {
		    *op++ = *ip++;
		}
		ex += inc1x;
	    } else {
		ex += inc2x;
		ip += d; // next pixel
	    }
	    
	}
    }
}

static void zoomouth_smooth(uchar *outbuf,	 /* Output buffer  */
			    const uchar *inbuf,	 /* input buffer */
			    int oh,	 /* height of the output buffer */
			    int d,	 /* number of bytes per pixel */
			    int iw,	 /* width of the input buffer */
			    int x,	 /* x origin of bounding box in input buffer */
			    int y,	 /* y origin for BB */
			    int w,	 /* width of BB */
			    int h)	 /* height of BB */
{
    int                     i, j, k;
    int                     *accum;
    int                     nbaccum;
    int                     ey, inc1y, inc2y;
    uchar                   *op;
    const uchar             *ip;

    accum = new int[d];
    // now zoom out the vertical direction
    for (j = 0 ; j < w ; j++) {
	// set up the integer counters
	ey = 2*oh -h;
	inc1y = 2 * (oh - h);
	inc2y = 2 * oh;
	// output will be the final buffer
	op = outbuf + j * d;
	// input will be the intermediary buffer allocated above
	ip = inbuf + d * ((x+j) + y*iw);
	// work out what to write
	// first pixel
	for (k = 0 ; k < d ; k++) 
	    accum[k] = 0;
	nbaccum = 0;
	// rest of the column
	for (i = 0 ; i < h ; i++) {
	    // fill in the accumulators
	    for (k = 0 ; k < d ; k++) {
		accum[k] += *(ip+k);
	    }
	    ip +=  iw * d;  // skip one line
	    nbaccum++;
	    
	    if (ey > 0) {
		// time has come to write out something
		for (k = 0 ; k < d ; k++) {
		    *(op+k) = (int)(((double)(accum[k])/nbaccum) + 0.5); // write out the average
		    accum[k] = 0; // clear the accumulator
		}
		op += w * d; // skip one line
		nbaccum = 0;
		ey += inc1y;
	    } else {
		ey += inc2y;
	    }
	}
    }
    // free the dynamic array
    delete[] accum;
}


static void zoomouth(uchar *outbuf,	 /* Output buffer  */
		     const uchar *inbuf,	 /* input buffer */
		     int oh,	 /* height of the output buffer */
		     int d,	 /* number of bytes per pixel */
		     int iw,	 /* width of the input buffer */
		     int x,	 /* x origin of bounding box in input buffer */
		     int y,	 /* y origin for BB */
		     int w,	 /* width of BB */
		     int h)	 /* height of BB */
{
    int                     i, j, k;
    int                     ey, inc1y, inc2y;
    uchar                   *op;
    const uchar             *ip;

    // now zoom out the vertical direction
    for (j = 0 ; j < w ; j++) {
	// set up the integer counters
	ey = 2*oh -h;
	inc1y = 2 * (oh - h);
	inc2y = 2 * oh;
	// output will be the final buffer
	op = outbuf + j * d;
	// input will be the intermediary buffer allocated above
	ip = inbuf + d * ((x+j) + y*iw);
	// work out what to write
	// rest of the column
	for (i = 0 ; i < h ; i++) {
	    if (ey > 0) {
		// time has come to write out something
		for (k = 0 ; k < d ; k++) {
		    *(op+k) = *(ip+k);
		}
		op += w * d; // skip one line
		ey += inc1y;
	    } else {
		ey += inc2y;
	    }
	    ip +=  iw * d;  // skip one line
	}
    }
}

/* zcnb stands for zoomed, clipped, nobuffering */
void fl_draw_zcnb(Fl_RGB_Image *b,	 /* Input image */
		  int ox,     /* x origin of where the image will be drawn in the window */
		  int oy,     /* y origin of where the image will be drawn in the window */
		  int ow,     /* width of the window the image will be drawn to */
                  int oh,     /* height of the window the image will be drawn to */
		  int x,	 /* x origin of the bounding box in the image */
		  int y,	 /* y origin of the bounding box in the image */
		  int w,	 /* width of the bounding box in the image */
		  int h,	 /* height of the bounding box in the image */
		  int drawsmooth)  /* should the output be smooth or not */
{
/** draws a Fl_RGB_Image object zoomed and clipped to a given bounding box

RETURN VALUE:	void 

DESCRIPTION:
The input Fl_RGB_Image is drawn, subject to the given bounding box.
The Fl_RGB_Image is *NOT* centered in the bounding box. It is expected
that x > 0, y > 0, w > 0, h > 0 and w and h are smaller than the
image's dimension. The portion of the image in the input bounding
box is scaled to fit in the output window frame.

This functions doesn't use an off-screen pixmap. It is slower
to update but uses less memory.

HISTORY:
Hugues Talbot	 4 Nov 1997

TESTS:

REFERENCES:

KEYWORDS:

**/
    int d;
    static uchar *buf = 0;
    static uchar *buf2 = 0;
    
    d = b->d();  // image depth
    
    // incorrect entries
    if (ow < 0) ow = 0;
    if (oh < 0) oh = 0;
    if (w < 0) w = 0;
    if (h < 0) h = 0;
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    if (w > b->w()) {
	w = b->w();
    } 
    if (h > b->h()) {
	h = b->h();
    }
    
    // somewhat subtle cases
    if (x+w > b->w()) { // bounding box exceed right hand boundary
	// adjust x
	x = b->w() - w;
    }
    if (y+h > b->h()) { // bounding box exceeds bottom boundary
	// adjust y
	y = b->h() - h;
    }
    

    if (buf) {
	free(buf);
	buf = 0; // buf may not have been allocated even if this function has been called before
    }

    // realloc buffer, don't care about old content, realloc would be less efficient
    buf = (uchar *)malloc(ow * oh * d * sizeof(uchar));


    //dbgprintf("Display: ox=%d oy=%d ow=%d oh=%d x=%d y=%d w=%d h=%d\n",
    //	   ox, oy, ow, oh, x , y , w, h);
    
   
    
    // bresenham-like processing
    if (ow >= w && ((ow != w) || (oh >= h))) {
	if (oh >= h) {
	    zoominwh(buf, (const uchar*)(b->data()[0]), ow, oh, b->w(), d, x, y, w, h);
	} else { // oh < h
	    dbgprintf("Case (1) where (ow=%d >= w=%d && oh=%d < h=%d) \n",
		      ow, w, oh, h);
            // Zooming in w and zooming out in h
            if (buf2 != 0) {
                free(buf2);
                buf2 = 0;
            }
            buf2 = (uchar *)malloc(ow * h * d * sizeof(uchar));
            zoominw_only(buf2, (const uchar*)(b->data()[0]), ow, h, b->w(), d, x, y, w, h);
            if (drawsmooth)
                zoomouth_smooth(buf, buf2, oh, d, ow, 0,0,ow,h);
            else
                zoomouth(buf, buf2, oh,d,ow,0,0,ow,h);
            
	}
    } else { // ow <= w
	// whereas for zooming in it is OK to just show larger pixels (in general)
	// zooming out requires some smoothing or the result just looks awful.
	// the idea here is to accumulate pixel values in the larger window until
	// one pixel has to be written in the smaller one. The average of the
	// accumulated pixels is written.

		
	// in this case we need a second buffer for the intermediary image
	if (buf2 != 0) {
	    free(buf2);
	    buf2 = 0;
	}
	buf2 = (uchar *)malloc(ow * h * d * sizeof(uchar));
	// zoom out the x dimension
	if (drawsmooth)
	    zoomoutw_smooth(buf2,(const uchar*)(b->data()[0]),ow,d,b->w(),x,y,w,h);
	else
	    zoomoutw(buf2,(const uchar *)(b->data()[0]),ow,d,b->w(),x,y,w,h);
	if (oh < h) {
	    if (drawsmooth)
		zoomouth_smooth(buf, buf2, oh,d,ow,0,0,ow,h);
	    else
		zoomouth(buf, buf2, oh,d,ow,0,0,ow,h);
	} else if (oh == h) {
	    // this should work
	    memcpy(buf, buf2, ow*oh*d);
	} else {
	    dbgprintf("Case (2) where (ow = %d < w = %d && oh = %d > h = %d)\n",
                      ow, w, oh, h);
            // zooming out in w and in in h
            // (zoomin out in w already done)
            zoominh_only(buf, buf2, ow, oh, ow, d, 0, 0, ow, h);
	}
    }

    if (d == 1) {
	dbgprintf("Call to fl_draw_image\n");
	fl_draw_image_mono((const uchar *)buf, ox, oy, ow, oh, d, 0);
        im_draw_finished = true;
    } else {
	dbgprintf("Call to fl_draw_image\n");
	fl_draw_image((const uchar *)buf, ox, oy, ow, oh, d, 0);
        im_draw_finished = true;
    }
}
