#!/usr/local/bin/perl -w-- # -*- perl -*-
#
# $Id: lp_format,v 1.2 1994/09/10 18:20:49 qjb Exp $
# $Source: /home/qjb/scripts/RCS/lp_format,v $
# $Author: qjb $
#
# Expand tabs and wrap lines in an input file
#

# This code, from the perl manual page, forces this to be run by perl from 
# perl, sh, or csh.  It must be first.
eval '(exit $?0)' && eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'
& eval 'exec /usr/local/bin/perl -S $0 $argv:q'
    if 0;

$whoami = ($0 =~ m,([^/]*)$,) ? $1 : $0;

&usage if (@ARGV < 1);

$tabwidth = 8;
$ncolumns = 80;			# columns per row

for (@ARGV) {
    &expand_file($_);
}


sub expand_file {
    local($filename) = $_[0];
    local($col) = 0;
    local($line) = "";
    local(@output) = ();

    open(INFILE, "<" . $filename) || do {
	print STDERR "Failed to open $filename to read: $!\n";
	return;
    };

    while (<INFILE>) {
	$col = 0;
	$line = "";

	chop;
	while (length) {
	    s/^[^\t]+// && do {
		$col += length($&);
		$line .= $&;
	    };
	    s/^\t+// && do {
		local($ntabs, $tcol, $nspaces);
		$ntabs = length($&);
		# For first tab, skip over $tabwidth spaces; then go back to
		# the first tab stop after the current column.
		$tcol = $col + $tabwidth;
		$tcol -= $tcol % $tabwidth;
		$nspaces = ($tcol - $col);
		$ntabs--;
		$nspaces += ($tabwidth * $ntabs);
		$col += $nspaces;
		$line .= (" " x $nspaces);
	    };
	}
	while (length($line) > $ncolumns) {
	    push(@output, substr($line, 0, $ncolumns));
	    substr($line, 0, $ncolumns) = "";
	}
	if (length($line)) {
	    push(@output, $line);
	}
    }

    while(@output) {
	print shift(@output), "\n";
    }
}
    
sub usage {
    print STDERR "Usage: $whoami file [ file ... ]\n";
    print STDERR "  Expand tabs and wrap lines in given files.\n";
}
