Debian Codegraph @

tools/deresx

raw
1 #!/usr/bin/perl
2 #
3 # Seven Kingdoms: Ancient Adversaries
4 #
5 # Copyright 1997,1998 Enlight Software Ltd.
6 # Copyright 2017 Jesse Allen
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #
21 #
22
23 use warnings;
24 use strict;
25
26 use File::Basename;
27 use File::Path qw(make_path);
28 use File::Spec;
29
30 if (@ARGV < 1) {
31 print "Usage: $0 FILE.RES out_dir .ext\n";
32 print "Extracts all files from FILE.RES, giving each file the defined suffix .ext\n";
33 print "This is not for a 'LIBDB' generated resource file.\n";
34 exit 1;
35 }
36
37 my ($res, $outdir, $ext) = @ARGV;
38 if (!defined($outdir)) {
39 $outdir = "";
40 }
41 if (!defined($ext)) {
42 $ext = "";
43 }
44
45 if ($outdir ne "" && ! -d $outdir) {
46 eval { make_path($outdir) };
47 if ($@) {
48 print "Error: Cannot create $outdir\n";
49 exit 1;
50 }
51 }
52
53 my $fh;
54 if (!open($fh, '<', $res)) {
55 print "Error: Cannot open $res\n";
56 exit 1;
57 }
58 my $file_size = -s $res;
59 my $buf;
60 my $last_offset = 0;
61 read($fh, $buf, 2);
62 my $rec_count = unpack('s', $buf);
63 my $header_size = 2 + 13*$rec_count + 13;
64 my @files;
65 my @sizes;
66 my $read_bytes = $header_size;
67 for (my $i = 0; $i < $rec_count; $i++) {
68 $read_bytes += 13;
69 read($fh, $buf, 13);
70 my ($rec_name, $offset) = unpack('Z9l', $buf);
71 push(@files, $rec_name);
72 if ($last_offset) {
73 push(@sizes, $offset - $last_offset);
74 }
75 if ($last_offset > $offset) {
76 print "Error: Corrupt res file.\n";
77 exit 1;
78 }
79 $last_offset = $offset;
80 }
81 $read_bytes += 13;
82 read($fh, $buf, 13);
83 my ($rec_name, $offset) = unpack('Z9l', $buf);
84 push(@sizes, $offset - $last_offset);
85
86 for (my $i = 0; $i < $rec_count; $i++) {
87 $read_bytes += $sizes[$i];
88 read($fh, $buf, $sizes[$i]);
89 my $filename = sprintf("%.5d-%s%s", $i, $files[$i], $ext);
90 my $outfile = File::Spec->catfile($outdir, $filename);
91 my $fh2;
92 if (!open($fh2, '>', $outfile)) {
93 print "Error: Cannot open $outfile\n";
94 exit 1;
95 }
96 print $fh2 $buf;
97 close($fh2);
98 }
99
100 close($fh);
101
102 if ($read_bytes < $file_size) {
103 print "Error: Trailing data\n";
104 exit 1;
105 }
106
107 exit 0;