#!/usr/bin/perl
# jtag-state-machine.pl: create JTAG state transition graph using GraphViz
# Copyright (C) 2009 by Zachary T Welch <zw@superlucidity.net>
# Released under the GNU GPL v2 (or later).

use strict;
use warnings;
use GraphViz;
use JTAG;

my $g = new GraphViz(concentrate => 1, ratio => 'compress');

# place nodes in proper order to allow best placement
my @node_ranks = ( 7, 5, 4, 6,  2, 8, 3, 2,  7, 5, 4, 6,  2, 8, 3, 1 );
my @ranked_names = sort {
		$node_ranks[get_state_id($a)] <=> $node_ranks[get_state_id($b)]
	} jtag_state_names();


for my $name ( @ranked_names )
{
	my $id = get_state_id($name);
	$g->add_node($id, label => $name, rank => $node_ranks[$id]);
}

# place edges
my @edge_ranks = ( 1, 0, 1, 1,  0, 1, 0, 0,  1, 0, 1, 1,  1, 1, 0, 0 );
for my $start_name ( @ranked_names )
{
	my $start_id = get_state_id($start_name);
	for my $tms ( 0 .. 1 )
	{
		my $final_name = get_next_state($start_name, $tms);
		my $final_id = get_state_id($final_name);
		print "$start_name => $tms => $final_name\n";
		$g->add_edge($start_id => $final_id,
				label => "   $tms   ",
				weight => 36 - 12 * ($edge_ranks[$final_id] == $tms),
#				weight => 10 + 5 * ($edge_ranks[$final_id] != $tms),
#				constraint => ($edge_ranks[$final_id] == $tms)
				);
	}
}

# write the graph to the output file
my ( $filename ) = $0 =~ /([^\.]+)\.pl$/;
open FILE, ">$filename.svg" or die "unable to open $filename: $!\n";
print FILE $g->as_svg;
close FILE;

