#!/usr/bin/perl
# Author: Markus Schordan, 2003.
# $Id: cpp2pdf,v 1.1 2003/03/24 20:12:54 markus Exp $

############################################################################
# Reads a C++ file and generates a pdf file, showing the corresponding
# abstract syntax tree (=subset of sage3).
############################################################################

use Getopt::Long;

$rosetool="pdfGenerator";

sub printhelp {
  print("\nSYNOPSIS:\n cpp2pdf <INPUTFILE> [<OUTPUTFILE>]\n\n");
  print("OPTIONS:\n");
  print("-h --help              : Print this help message.\n");
  print("\nEXAMPLES:\n");
  print("cpp2pdf test1.C mytest1.C.pdf     : the new file mytest1.C.pdf is generated\n");
  print("cpp2pdf test1.C                   : the new file test1.C.pdf is generated\n");
  print("cpp2pdf test1.C test1.C.pdf       : the new file test1.C.pdf is generated\n");
  print("\n");
}

sub command {
  $command=$_[0];
  $string=$_[1];
  open(RECDIR, "$command $string|");
  @recDir=<RECDIR>;
  close(RECDIR);
  $string=@recDir[0];
  $string=~ s/\n//;
  return $string;
}

GetOptions("outputfile=s" => \$outfile, "help!" => \$printhelp_opt);

if($printhelp_opt) {
  printhelp();
  exit 0;
}

$E_BADARGS=65;
if(@ARGV < 1) {
  printhelp();
  exit $E_BADARGS;
}

$infile=@ARGV[0];

$exitstatus=system("$rosetool $infile");
if($exitstatus==0) {
  if(@ARGV==1) {
    $outfile="@ARGV[1].pdf";
    # outfile is generated by default behaviour
  } else {
    $infilebasename=command("basename",$infile);
    $genfile="$infilebasename.pdf";
    $outfile=@ARGV[1];
    # only rename file if it's not already generated by default output
    if(!($genfile eq $outfile)) {
      system("mv $genfile $outfile");
    }
  }
}

