#!/usr/bin/perl
#
#	extract_d3hog - extract Descent3 HOG files
#	written by Jan Engelhardt, 2003-2008
#
#	This program is free software; you can redistribute it and/or
#	modify it under the terms of the WTF Public License version 2 or
#	(at your option) any later version.
#

use Getopt::Long;
use strict;
do (($0 =~ m{^(.*)/})[0] || ".")."/shared.pm" ||
	die "Could not load shared.pm: $!\n";

my $ex_out_dir      = ".";
my $ex_archive_file = "-";
my $ex_auto_lower   = 0;
my $ex_verbose      = 0;

Getopt::Long::Configure(qw(bundling));
GetOptions(
	"C=s" => \$ex_out_dir,
	"L"   => \$ex_auto_lower,
	"f=s" => \$ex_archive_file,
	"v"   => \$ex_verbose,
);

&main();

sub main ()
{
	local(*IN, *OUT);

	open(IN, "< $ex_archive_file") ||
		die "Could not open $ex_archive_file: $!\n";
	binmode IN;
	if (&getcf(\*IN, 4) ne "HOG2") {
		die "Not a HOG2 file\n";
	}

	my $num_entries = unpack("V", &getcf(\*IN, 4));
	my $offset      = unpack("V", &getcf(\*IN, 4));
	&getcf(\*IN, 56); # 0xff

	if ($ex_verbose) {
		print STDERR "$num_entries files in archive\n";
	}

	for (my $i = 0; $i < $num_entries; ++$i) {
		# 48 long, 36 name, 4 length, 4 unknown
		my $file_name  = unpack("Z*", &getcf(\*IN, 40));
		my $file_size  = unpack("V", &getcf(\*IN, 4));
		my $time_stamp = unpack("V", &getcf(\*IN, 4));

		if ($ex_auto_lower && $file_name !~ /[a-z]/) {
			$file_name =~ tr/A-Z/a-z/;
		}
		if ($ex_verbose) {
			print "\@$offset: $file_name ($file_size bytes)\n";
		}
		$offset += $file_size;

		my $abs_file = "$ex_out_dir/$file_name";
		&mkdir_p_stripbase($abs_file);
		open(OUT, "> $abs_file") ||
			warn "Could not write to $abs_file: $!\n";
		binmode OUT;
		&transfer(\*OUT, \*IN, $file_size, $offset);
		close OUT;
	}
}
