#!/usr/bin/perl

# replacement for dat2ver (which is pretty well DOS-only)

=pod

=head1 NAME

zrename - rename z-code story files according to their z-machine version

=head1 SYNOPSIS

zrename filename [filename ...]

=head1 DESCRIPTION

B<zrename> renames Infocom and other Z-Code story files so that their
filename extension matches the Z-Machine version in the file header.

Most story files are versions 3 or 5 (renamed to .z3 or .z5). Valid
version numbers are 1 through 8, with 1, 2, 4, and 7 being rare and/or
obsolete.

Correctly-named files will be left alone. Files that are renamed do not
have their contents changed, only the name.

Be careful: no checking is done to make sure the input files are actually
z-code files, other than the value of the first byte of the file (which
must be in the range of 1 to 8).

=head1 AUTHOR

B. Watson (yalhcru@gmail.com)

=cut

$version = 0.1;

use warnings;

if(!@ARGV || $ARGV[0] =~ /^-?-h(?:elp)/) {
	print "Usage: $0 filenames\n";
	exit 0;
}

if($ARGV[0] =~ /^-?-v(?:ersion)/) {
	print $version;
	exit 0;
}

if($ARGV[0] =~ /^--man/) {
	system("pod2man -c 'Z-Code Renamer' -r v$version $0");
	exit 0;
}

for(@ARGV) {
	my $byte;
	open my $fh, "<$_";

	if(!read($fh, $byte, 1)) {
		warn "$_: $!\n";
		next;
	}

	$byte = ord($byte);

	if($byte < 1 || $byte > 8) {
		warn "$_: invalid version in header, skipping\n";
		next;
	}

	my $newname = $_;
	$newname =~ s/(?:\.[^.]*$|$)/.z$byte/;

	if($newname ne $_) {
		print "$_ => $newname\n";
		rename($_, $newname);
	}
}
