#!/usr/bin/perl
#
# This is a little script to snarf the journal entry from an Athena
# or Artemis project file and write it to STDOUT
# -------------------------------------------------------------------

use strict;
use Safe;
use Text::Wrap;
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
use Compress::Zlib;
use Getopt::Long;

my $help;
GetOptions('h'    => \$help,
	   'help' => \$help);

if ($help or not $ARGV[0]) {
  require Pod::Text;
  $^W=0;
  if ($Pod::Text::VERSION < 2.0) {
    Pod::Text::pod2text($0, *STDOUT);
  } elsif ($Pod::Text::VERSION >= 2.0) {
    my $parser = Pod::Text->new;
    open STDIN, $0;
    $parser->parse_from_filehandle;
  };
  exit;
};

Archive::Zip::setErrorHandler( \&is_zip_error_handler );
my $zip = Archive::Zip->new();
if ($zip->read( $ARGV[0] ) == AZ_OK) {
  $zip->extractMemberWithoutPaths("descriptions/journal.artemis", "...horae_journal");
  die "Hmmm... that was a zip file but not an Artemis project file...\n" unless (-e "...horae_journal");
  if (-s "...horae_journal" < 3) {
    print "  << empty journal >> \n";
    exit;
  };
  open P, "...horae_journal";
  print while (<P>);
  close P;
  unlink  "...horae_journal";
  exit;
} else {
  die "Whoops!  That file doesn't seem to exist!\n" unless (-e $ARGV[0]);
  my $athena_fh = gzopen($ARGV[0], "rb") or die "could not open $ARGV[0] as an Athena or Artemis project file\n";
  my $nline = 0;
  my $line = q{};
  my $cpt = new Safe;
  while ($athena_fh->gzreadline($line) > 0) {
    ++$nline;
    next unless ($line =~ m{^\@journal});
    my $cpt = new Safe;
    @ {$cpt->varglob('journal')} = $cpt->reval($line);
    my @j = ();
    push @j, wrap("","",$_) foreach (@ {$cpt->varglob('journal')});
    my $journal = join($/, @j);
    if ($journal =~ /^[\s\n\r]*$/) {
      print "  << empty journal >> \n";
      exit;
    };
    print $journal, $/;
    exit;
  };
};

sub is_zip_error_handler { 1; };

1;

__END__

=head1 NAME

rdaj - echo the Athena or Artemis project journal entry to the screen

=head1 SYNOPSIS

   rdaj [-h] project_file

=head1 DESCRIPTION

This little program grabs the journal entry from your Athena or
Artemis project files and echos it to the screen.

=head1 AUTHOR

  Bruce Ravel, bravel@anl.gov
  http://cars9.uchicago.edu/~ravel

=cut
