#!/usr/bin/perl -w

use strict;
use Graph::Easy 0.58;
use Graph::Easy::Parser;

my $help_requested = 0;

# echo "[A]" | graph-easy  		# should work
# graph-easy				# need help
$help_requested = 1 if @ARGV == 0 && -t STDIN;

my $OUT = \*STDERR;
my $opt = get_options();

# error?
$help_requested = 1 if !ref($opt);

# no error and --help was specified
$help_requested = 2 if ref($opt) && $opt->{help} ne '';

my $copyright = "Graph::Easy v$Graph::Easy::VERSION  (c) by Tels 2004-2007.  "
	       ."Released under the GPL 2.0 or later.\n\n";

if (ref($opt) && $opt->{version} != 0)
  {
  print $copyright;
  exit 2;
  }

if ($help_requested > 0)
  {
  print STDERR $copyright;
  require Pod::Usage;
  if ($help_requested > 1 && $Pod::Usage::VERSION < 1.35)
    {
    # The way old Pod::Usage executes "perldoc" might fail:
    system('perldoc', $0);
    exit 2;
    }
  Pod::Usage::pod2usage( { -exitval => 2, -verbose => $help_requested } ); 
  }

my $verbose = $opt->{verbose};

print $OUT $copyright if $verbose;

#############################################################################
# Create the parser object

my $parser_class = 'Graph::Easy::Parser';
if ($opt->{from} eq 'graphviz')
  {
  require Graph::Easy::Parser::Graphviz;
  $parser_class = 'Graph::Easy::Parser::Graphviz';
  }
elsif ($opt->{from} =~ /^(vcg|gdl)\z/)
  {
  require Graph::Easy::Parser::VCG;
  $parser_class = 'Graph::Easy::Parser::VCG';
  }

print $OUT "Creating $parser_class object.\n" if $verbose;

my $parser = $parser_class->new( debug => $opt->{debug} );

#############################################################################
# parse the input file

print $OUT "Parsing input in $opt->{from} from $opt->{inputname}.\n" if $verbose;

my $graph = $parser->from_file($opt->{input});

my $error = '';
$error = $parser->error() if !$graph || $parser->error();
$error = $graph->error() if $graph && $graph->error();

die ("Parser error: " . $error) if $error && $parser->fatal_errors() != 0;

#############################################################################
# Generate the statistics if wanted:

if ($opt->{stats})
  {
  print STDERR "\nInput is a ", 
	$graph->is_simple() ? 'simple' : 'multi-edged',
	", ",
	$graph->is_undirected() ? 'undirected' : 'directed',
        " graph with:\n";

  my $nodes = $graph->nodes();
  my $edges = $graph->edges();
  my $groups = $graph->groups();

  print STDERR "    $nodes node" . ($nodes != 1 ? 's' : '') .
		 ", $edges edge"   . ($edges != 1 ? 's' : '') .
		 " and $groups group"   . ($groups != 1 ? 's' : '') . "\n\n";

  for my $g ($graph->groups())
    {
    my $nodes = $g->nodes();
    my $edges = $g->edges();
    my $groups = $g->groups();

    print STDERR "  Group '$g->{name}':\n";
    print STDERR "    $nodes node" . ($nodes != 1 ? 's' : '') .
		 ", $edges edge"   . ($edges != 1 ? 's' : '') .
		 " and $groups group"   . ($groups != 1 ? 's' : '') . "\n\n";
    }
  }

#############################################################################
# Generate the wanted output format and write it to the output:

if (! $opt->{parse})
  {
  my $method = 'as_' . $opt->{as} . '_file';
  if ($verbose)
    {
    if ($opt->{outputname} =~ /\.png\z/)
      {
      print $OUT "Piping output to 'dot -Tpng -o \"$opt->{outputname}\"'.\n";
      }
    else
      {
      print $OUT "Writing output as $opt->{as} to $opt->{outputname}.\n";
      }
    }

  $graph->timeout(abs($opt->{timeout} || 120));
  my $FILE = $opt->{output};
  print $FILE $graph->$method();

  print $OUT "Everything done. Have fun!\n\n" if $verbose;
  }

#############################################################################
# Everything done

#############################################################################
#############################################################################

