#!/usr/bin/perl -w
use strict;
use JSON;

my $no_ctxt = 0;
while ($ARGV[0] & $ARGV[0] =~ /^\-(.+)/) {
    my $opt = shift @ARGV;
    if ($opt eq '-n' || $opt eq '--no-json-ld-context') {
        $no_ctxt = 1;
    }
}

my @curs = ();
while(<>) {
    next if /^Abbrev/;
    chomp;
    my ($id,$db,$n,$c) = split(/\t/,$_);
    if (!$n) {
        warn "No label: $_";
        $n = $id;
        $n =~ s/^(\w+)://;
    }
    if (!$id) {
        warn "No ID: $_";
        next;
    }
    my $sameAs;
    my %ch = (
        id => $id,
        type => "foaf:Agent",  # TODO: use foaf:Group if mtg
        member => {
            label => $db,
            type => "foaf:Organization",
        },
        label => $n,
    );
    if ($c && $c =~ /(http\S+)/) {
        $ch{sameAs} = $1;
        $c =~ s/http:\S+//;
    }
    if ($c) {
        $ch{comment} = $c;
    }
    push(@curs,\%ch);
};

my $doc = {
    '@' => {
        id => '@id',
        type => {
            '@id' => "rdf:type", 
            '@type' => '@id',
        },
        member => 'foaf:member',
        label => "rdfs:label",

        foaf => "http://xmlns.com/foaf/0.1/",
        obo => "http://purl.obolibrary.org/obo/",
        GO => "http://purl.obolibrary.org/obo/GO_",
        GOC => "http://purl.obolibrary.org/obo/go/curators/",
        vivoweb => "http://vivoweb.org/ontology/core#",   # E.g. Consortium, Institute
    },
    curators => \@curs
};

if ($no_ctxt) {
    delete $doc->{'@'};
}

my $json = new JSON;
print $json->pretty->encode( $doc ); 
