#!/usr/bin/perl

my $IDSPACE = 'GOTAX';
my $maxid = 0;

my %ok_rel_h =
    (
     only_in_taxon=>1,
     never_in_taxon=>1,
    );

my %seen = ();
my @lines = <>;
foreach (@lines) {
    my $line = $_;
    while (true) {
        if ($line =~ /$IDSPACE:(\d+)/) {
            my $id = $1;
            if ($id > $maxid) {
                $maxid = $id;
            }
            $seen{$id}++;
            if ($seen{$id} > 1) {
                die "$id used more than once!";
            }
            $line =~ s/$IDSPACE:\d+//;
        }
        else {
            last;
        }
    }
}
print STDERR "max id = $IDSPACE:$maxid\n";
my $n = 0;
foreach (@lines) {
    chomp;
    my $cmt = '';
    if (/(\s*\!.*)/) {
        $cmt = $1;
        s/\s*\!.*//;
    }
    if (/^relationship:\s*(\S+)\s+(\S+)\s*(.*)/) {
        my ($rel, $v, $rest) = ($1,$2,$3);

        if ($ok_rel_h{$rel}) {
            if ($rest =~ /\{id=.*\}/) {
                # OK
            }
            elsif ($rest =~ /id=/) {
                #die "Human intervention required! I expect the id tag to be the first one listed on the set of trailing qualifiers";
            }
            elsif ($rest =~ /\{(.*)\}/) {
                $rest = sprintf("{id=\"%s\", $1}", getnextid());
                $_ = "relationship: $rel $v $rest";
            }
            elsif ($rest) {
                die;
            }
            else {
                $_ = sprintf("$_ {id=\"%s\"}", getnextid());
            }
        }
    }
    print "$_$cmt\n";
}

print STDERR "New $IDSPACE IDs assigned: $n\n";
exit 0;

sub getnextid {
    $maxid++;
    $n++;;
    return $IDSPACE.sprintf(':%07d', $maxid);

}
