/********************************************************************

PhatBeat - A simple beat-counter for producers, DJs, or anybody else.
Copyright (C) 2004 Jack Chatterton <chattj AT postreal.org>

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-1307, USA.

*********************************************************************/

// Routine to resize a block of surface to a new block of surface.

#include "SDL.h"
using namespace std;
#include <math.h>
using namespace std;

#include "phatx.h"
using namespace std;

SDL_Surface *Resize(SDL_Surface *src, SDL_Rect *newsize) {
	int i, j;			
	Color *spixel, *dpixel;
	Color t00, t01, t10, t11, pcolor;
	SDL_Surface *tempsurf = SDL_CreateRGBSurface(src->flags, \
			newsize->w, newsize->h, 32, 0, 0, 0, 0);
	SDL_Surface *returnme = SDL_ConvertSurface(tempsurf, src->format, src->flags);
	
	SDL_LockSurface(src);
	SDL_LockSurface(tempsurf);
	SDL_LockSurface(returnme);
	
	spixel = (Color *) src->pixels;
	dpixel = (Color *) returnme->pixels;

	float wratio = (float)src->w / (float)returnme->w;
	float hratio = (float)src->h / (float)returnme->h;
	
	for(j = 0; j < newsize->h; j++)
		for(i = 0; i < newsize->w; i++)	{
			t00 = spixel[(int)(floor(i * wratio)) + \
				(int)((floor(j * hratio))*src->w)];
			t01 = spixel[(int)(floor(i * wratio)) + \
				(int)((ceil(j * hratio))*src->w)];
			t10 = spixel[(int)(ceil(i * wratio)) + \
				(int)((floor(j * hratio))*src->w)];
			t11 = spixel[(int)(ceil(i * wratio)) + \
				(int)((ceil(j * hratio))*src->w)];
			
			pcolor.r = (t00.r + t01.r + t10.r + t11.r) / 4;
			pcolor.g = (t00.g + t01.g + t10.g + t11.g) / 4;
			pcolor.b = (t00.b + t01.b + t10.b + t11.b) / 4;
			pcolor.a = (t00.a + t01.a + t10.a + t11.a) / 4;
			
			dpixel[i + (j * newsize->w)] = pcolor;
		}
	
	SDL_UnlockSurface(returnme);
	SDL_UnlockSurface(tempsurf);
	SDL_UnlockSurface(src);
		
	return returnme;
}
