#!/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 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]);
  open P, $ARGV[0] or die "Whoops!  That file cannot be read!\n";
  my $first = <P>;
  die "$ARGV[0] seems not to be either an Athena or Artemis project file\n" unless ($first =~ /Athena project file/);
  while (<P>) {
    next unless (/^\@journal/);
    my $cpt = new Safe;
    @ {$cpt->varglob('journal')} = $cpt->reval($_);
    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 journal entry Athena/Artemis projects 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
