#!/usr/bin/perl
#
# 'joinfile.pl' [ MBD 16:46 28/02/2005 ]
#
# Joins files and builds some info.
#
# Usage:
# joinfile [dir] [basename] [addheader]
#
# [addheader]: false|true. Optional, defaults to false, appends a header to
# the archive: first byte: number of files, followed by file sizes in two
# byte words, big endian.
use strict;
use warnings;
use File::Basename;
#
if (@ARGV < 2) {
print ("\nUsage:\n\tjoinfile
[addheader]\n\n");
exit (1);
}
# parameters
my ($dir, $base, $hdr) = @ARGV;
my @list = glob("$dir/*");
# define args if not provided
$hdr = (defined($hdr) && $hdr eq "true") ? 1 : 0;
# Create output files;
my ($of, $oh, $ot);
open ($of, ">$base.jfl") or
die ("Unable to create $base.jfl for writing.");
binmode($of);
open ($oh, ">$base.hed") or
die ("Unable to create $base.hed for writing.");
open ($ot, ">$base.txt") or
die ("Unable to create $base.txt for writing.");
# Write .hed's first lines:
my $upbase = uc(basename($base));
$upbase =~ tr/\./_/;
print $oh "#ifndef __${upbase}_HED__\n";
print $oh "#define __${upbase}_HED__\n\n";
# Write archive's header if requested
# FIXME! quick hack, check for errors, stat files only once...
if ($hdr) {
print $of pack('C', scalar(@list));
foreach my $file (@list) {
my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
$atime, $mtime, $ctime, $blksize, $blocks) = stat ($file);
print $of pack('S', $size);
}
}
# Process each input file:
my $idx = 0;
my $ofs = 0;
foreach my $file (@list) {
# Open file and get info
my $if;
open ($if, "<$file") or
die ("Unable to open $file for reading");
binmode($if);
my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
$atime, $mtime, $ctime, $blksize, $blocks) = stat ($if);
# Read file contents and append to result
my $contents;
my $cnt = read($if, $contents, $size);
print $of $contents;
close ($if);
# Add info to .hed
my $upfile = uc(basename($file));
$upfile =~ s|^\./||; # remove leading "./"
$upfile =~ tr/\./_/; # replace "." with "_"
print $oh "\t#define ${upbase}_${upfile}_IDX $idx\n";
print $oh "\t#define ${upbase}_${upfile}_OFS $ofs\n";
print $oh "\t#define ${upbase}_${upfile}_BYTE $size\n";
print $oh "\n";
# Add info to .txt
print $ot basename($file)."\n";
$idx++;
$ofs += $size;
}
# Finish .hed file
print $oh "\t#define ${upbase}_JFL_SIZE $ofs\n";
print $oh "\t#define ${upbase}_JFL_MAX $idx\n\n";
print $oh "#endif\n";
# Close file handles
close ($oh);
close ($of);
close ($ot);