#!/usr/bin/perl

# This script makes it easier to handle relative neural connections in f1 genotypes when adding/deleting neurons.
# Usage:
#   perl add_neuro.pl <neuron_number> <f1_genotype>
# If not provided, the <f1_genotype> will be read from stdin.
# <neuron_number> is 1-based.

# TODO: handle bounds (1..N) of <neuron_number> and display a warning when exceeded
# TODO: test thoroughly
# TODO: consider joining with del_neuro.pl or including a common part - 80% of the code is the same.

my $num = shift @ARGV;

my $geno;
if (@ARGV) {
	$geno = "@ARGV";
} else {
	$geno = (<STDIN>);
}

my @out;
my $idx = 0;
my $ratio = 1;
for (split /\[/, $geno) {
	if ($idx == 0) {
		push @out, $_;
		$idx++;
		next;
	}
 	if ($idx == $num) {
		push @out, "NEW]";
		$idx++;
		$ratio *= -1;
	}
	my ($neuro, $rest) = split /\]/;
	my @neuroOut;
	foreach (split /,/, $neuro) {
		if (/([-0-9]+):(.*)/ && ($ratio * ($1 + $idx) >= $ratio * ($num))) {
			push @neuroOut, join (':', ($1 + $ratio, $2));
		} else {
			push @neuroOut, $_;
		}
	}
	push @out, join(',', @neuroOut) . ']' . $rest;
	$idx++;
}

printf "%s\n", join('[', @out);

