#!/usr/pkg/bin/perl

=begin metadata

Name: asa
Description: interpret ASA/FORTRAN carriage-controls
Author: Jeffrey S. Haemer
License: perl

=end metadata

=cut


use strict;

use File::Basename qw(basename);

use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;

my $Program = basename($0);

if (grep /\A\-/, @ARGV) {
	warn "usage: $Program [file ...]\n";
	exit EX_FAILURE;
}
my $rc = EX_SUCCESS;
foreach my $file (@ARGV) {
	next if (-d $file);
	my $fh;
	unless (open $fh, '<', $file) {
		warn "$Program: Can't open '$file': $!\n";
		$rc = EX_FAILURE;
		next;
	}
	run_file($fh);

	unless (close $fh) {
		warn "$Program: Can't close '$file': $!\n";
		$rc = EX_FAILURE;
	}
}
unless (@ARGV) {
	run_file(*STDIN);
}
exit $rc;

sub run_file {
	my $fh = shift;

	my %prefix = (
		'1' => "\f",
		'+' => "\r",
		'0' => "\n\n",
		'-' => "\n\n\n",
	);
	while (<$fh>) {
		chomp;
		if (!length($_)) {
			print "\n";
			next;
		}
		my $c = substr $_, 0, 1;
		$_ = substr $_, 1;
		my $p = exists $prefix{$c} ? $prefix{$c} : "\n";
		print $p, $_;
	}
}

=head1 NAME

asa - interpret ASA/FORTRAN carriage-controls

=head1 SYNOPSIS

asa [I<filename> ...]

=head1 DESCRIPTION

=over 2

Traditional FORTRAN programs put carriage-control characters
in the first columns of their output,
which were interpreted by older lineprinters
according to the ASA vertical format control standard.
(ASA was the American Standards Association -- now ANSI.)

Under this standard, the first character of each printable record (line)
determines vertical spacing, as follows:

=over 2

I<blank>    carriage return
0           two carriage returns
1           Formfeed
+           overprint
-           three carriage returns (IBM extension)

=back

All other characters are discarded, and empty lines behave as though
they have a leading blank.

B<asa> interprets these characters.

=back

=head1 EXIT VALUES

=over 2

0 normal exit

1 inability to write on stdout or to read an input file

2 bad argument

Exit status values chosen from MKS toolkit.

=back

=head1 AUTHOR

Jeffrey S. Haemer

=head1 BUGS

Currently, B<asa> just looks at the readability of its input files
at startup time.  It should really do it a file at a time,
but that makes the code look gross.

The carriage-control '-' is an IBM extension.
Perhaps the default should ignore it
and there should be a '-i' option to interpret it.

=head1 SEE ALSO

Communications of the ACM, Vol 7, No. 10, p. 606, October
1964.

NWG/RFC 189, Appendix C

=cut
