#!/usr/bin/perl -w

use Gimp ":auto";
use Gimp::Fu;

sub mortal_add_image
{
	my ($img, $filename, $x, $y) = @_;
	
	my ($pngimg, $pnglayer, $width, $height, $layername, $newlayer, $float );
	
	print STDERR "Loading $filename\n";
	
	# 1. LOAD THE PNG IMAGE
	
	$pngimg = gimp_file_load( $filename, $filename );
	$pnglayer = gimp_image_get_active_layer( $pngimg );
	gimp_edit_copy( $pnglayer );
	$width = gimp_image_width( $pngimg );
	$height = gimp_image_height( $pngimg );
	
	# 2. PASTE THE IMAGE INTO $img
	
	$layername = substr( $filename, rindex( $filename, "/" ) + 1 );
	$bglayer = gimp_image_get_active_layer( $img );
	# $newlayer = gimp_layer_new( $img, $width, $height, RGBA_IMAGE, $layername, 100, NORMAL_MODE );
	# gimp_image_add_layer( $img, $newlayer, -1 );
	# gimp_image_set_active_layer( $img, $newlayer );
	$float = gimp_edit_paste( $bglayer, 0 );
	gimp_floating_sel_to_layer( $float );
	gimp_layer_set_name( $float, $layername );
	gimp_layer_set_offsets( $float, $x, $y );
	gimp_layer_set_visible( $float, 0 );
        	
	# 3. CLEAN UP $pngimage
	
	gimp_image_delete( $pngimg );
}

sub mortal_load
{
	my ($directory) = @_;
	$img = gimp_image_new( 720, 576, RGB );
	gimp_image_undo_freeze( $img );
	$layer = gimp_layer_new( $img, 720, 576, RGBA_IMAGE, "Background", 100, NORMAL_MODE );
	gimp_image_add_layer( $img, $layer, -1 );
	gimp_image_set_active_layer( $img, $layer );
	
	@files = `ls $directory/*.png | grep -v /learn_`;
	@files = sort @files;
	
	open NEURALLOG, "$directory/neural.log";
	while (<NEURALLOG>)
	{
		($x,$y,$filename) = /'x'=>(\d+),\s*'y'=>(\d+),\s*'filename'.*\/(.*) },/;
		$XCoords{$filename} = $x;
		$YCoords{$filename} = $y;
	}
	close NEURALLOG;
	
	gimp_progress_init( "Loading " . scalar @files . " images ..." );
	
	for ( $i = 0; $i < scalar @files; ++$i )
	{
		gimp_progress_update( $i / scalar @files );
		
		$filename = $files[$i];
		chomp $filename;
		$basename = substr( $filename, rindex( $filename, "/" ) + 1 );
		$x = $XCoords{$basename};
		$y = $YCoords{$basename};
		mortal_add_image( $img, $filename, $x, $y );
		
	}
	
	gimp_image_undo_thaw( $img );
	return $img;
}

register
	"mortal_load",
	"Load all Mortal Szombat images",
	"Select a directory, all .png images, except for those which contain
learn_ will be loaded into a single image.",
	"UPi <upi\@apocalypse.rulez.org>",
	"(C) UPi",
	"2002-07-06",
	"<Toolbox>/Xtns/Perl-Fu/Mortal load",
	"*",
	[
	 [PF_STRING,	"directory", "Source directory", $ENV{HOME}]
	],
	\&mortal_load;

exit main();
