/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

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


#include	<fcntl.h>
#include	<stdio.h>
#include	"ppm_types.h"
#include	"memory_debug.h"
#include	"u_file.h"

void
get_col(unsigned char * col,
	PPM_INFO * ppm,
	int x,
	int y,
	int step,
	int r_width,
	int r_height)
{
int _x,_y;
unsigned char c[3];
int i;
int cc[3];
int cnt;
	cc[0] = cc[1] = cc[2] = 0;
	cnt = 0;
	for ( _y = y - r_height ; _y <= y + r_height ; _y ++ ) {
		_x = x - r_width;
		u_lseek(ppm->pi_fd,
			ppm->pi_offset + (_y * ppm->pi_width + _x) * step,
			SEEK_SET);
		for ( ; _x <= x + r_width ; _x ++ ) {
			u_read(ppm->pi_fd,c,step);
			for ( i = 0 ; i < step ; i ++ )
				cc[i] += c[i];
			cnt ++;
		}
	}
	for ( i = 0 ; i < step ; i ++ )
		col[i] = cc[i]/cnt;
}


int
ppm_converter(
	char * from_ppm,
	char * to_ppm,
	int width,
	int height,
	int (*func)(
		int * x,
		int * y,
		int * radius_width,
		int * radius_height,
		void * work),
	void * work)
{
PPM_INFO * ppm,* target;
int step;
int x,y,xx,yy;
unsigned char col[3];
int r_width,r_height;

	ppm = d_alloc(sizeof(*ppm));
	target = d_alloc(sizeof(*target));
	ppm->pi_fd = u_open(from_ppm,O_RDONLY);

	if ( ppm->pi_fd < 0 ) {
		fprintf(stderr,"cannot open the file \"%s\"\n",
			from_ppm);
		return -1;
	}
	read_header(ppm);
	if ( strcmp(ppm->pi_type,"P5") == 0 )
		step = 1;
	else	step = 3;

	*target = *ppm;
	target->pi_width = width;
	target->pi_height = height;

	target->pi_fd = open(to_ppm,O_RDWR|O_CREAT|O_TRUNC,0644);
	if ( target->pi_fd < 0 ) {
		u_close(ppm->pi_fd);
		fprintf(stderr,"cannot open the file \"%s\"\n",
			to_ppm);
		return -1;
	}
	write_header(target);
	u_lseek(target->pi_fd, target->pi_offset, SEEK_SET);
	for ( y = 0 ; y < target->pi_height ; y ++ )
		for ( x = 0 ; x < target->pi_width ; x ++ ) {
			xx = x;
			yy = y;
			if ( (*func)(&xx,&yy,&r_width,&r_height,work) < 0 )
				col[0] = col[1] = col[2] = 0x80;
			else if ( xx >= 0 && yy >= 0 &&
					xx < ppm->pi_width &&
					yy < ppm->pi_height )
		 		get_col(col,ppm,xx,yy,step,r_width,r_height);
			else	col[0] = col[1] = col[2] = 0x80;
			u_write(target->pi_fd,col,step);
		}
	u_close(ppm->pi_fd);
	u_close(target->pi_fd);
	return 0;
}

