#!/usr/bin/env perl
#
# cat refseq | refseq.pl
#
# DEFINITION
# FEATURES
#   /db_xref
#   /note
#   /EC_number
#

use strict;
use warnings;

my $locus = "";
my $def = "";
my $head = "";
while (my $l = <STDIN>) {
  if ($l =~ /^LOCUS +(\S+)/) {
    $locus = $1;
  }
  elsif ($l =~ /^(DEFINITION) +/) {
    $head = $1;
    $def = $l;
  }
  elsif ($l =~ /^(\S+)/) {
    $head = $1;
    if ($def) {
      note($def);
      $def = "";
    }
  }
  elsif ($l =~ /^   PUBMED +(\S+)/) {
    pmid($1);
  }
  elsif ($l =~ /^ / && $head eq 'DEFINITION') {
    $def .= $l;
  }
  elsif ($l =~ /^ / && $head eq 'FEATURES') {
    my $s = substr($l,21);
    if ($s =~ /^\/db_xref=\"(\S+)\"/) {
      db_xref($1);
    }
    elsif ($s =~ /^\/note=\"(\S+)/) {
      if ($s !~ /\"$/) {
        while (my $t = <STDIN>) {
          $s .= $t;
          last if $s =~ /\"$/;
        }
      }
      note($s);
    }
    elsif ($s =~ /^\/EC_number=\"(\S+)\"/) {
      note($s);
    }
  }
  if ($l =~ /^\/\//) {
    $locus = "";
    $def = "";
    $head = "";
  }
}

sub pmid {
  my $pmid = shift;
  print "rs:$locus\tpmid:$pmid\n";
}

sub db_xref {
  my $w = shift;
  $w =~ /([^:]+):(\S+)/;
  my $db = $1;
  my $id = $2;
  if ($db eq 'taxon') {
    print "rs:$locus\ttax:$id\n";
  }
  elsif ($db eq 'MIM') {
    print "rs:$locus\tomim:$id\n";
  }
  elsif ($db eq 'GI') {
    print "rs:$locus\tncbi-gi:$id\n";
  }
  elsif ($db eq 'GeneID') {
    print "rs:$locus\tncbi-geneid:$id\n";
  }
  #elsif ($db eq 'CDD') {
  #  print "rs:$locus\tncbi-cdd:$id\n";
  #}
  #elsif ($db eq 'InterPro') {
  #  print "rs:$locus\tinterpro:$id\n";
  #}
  #elsif ($db eq 'GO') {
  #  print "rs:$locus\tgo:$id\n";
  #}
  #elsif ($db eq 'PFAM') {
  #  print "rs:$locus\tpf:$id\n";
  #}
  #elsif ($db =~ /^UniProt/) {
  #  print "rs:$locus\tup:$id\n";
  #}

}

sub note {
  my $s = shift;
  my @n = ();
  $s =~ s/\s+/ /gm;
  @n = ($s =~ /\d+\.\d+\.\d+\.\d+/g);
  foreach my $ec (@n) {
    print "rs:$locus\tec:$ec\n";
  }
}
