#!/usr/cs/bin/perl

# Formats ASCII text for the PalmPilot. Tries to make ASCII drawings look
# right under the Pilot's proportional font. 

# Written by David Coppit (david@coppit.org,
# http://www.coppit.org/index.html)
# Please send me any modifications you make. (for the better, that is. :) Feel
# free to modify, adapt, or redistribute, but please leave original authorship
# credit to me.

# Usage: formatit [input] > [output]

if ($#ARGV == -1)
{
  die "Give an argument file to format for the pilot.\n";
}

open (INPUT, $ARGV[0]);

$" = "";

while ($line = <INPUT>)
{
  # Ignore more than 1 more empty line (already printed one at the end of the
  # last iteration).
  $count = 0;
  if ($line eq "\n")
  {
    print $line;

    $count++;
    while (($line = <INPUT>) && ($line eq "\n"))
    {
      $count++;
    }
  }

  # Get a paragraph
  @para = ();
  do
  {
    push @para, $line;
  }
  while (($line = <INPUT>) && ($line ne "\n"));

  if (eof(INPUT))
  {
    exit;
  }

  $linepara = join("",@para);

  # Try to detect illustrations
  if ($linepara =~ /[\/|_\\].*[\/|_\\].*[\/|_\\].*[\/|_\\]/)
  {
    # Convert " " to "  " for proportional font
    grep { s/ /  /g } @para;
    print @para;
  }

  # Try to detect lists
  elsif (($#para > 0) && (length($para[0]) < 55) && (length($para[1]) < 55))
  {
    print @para;
  }

  # Try to detect blockquotes
  elsif (($para[0] =~ /^\s\s\s\s\s*\S/) &&
         ($para[1] =~ /^\s\s\s\s\s*\S/))
  {
    print @para;
  }

  # Try to detect TOC
  elsif (($#para > 2) &&
         ($para[0] =~ /^\s*\d/) &&
         ($para[1] =~ /^\s*\d/) &&
         ($para[2] =~ /^\s*\d/))
  {
    print @para;
  }

  else
  {
    $linepara =~ s/\n/ /g;
    $linepara =~ s/ $/\n/;
    print $linepara;
  }

  # Print the newline between paragraphs.
  print $line;
}

close INPUT;
