#!/usr/local/ActivePerl-5.10/bin/perl-dynamic -s
require 5.000;

## this script reads in the CCO OBO file and prints a list of CCO ids and terms

##	output file
open (CCO_TERMS, ">CCO_terms.txt");

##	input file -- read in OBO terms
&parse_obo(%nodes);

##	

foreach $query_node (sort keys %nodes) {
	$line = $nodes{$query_node}->{"name"};
	print CCO_TERMS "$query_node\t$line\n";
	}

close (CCO_TERMS) || die "CCO_TERMS file was not closed\n";
exit (0);

############
sub parse_obo()
{
    %nodes = ();

    open (OBO, "Cell_Cycle_Ontology.obo") ||print "ontology open error";
    while (<OBO>) {

    if (/\[Term\]/) {
    #new term
	&get_node_info($node_id, $node_name, @parent_nodes);
	$term = {
		"name" => $node_name,
		"parents" => [ @parent_nodes ],
		"children" => [ @child_nodes ],
		};

	$nodes{$node_id} = $term;
	} #end term test
     } #end read loop

     close (OBO);

    #associate with child nodes as parents
    foreach $node_id (keys %nodes) {
	@parent_nodes = @ { $nodes{$node_id}->{"parents"} };

	#register as child with each parent node
	foreach $parent (@parent_nodes) {
		$parent_node = $parent->{"id"};
		$parent_type = $parent->{"type"};
		$child =  {
		      "id" => $node_id,
		      "type" => $parent_type,
		      };
		@child_nodes = @ { $nodes{$parent_node}->{"children"} };
		push @child_nodes, $child;
		$nodes{$parent_node}->{"children"} = [ @child_nodes ];
	}
    }
}

############
sub get_node_info($node_id, $node_name, @parent_nodes)
{
#clear info
    $node_id = "";
    $node_name = "";
    @parent_nodes = ();

    while (<OBO>) {
    chomp;
    $term_line = $_;

    #node_id
	if ($term_line =~ /^id: ([A-Z]+:.?\d+)/) {
	    $node_id = $1;
	    }

    #node name
	if ($term_line =~ /^name: (.*)/) {
	    $node_name = $1;
	    }
    #is_a
	if ($term_line =~ /^is_a: (\w+:\d+)/) {
	    $parent_id = $1;
	    $parent_type = "is_a";
	    $parent = {
		      "id" => $parent_id,
		      "type" => $parent_type,
		      };
	    push @parent_nodes, $parent;
	    }
	    
    #other relationship
	if ($term_line =~ /^relationship: (\S+) ([A-Z]+:\d+)/) {
	    $parent_id = $2;
	    $parent_type = $1;
	    $parent = {
		      "id" => $parent_id,
		      "type" => $parent_type,
		      };
	    push @parent_nodes, $parent;
	    }
	    
    #end of Term
	if ($term_line eq "") {
	    return();
	    }
    } #end read node
} #end get_node_info routine

__END__