#!@@PERL@@ -s
#
#	This script is part of rtfdtohtml.
#	Copyright (c) 1996  Elmar Ludwig - Universitaet Osnabrueck
#
#	Collect all Resources (e.g. Images) in a single shared Folder.
#
#	Options:	-link	preserve original files as (hard) links

$place = $ENV{'RTFDSHARED'} ? $ENV{'RTFDSHARED'} : 'shared';
-d $place || mkdir($place, 0777) || die "cannot create $place folder: $!";

# preload the resource cache
opendir(IMAGES, $place) || die "cannot open $place folder: $!";
@files = readdir IMAGES;
closedir IMAGES;

foreach (@files)
{
    $shared{-s _} .= $_.'/' if -f $place.'/'.$_;
}

# process the argument list
foreach $dir (@ARGV)
{
    @tmp = split(/\//, $dir);
    $shared = '../' x @tmp . $place.'/';		# find path to resources

    next unless open(INDEX, $dir.'/index.html');
    read(INDEX, $html, 0xffffff);			# no more than 16MB
    close INDEX;

    @files = ();
    opendir(DIR, $dir) || die "cannot open $dir: $!";
    $dir .= '/';
    while ($file = readdir DIR)				# build local filelist
    {
	push(@files, $file) if ($file !~ /\.html?$/ && -f $dir.$file);
    }
    closedir DIR;

    foreach $file (@files)				# find all matches
    {
	$path = $dir.$file;
	$alias = '';
	$size = -s $path;

	foreach (split(/\//, $shared{$size}))
	{
	    if (system('cmp', '-s', $place.'/'.$_, $path) == 0)
	    {
		$alias = $_;
		last;
	    }
	}

	# no alias found, add file to resource cache
	if ($alias eq '')
	{
	    $count = 0;
	    $alias = $file;
	    $alias = ++$count.'_'.$file while -e $place.'/'.$alias;
	    die "cp command failed" if system('cp', $path, $place.'/'.$alias);
	    $shared{$size} .= $alias.'/';
	}

	# replace this resource with shared alias
	unlink $path || die "cannot remove $path: $!";
	link($place.'/'.$alias, $path) if $link;

	$alias = $shared.$alias;
	$file =~ s/\W/\\$&/g;
	$html =~ s/<[Ii][Mm][Gg] [Ss][Rr][Cc]=["']$file["']/<IMG src="$alias"/g;
	$html =~ s/<[Aa] [Hh][Rr][Ee][Ff]=["']$file["']/<A href="$alias"/g;
    }

    open(INDEX, '>'.$dir.'index.html') || die "${dir}index.html failed: $!";
    print INDEX $html;
    close INDEX;
}