sub get_options
  {
  # set the defaults
  my $opt = {
    input => undef,
    output => undef,
    as => '',
    from => 'txt',
    help => '',
    as_ascii => '',
    as_boxart => '',
    as_html => '',
    as_svg => '',
    as_graphviz => '',
    as_txt => '',
    as_png => '',
    as_vcg => '',
    as_gdl => '',
    as_graphml => '',
    debug => 0,
    from_txt => '',
    from_graphviz => '',
    verbose => 0,
    version => 0,
    parse => 0,
    stats => 0,
    timeout => 120,
  };
  # map the output format to the method to generate the output:
  my $formats = {
    html => 'html',
    txt => 'ascii',
    svg => 'svg',
    png => 'graphviz',
    dot => 'graphviz',
    vcg => 'vcg',
    gdl => 'gdl',
    graphml => 'graphml',
  };

  # do we have some options?
  if (@ARGV > 0)
    {
    require Getopt::Long;

    my $rc = Getopt::Long::GetOptions (
	"input=s" => \$opt->{input},
	"output=s" => \$opt->{output},
	"as=s" => \$opt->{as},
	"from=s" => \$opt->{from},
	"help|?" => \$opt->{help},
	"version" => \$opt->{version},
	"verbose" => \$opt->{verbose},
	"debug=i" => \$opt->{debug},
	"parse" => \$opt->{parse},
	"as_ascii|ascii" => \$opt->{as_ascii},
	"as_html|html" => \$opt->{as_html},
	"as_svg|svg" => \$opt->{as_svg},
	"as_png|png" => \$opt->{as_png},
	"as_txt|txt" => \$opt->{as_txt},
	"as_vcg|vcg" => \$opt->{as_vcg},
	"as_gdl|gdl" => \$opt->{as_gdl},
	"as_graphml|graphml" => \$opt->{as_graphml},
	"as_graphviz|graphviz|as_dot|dot" => \$opt->{as_graphviz},
	"as_boxart|boxart" => \$opt->{as_boxart},
	"timeout=i" => \$opt->{timeout},
	"stats" => \$opt->{stats},
	"from_txt" => \$opt->{from_txt},
	"from_graphviz" => \$opt->{from_graphviz},
	);
    return unless $rc;
    }

  # allow "as=dot" for easier usage:
  $opt->{as} = 'graphviz' if $opt->{as} eq 'dot';

  # if there areguments left, they are input and possible output
  $opt->{input} = shift @ARGV if @ARGV;
  $opt->{output} = shift @ARGV if @ARGV;

  if (!defined $opt->{input})
    {
    $opt->{input} = \*STDIN;
    $opt->{inputname} = 'STDIN';
    }
  else 
   {
   $opt->{inputname} = $opt->{input};
   }
 
  # This code gets confused if the user specified multiple options. Not much
  # can be done about that except whack the user with something heavy:
  for my $format (qw/ascii boxart html svg txt graphviz png vcg gdl graphml/)
    {
    warn ("Warning: Output format '$format' overrides specified '$opt->{as}'")
      if $opt->{"as_$format"} && $opt->{as};
    $opt->{as} = $format if $opt->{"as_$format"};
    delete $opt->{"as_$format"};
    }

  if ($opt->{as} eq 'png')
    {
    $opt->{output} = $opt->{input} unless defined $opt->{output};
    # per default output it to graph.png
    $opt->{output} = 'graph.txt' if ref($opt->{input});
    $opt->{output} =~ s/\.(txt|dot|vcg|gdl|graphml|png)\z//;
    $opt->{output} .= '.' . $opt->{as};			# example.txt => example.png
    }
  if (!defined $opt->{output})
    {
    $opt->{outputname} = 'STDOUT';
    $opt->{output} = \*STDOUT;
    # default to ASCII if nothing is known
    $opt->{as} = 'ascii' if $opt->{as} eq '';
    }
  else
    {
    my $file = $opt->{output};
    $opt->{outputname} = $opt->{output};
    if ($opt->{as} eq '')
      {
      $opt->{as} = 'ascii';		# default
      $opt->{as} = $formats->{$1} if $file =~ /\.(html|svg|txt|dot|png|vcg|gdl|graphml)\z/;
      }
    $opt->{output} = undef;
    if ($opt->{as} ne 'png')
      {
      # do not clobber the output file if we cannot read the input
      return unless ref $opt->{input} || -R $opt->{input};

      open $opt->{output}, ">$file" or die ("Cannot write to $file: $!");
      }
    else
      {
      # open a pipe to dot
      my $file_save = $file;
      $file_save =~ s/["'\|;]//g;	# remove potentially unsafe characters
      open $opt->{output}, "|dot -Tpng -o \"$file_save\"" or die ("Cannot open pipe to dot: $!");
      }
    }
    
  if ($opt->{as} ne 'png')
    {
    binmode ($opt->{output}, ':utf8') or die ("Cannot do binmode(output,':utf8')");
    }
  else
    {
    $opt->{as} = 'graphviz';
    }

  for my $format (qw/txt graphviz dot vcg gdl/)
    {
    $opt->{from} = $format if $opt->{"from_$format"};
    delete $opt->{"from_$format"};
    }
  $opt->{from} = 'graphviz' if $opt->{from} eq 'dot';

  $opt;
  }

__END__

=pod

=head1 NAME

graph-easy - render/convert graphs in/from various formats

=head1 SYNOPSIS

Convert between graph formats and layout/render graphs:

	graph-easy [options] [inputfile [outputfile]]

	echo "[ Bonn ] - car -> [ Berlin ]" | graph-easy
	graph-easy --input=graph.dot --as_ascii
	graph-easy --html --output=graph.html graph.txt
	graph-easy graph.txt graph.svg
	graph-easy graph.txt --as_dot | dot -Tpng -o graph.png
	graph-easy graph.txt --as_png
	graph-easy graph.vcg --as_dot
	graph-easy graph.dot --gdl
	graph-easy graph.dot --graphml

=head1 ARGUMENTS

=over 10

=item --help

Print the full documentation, not just this short overview.

=item --input

Specify the input file name. Example:

    graph-easy --input=input.txt

The format will be auto-detected, override it with L<--from>.

=item --output

Specify the output file name. Example:

    graph-easy --output=output.txt input.txt

=item --as

Specify the output format. Example:

    graph-easy --as=ascii input.txt

Valid formats are:

    ascii	ASCII art rendering
    boxart	Unicode Boxart rendering
    html	HTML
    svg		Scalable Vector Graphics
    graphviz    the DOT language
    dot		n alias for "graphviz"
    txt		Graph::Easy text
    vcg		VCG (Visualizing Compiler Graphs - a subset of GDL) text
    gdl		GDL (Graph Description Language) text
    graphml	GraphML
    png		PNG file rendered via "dot"

The default format will be determined by the output filename extension,
and is C<ascii>, if the output filename was not set.

Or use B<ONE> argument of the form C<--as_ascii> or C<--ascii>.

=item --from

Specify the input format. Valid formats are:

    graphviz	the DOT language
    txt		Graph::Easy text
    vcg		VCG text
    gdl		GDL (Graph Description Language) text

If not specified, the input format is auto-detected.

You can also use B<ONE> argument of the form C<--from_dot>, etc.

=item --parse

Input will only be parsed, without any output generation.
Usefull in combination with C<--debug=1> or C<--stats>. Example:

    graph-easy input.txt --parse --debug=1

=item --stats

Write various statistics about the input graph to STDERR. Best used in
combination with C<--parse>:

    graph-easy input.txt --parse --stats

=item --timeout

Set the timeout B<in seconds> for the Graph::Easy layouter that generates
ASCII, HTML, SVG or boxart output. If the layout does not
finish in this time, it will be aborted. Example:

    graph-easy input.txt --timeout=500

Conversion to DOT, VCG/GDL, GraphML or plain text ignores the timeout.

=item --verbose

Write info regarding the conversion process to STDERR.

=back

=head1 DESCRIPTION

C<graph-easy> reads a description of a graph (a connected network of
nodes and edges, not a pie chart :-) and then convert this to the desired
output format.

By default, the input will be read from STDIN, and the output will go to
STDOUT. The input is expected to be encoded in UTF-8, the output will
also be UTF-8.

It understands the following formats as input:

    Graph::Easy	 http://bloodgate.com/perl/graph/manual/
    DOT		 http://www.graphviz.org/
    VCG		 http://rw4.cs.uni-sb.de/~sander/html/gsvcg1.html
    GDL		 http://www.aisee.com/

The formats are automatically detected, regardless of the input file name,
but you can also explicitely declare your input to be in one specific
format.

The output can either be a dump of the graph in one of the following formats:

    Graph::Easy	 http://bloodgate.com/perl/graph/manual/
    DOT		 http://www.graphviz.org/
    VCG		 http://rw4.cs.uni-sb.de/~sander/html/gsvcg1.html
    GDL		 http://www.aisee.com/
    GraphML	 http://graphml.graphdrawing.org/

In addition, C<Graph::Easy>> can also create layouts of graphs in
one of the following output formats:

    HTML   SVG	 ASCII	 BOXART

Note that for SVG output, you need to install the module
L<Graph::Easy::As_svg> first.

As a shortcut, you can also specify the output format as 'png', this will
cause C<graph-easy> to pipe the input in graphviz format to the C<dot> program
to create a PNG file in one step. The following two examples are equivalent:

    graph-easy graph.txt --as_dot | dot -Tpng -o graph.png
    graph-easy graph.txt --as_png

X<svg>
X<html>
X<ascii>
X<boxart>
X<png>
X<dot>
X<graphviz>
X<vcg>
X<gdl>
X<graph description language>
X<unicode>

=head1 OTHER ARGUMENTS

C<graph-easy> supports a few more arguments in addition to the ones from above:

=over 10

=item --version

Write version info and exit.

=item --debug=N

Write debugging info to STDERR. Warning, this can create huge amounts
of hard-to-understand output! Example:

	graph-easy input.txt --output=test.html --debug=1

=item --png, --dot, --vcg, --gdl, --txt, --ascii, --boxart, --html, --svg

Given exactly one of these options, produces the desired output format.

=back

=head1 EXAMPLES

=head2 ASCII output

	echo "[ Bonn ] -- car --> [ Berlin ], [ Ulm ]" | graph-easy

	+--------+  car   +-----+
	|  Bonn  | -----> | Ulm |
	+--------+        +-----+
	  |
	  | car
	  v
	+--------+
	| Berlin |
	+--------+

=head2 Graphviz example output

	echo "[ Bonn ] -- car --> [ Berlin ], [ Ulm ]" | graph-easy --dot
	digraph GRAPH_0 {
	
	  edge [ arrowhead=open ];
	  graph [ rankdir=LR ];
	  node [
	    fontsize=11,
	    fillcolor=white,
	    style=filled,
	    shape=box ];
	
	  Bonn -> Ulm [ label=car ]
	  Bonn -> Berlin [ label=car ]
	
	}

=head2 VCG example output

	echo "[ Bonn ] -- car --> [ Berlin ], [ Ulm ]" | graph-easy --vcg
	graph: {
	  title: "Untitled graph"
	
	  node: { title: "Berlin" }
	  node: { title: "Bonn" }
	  node: { title: "Ulm" }
	
	  edge:  { label: "car" sourcename: "Bonn" targetname: "Ulm" }
	  edge:  { label: "car" sourcename: "Bonn" targetname: "Berlin" }
	
	}

=head2 GDL example output

GDL (Graph Description Language) is a superset of VCG, and thus the output will
look almost the same as VCG:

	echo "[ Bonn ] -- car --> [ Berlin ], [ Ulm ]" | graph-easy --gdl
	graph: {
	  title: "Untitled graph"
	
	  node: { title: "Berlin" }
	  node: { title: "Bonn" }
	  node: { title: "Ulm" }
	
	  edge:  { label: "car" source: "Bonn" target: "Ulm" }
	  edge:  { label: "car" source: "Bonn" target: "Berlin" }

	}	

=head2 GraphML example output

GraphML is XML:

	echo "[ Bonn ] -- car --> [ Berlin ], [ Ulm ]" | graph-easy --graphml
	<?xml version="1.0" encoding="UTF-8"?>
	<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
	    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
	     http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
	
	  <!-- Created by Graph::Easy v0.58 at Mon Aug 20 00:01:25 2007 -->
	
	  <key id="d0" for="edge" attr.name="label" attr.type="string"/>
	
	  <graph id="G" edgedefault="directed">
	    <node id="Berlin"/>
	    <node id="Bonn"/>
	    <node id="Ulm"/>
	    <edge source="Bonn" target="Berlin"/>
	      <data key="d0">car</data>
	    <edge source="Bonn" target="Ulm"/>
	      <data key="d0">car</data>
	  </graph>
	<graphml>

=head1 CAVEATS

Please note that it is impossible to convert 100% from one format to another
format since every graph language out there has features that are unique to
only this language.

In addition, the conversion process always converts the input first into an
L<Graph::Easy> graph, and then to the desired output format. 

This means that only features and attributes that are actually valid in
Graph::Easy are supported yet. Work in making Graph::Easy an universal
format supporting as much as possible is still in progress.

Attributes that are not yet supported natively by Graph::Easy are converted
to custom attributes with a prefixed C<x-format->, f.i. C<x-dot->. Upon output
to the same format, these are converted back, but conversion to a different
format will lose these attributes.

For a list of what problems still remain, please see the TODO
file in the C<Graph::Easy> distribution on CPAN:

L<http://search.cpan.org/~tels/Graph-Easy/>

If you notice anything wrong, or miss attributes, please file a bug report on

L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Graph-Easy>

so we can fix it and include the missing things into Graph::Easy!

X<bugreport>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the terms of the GPL.

See the LICENSE file of Graph::Easy for a copy of the GPL.

This product includes color specifications and designs developed by Cynthia
Brewer (http://colorbrewer.org/). See the LICENSE file for the full license
text that applies to these color schemes.
X<gpl>
X<apache-style>
X<cynthia>
X<brewer>
X<colorscheme>
X<license>

=head1 AUTHOR

Copyright (C) 2004 - 2007 by Tels L<http://bloodgate.com>

=head1 SEE ALSO

More information can be found in the online manual of Graph::Easy:

L<http://bloodgate.com/perl/graph/manual/>

See also: L<Graph::Easy>, L<Graph::Easy::Manual>

=cut
