#!/usr/bin/perl

# Perl program to construct a test image.
# Output: test.pgm image.
# Input: It's necessary edit $rows and $cols 
#        values by hand 
#
# Could be much more easy to use the command:
# pgmramp -ellipse 256 256 > output_image.pgm
#
# Fraga April, 2001

$rows = 256;
$cols = 256;

if ( $rows > $cols ) {
	$center = ($cols - 1 )/2;
}
else {
	$center = ($rows - 1 )/2;
}

for ( $i=0; $i<$rows; $i++ ) {
	$di = $center - $i;
	$di2 = $di * $di;
	for ( $j=0; $j<$cols; $j++ ) {
		$dj = $center - $j;
		$dj2 = $dj * $dj;

		$val = sqrt ( $di2 +  $dj2 );
		# Putting image values
		$img[ $cols * $i + $j ] = 255 - int ( $val );
	}
}
$val = save_pgn_img ( \@img, $rows, $cols, "test.pgm" );
if ( !$val ) {
	printf "All's ok!\n";
}
else {
	print "You have problems...\n";
}

# Subroutine to save a image in ASCII PGM format
# (see pgm man pages on NETPBM package)
sub save_pgn_img (\@$$$) {  # ( @img, $rows, $cols );
	local (*myimg) = shift(@_);
	my $myrows = shift(@_);
	my $mycols = shift(@_);
	my $filename = shift(@_);

	my $n = @myimg;
	printf "$n $mycols $myrows $filename\n";

	open ( MYFILE, ">$filename" ) or return 1;

	print MYFILE "P2\n";
	print MYFILE "# file: $filename\n";
	print MYFILE "$mycols $myrows\n";
	print MYFILE "255\n";

	for ( my $i=1; $i <= $myrows*$mycols; $i++ ) {
		printf( MYFILE "%3d ", $myimg[$i-1] ); 
		if ( !($i%17) ) {
			print MYFILE "\n";
		}
	}
	close MYFILE;
	return 0;
}
