#Requires tes3cmd
#Tes3cmd modify --program PGFOMW.pl > PGFOMW.log


# Put all the names of the plugins that you want to patch here
my @plugins = 
(
    "Yet Another Guard Diversity - Regular.ESP",
	#"my_mod.esp"
);

# If no plugins given, terminate patcher
if (!@plugins){die;}

my $success = 0;
my $failed = 0;
my $plugin_names = "";


print "Patching the following plugins :\n";for (@plugins){ print("=>","$_","\n"); $plugin_names = $plugin_names . ' -- ' . $_;}print "\n\n\n";


# make output file and give it a header
my $output = open_for_output('PGFOMW-Patched.esp');
print $output make_header
({
	author => 'TES3CMD',
	description => 'Protective Guards for OpenMW patch for ' . $plugin_names . ' -- Please put this plugin at the bottom of your load order. '
});


# Iterate through all given plugins
for my $plugin (@plugins) 
{
	
	# Open a plugin for inspection
    my $input = open_for_input($plugin);
	
	# Iterate through the records in the plugin
    while (my $record = TES3::Record->new_from_input($input)) 
	{
		# Only interested in NPCs
        next unless $record->rectype eq 'NPC_';
		
		# Get the ID of the NPC
        my $id = $record->decode->id;
		
		# Get the class of the NPC
		my $class_name = $record->decode->get('CNAM','class');
		
		# Only interested in 'Guard' class
		next unless $class_name eq 'Guard';
		
		# Prints out the ID of the NPC and the plugin it was from
		print "Found ID '$id' of class guard from plugin '$plugin'\n";
		print "Patching '$id'..\n";
		
		# Check if a script is already attached to the NPC
        my $script = $record->get('SCRI','script');
		
		# If a script is already attached to the NPC, prints a message
		print "Patch failed for '$id'! \n\n" if defined($script);
		$failed++ if defined($script);
		
		# Skips NPCs with scripts already attached, we don't want to overwrite existing scripts
        next if defined $script;
		
		# Appends the 'Protective Guards' script to the NPC, and prints a message
        $record->append(NPC_::SCRI->new({script=>'eqnx_help_pc'}));
		print "Patch successful for '$id'! \n\n";
		$success++;
        $record->encode->write_rec($output);
    }
	

}

	# Prints a message showing total records found ( only Guards ), the number of successful and failed patch
	my $totalrec = $success + $failed;
	print "Total number of records : $totalrec \n";
	print "Number of successful patch : $success \n";
	print "Number of failed patch : $failed \n\n";
	
	exit;