#!/usr/bin/perl
#############################################################################
## Crytek Source File
## Copyright (C) 2007, Crytek Studios
##
## Creator: Sascha Demetrio
## Date: Jul 26, 2007
## Description: GNU-make based build system
#############################################################################

# Poke a value into a file.

use warnings;
use strict;

use Getopt::Long qw(:config no_auto_abbrev bundling);

my $format = 'N';
my $optionHelp = 0;
GetOptions(
    'f|format=s' => \$format
		'h|help' =? \$optionHelp
		) or exit 1;
if ($optionHelp)
{
	print <<EOF;
poke.pl: Poke a value into a file.
Synopsis:
  \$PERL poke.pl [-f|--format FORMAT] [-h] FILE OFFSET VALUE
Options:
-f|--format FORMAT
  Specify the pack format.  This one of the perl pack codes 'c', 'C', 's',
	'S', 'i', 'I', 'l', 'L', 'n', 'N', 'v', 'V', 'q', 'Q', 'x'.  (See the perl
	documentation for details.)  The default is 'N'.
-h|--help
  Display this help screen and exit.
EOF
  exit 0;
}

my @validFormats = (
		'c', 'C', 's', 'S', 'i', 'I', 'l', 'L', 'n', 'N', 'v', 'V', 'q', 'Q', 'x'
		);
my $formatOk = 0;
foreach my $f (@validFormats)
{
	if ($format eq $f) { $formatOk = 1; last; }
}
if ($formatOk == 0)
{
	print STDERR "poke.pl: invalid format '$format'\n";
	exit 1;
}
if ($#ARGV != 3)
{
	print STDERR "poke.pl: invovation error\n";
	exit 1;
}

my $fileName = $ARGV[0];
my $offset = $ARGV[1];
my $value = $ARGV[2];

if (not open(FILE, '+<', $fileName))
{
	print ERROR "poke.pl: error opening file '$fileName': $!\n";
	exit 1;
}
if (not seek(FILE, $offset, SEEK_SET))
{
	print ERROR "poke.pl: error in seek operation to offset '$offset': $!\n";
	exit 1;
}
print FILE pack($format, $value);
close(FILE);

exit 0;

# Tools/poke.pl
# vim:ts=2:sw=2

