#!/usr/bin/perl

# Printer defines (for a HP DJ+)
#
$RESET="\033E\e&k2G";
$HEADER="\033(0N\033(s0u0p10h12v0s0b3t2Q";
$TEXT="\033(0N\033(s0u0p12h12v0s0b6t2Q";
# this is for 12 cpi (12*8-2)=94 (for 10 cpi use 78)
$LINELENGTH=94;
$FIRSTQUOTEON="\033(s7B";
$FIRSTQUOTEOFF="\033(s0B";
$QUOTEON="\033(s1S";
$QUOTEOFF="\033(s0S";
$ORIGINON=$HEADER;
$ORIGINOFF=$TEXT;

# regex for quote and origin
#
$QUOTERX='^(\s*([A-Za-z]*)>+)+';
$FIRSTRX='^[^>]*>[^>]*$';
$ORIGRX='^( \* Origin:|---)';

# data defs
#
$mode = 0;

$number="";
$area="";
$from="";
$fromaddr="";
$to="";
$toaddr="";
$subject="";
$date="";
$recv="";

$first=1;

# line output sub
#
sub printLine {
    my ($line)=@_;
    if ($line =~ /$QUOTERX/) {
	if ($& =~ /$FIRSTRX/) {
	    print $FIRSTQUOTEON.$line.$FIRSTQUOTEOFF;
	} else {
	    print $QUOTEON.$line.$QUOTEOFF;
	}
    } elsif ($line =~ /$ORIGRX/) {
	print $ORIGINON.$line.$ORIGINOFF;
    } else {
	print $line;
    }
}

 main: while (<STDIN>) {
     if (/^###MESSAGE_START###/) {
	 if ($first) {
	     $first=0;
	 } else {
	     print "\f";
	 }
	 $mode=1; next main;
     }
     if (/^##HEADER##$/ && $mode) {
	 $mode=2; next main;
     }
     if (/^##TEXT##$/ && $mode) {
	 print $RESET.$HEADER;
	 print <<EOF;
------------------------------------------------------------------------------
Message Number $number from area $area
------------------------------------------------------------------------------
EOF
	 if ($fromaddr eq "") {
	     print "From: $from\n";
	 } else {
	     print "From: $from ($fromaddr)\n";
	 }
	 if ($toaddr eq "") {
	     print "From: $to\n";
	 } else {
	     print "From: $to ($toaddr)\n";
	 }
	 print <<EOF;
Subj: $subject
Send: $date
EOF
	 if ($recv ne "") {
	     print "Recv: $recv\n";
	 }
	 print <<EOF;
------------------------------------------------------------------------------
EOF
	 print $TEXT;
	 $mode=3;
	 next main;
     }
     if (/^##KLUDGES##$/ && $mode) {
	 $mode=4; next main;
     }
     if (/^###MESSAGE_END###$/ && $mode) {
	 $mode=0; next main;
     }
     if ($mode==2) {
	 if (/^#Number: (.*)/) {
	     $number=$1+1;
	 }
	 if (/^#Area: (.*)/) {
	     $area=$1;
	 }
	 if (/^#From: (.*)/) {
	     $from=$1;
	 }
	 if (/^#\@From: (.*)/) {
	     $fromaddr=$1;
	     if ($fromaddr eq "0:0/0.0") {
		 $fromaddr="";
	     }
	 }
	 if (/^#To: (.*)/) {
	     $to=$1;
	 }
	 if (/^#\@To: (.*)/) {
	     $toaddr=$1;
	     if ($toaddr eq "0:0/0.0") {
		 $toaddr="";
	     }
	 }
	 if (/^#Subject: (.*)/) {
	     $subject=$1;
	 }
	 if (/^#Date: (.*)/) {
	     $date=$1;
	 }
     }
     if ($mode==3) {
	 while (length $_ >$LINELENGTH) {
	     if (/^(.{0,$LINELENGTH})(\s+)/) {
		 printLine("$1\n");
		 $_ = substr($_,length $1.$2);
	     } else {
		 printLine(substr($_,0,$LINELENGTH)."\n");
		 $_ = substr($_,$LINELENGTH);
	     }
	 }
	 printLine($_);
     }
 }

print $RESET;
