#!/usr/bin/perl -w
use List::Util qw(shuffle);
use strict;

my $excl="NONE";
if ($ARGV[2]) { $excl=$ARGV[2] }
my $max=0;
if ($ARGV[3]) { $max=$ARGV[3] }

open(I,"<$ARGV[0]");
my @sp0=();
while (<I>) {
	chomp;
	my @tmp = split /\t/;
	if (($tmp[2]=~/\.$ARGV[1]\./)&&(!($tmp[2]=~/\.$excl\./))) {
		push @sp0, "CHR$tmp[1]";
	}
}
close I;

my @sp=@sp0;
if ($max>0) { @sp = shuffle @sp0; @sp=@sp[0..($max-1)] }

print "MATCH\n";
print "(oga:OG),(ogb:OG),\n";
my @abs=();
my @orta=();
my @ortb=();
for my $x (0..$#sp) {
	my $n=$x+1;
 print "(f".$n."a)-[:location]-(chr$n:$sp[$x])-[:location]-(f".$n."b),";
 push @orta, "(f".$n."a)";
 push @ortb, "(f".$n."b)"; 
 push @abs, "abs(f".$n."a.CoordinateStart-f".$n."b.CoordinateStart)";
 print "\n";
}

print "(chr1)-[:orthologous]-(chr1alg:ALG),\n";


for my $x (@orta) {
 print "$x-[:orthologous]-(oga),\n";
}
for my $x (0..$#ortb) {
 print "$ortb[$x]-[:orthologous]-(ogb)";
 if ($x<$#ortb) { print "," }
 print "\n";
}

print "RETURN\nchr1.name,\nf1a.name,\nf1b.name,\nchr1alg.name,\n";
print "(".join("+",@abs).")/".($#sp+1)." AS AVERAGE\n";
