#!/usr/bin/perl -w
#Coded by Sha0
#Se lo dedico a HiDaRK que siepre me ganaba en WesNoth ;)
#./cheat.pl  wesnoth i,21

#Globals
use strict;
my $process=$ARGV[0];
my $pids=`pidof $process`; 
my @memaddr;
my $addr;
my $i;
my $find=$ARGV[1];
my $addr_file='/tmp/direcciones.tmp';
my $newstr='';
my $res;
$pids =~ s/ /,/g;
$pids =~ s/\n//g;


if (-e $addr_file) {
	#Buscar la cadena $find solo en las direcciones del fichero 
	#de ocurrecncias	
	#y crear de nuevo el fichero con las nuevas ocurrencias
	#asi hasta que solo quede una (como en los inmortales ;)
	#Cuando quede una se le preguntará por que cadena reemplazarla
	
	@memaddr = `cat $addr_file | awk '{print \$3}'`;
	`rm -rf $addr_file`;
	for ($i=0;$i<=$#memaddr;$i++) {
		$addr=$memaddr[$i];
		$addr =~ s/\n//g;
		$res=`memgrep -p $pids -s -a $addr -l 4 -f $find | grep -v Searching`;
		print $res;
		
		if ($res =~ /found/) {
			open (X,">>$addr_file");
			print X $res;
			close (X);
		}
	}

} else {
	#Crear un fichero de ocurrencias 	

	`memgrep -p $pids -s -a data,bss -f $find | grep -v '=>' > $addr_file `
}

print `cat $addr_file`;

if (`cat $addr_file | wc -l` == 1) {
	print "Enhorabuena, el offset es ".`cat $addr_file`."\n";
	print "lo modificaremos por:";
	$newstr=<STDIN>;
	chomp($newstr);
	$addr=`cat $addr_file | awk '{print \$3}'`;
	$addr=~s/\n//g;
	print `memgrep -p $pids -s -r -a $addr -l 4 -f $find -t $newstr `;
}
