#!/usr/bin/perl

# Program to demostrate the Logic Operators
# over binaries images
#
# Output: An image in PBM format (Portable BitMap)
#
# Fraga. April 14, 2001

$rows = 80;
$cols = 100;

for ( $i=0; $i<$rows; $i++ ) {
	for ( $j=0; $j<$cols; $j++ ) {
		$imgA[ $cols * $i + $j ] = 0;
		$imgB[ $cols * $i + $j ] = 0;
	}
}
# image A		
for ( $i=30; $i<70; $i++ ) {
	for ( $j=20; $j<60; $j++ ) {
		$imgA[ $cols * $i + $j ] = 1;
	}
}
$val = save_pbm_img ( \@imgA, $rows, $cols, "A.pbm" );
if ( !$val ) {
	printf "All's ok!\n";
}
else {
	print "You have problems...\n";
}

# image B		
for ( $i=10; $i<40; $i++ ) {
	for ( $j=50; $j<80; $j++ ) {
		$imgB[ $cols * $i + $j ] = 1;
	}
}
$val = save_pbm_img ( \@imgB, $rows, $cols, "B.pbm" );
if ( !$val ) {
	printf "All's ok!\n";
}
else {
	print "You have problems...\n";
}

##############################
###   LOGIC OPERATIONS   #####
##############################
## Complement: NOT(A)
for ( $i=0; $i<$rows; $i++ ) {
	for ( $j=0; $j<$cols; $j++ ) {
		$imgC[ $cols * $i + $j ] = !$imgA[ $cols * $i + $j ];
	}
}
$val = save_pbm_img ( \@imgC, $rows, $cols, "notA.pbm" );

## AB = A and B
for ( $i=0; $i<$rows; $i++ ) {
	for ( $j=0; $j<$cols; $j++ ) {
		$imgC[ $cols * $i + $j ] = 
			$imgA[ $cols * $i + $j ] & $imgB[ $cols * $i + $j ];
	}
}
$val = save_pbm_img ( \@imgC, $rows, $cols, "AB.pbm" );

## A + B = A or B
for ( $i=0; $i<$rows; $i++ ) {
	for ( $j=0; $j<$cols; $j++ ) {
		$imgC[ $cols * $i + $j ] = 
			$imgA[ $cols * $i + $j ] | $imgB[ $cols * $i + $j ];
	}
}
$val = save_pbm_img ( \@imgC, $rows, $cols, "AorB.pbm" );

## A xor B
for ( $i=0; $i<$rows; $i++ ) {
	for ( $j=0; $j<$cols; $j++ ) {
		$imgC[ $cols * $i + $j ] = 
			$imgA[ $cols * $i + $j ] ^ $imgB[ $cols * $i + $j ];
	}
}
$val = save_pbm_img ( \@imgC, $rows, $cols, "AxorB.pbm" );

## (NOT(A))B
for ( $i=0; $i<$rows; $i++ ) {
	for ( $j=0; $j<$cols; $j++ ) {
		$imgC[ $cols * $i + $j ] = 
			(!$imgA[ $cols * $i + $j ]) & $imgB[ $cols * $i + $j ];
	}
}
$val = save_pbm_img ( \@imgC, $rows, $cols, "notAB.pbm" );

# Subroutine to save a image in ASCII PBM format
# (see pbm man pages on NETPBM package)
sub save_pbm_img (\@$$$) {  # ( @img, $rows, $cols, $filename );
	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 "P1\n";
	print MYFILE "# file: $filename\n";
	print MYFILE "$mycols $myrows\n";

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