#!/usr/bin/perl
#   mfl [$len]
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# This little program reads in a portion of a makefile, and reformats #
# it in a conventional manner.
#
# See also sh/mkjoin.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$len = $ARGV[0] || 88;

# Read in the data and collect the file names.
line:
while ($line = <STDIN>) {
	if ($line =~ /^#/) {	# Comment?
		print $line;
		next line;
	}
	if ($line =~ /^\w+\s*=/) {	# Macro?
		while ($line =~ /\\\s*$/) {	# Continued?
			print $line;	# Eat up the rest of the macro.
			$line = <STDIN>;
		}
		print $line;
		next line;
	}
	while ($line =~ s/\\\s*$//) {	# Continued?
		$cont = <STDIN>;
		$line .= $cont;	# Join all the continuations.
	}
	if ($line =~ s/^([\$\w]+.*):\s*/\t/) {	# Rule?
		$t = $1;	# Note targets.
		&wrapup();	# Finish off previous entry.
		($trg = $t) =~ s/\s+/ /g;
		if ($line =~ s/^\s*(.*)\s*;/\t/) {
			($dep = $1) =~ s/\s+/ /g;
		} else {
			($dep = $line) =~ s/\s+/ /g;
			$line = '';
		}
		&outline("$trg: $dep");
	}
	# The line should now contain only commands
	if ($line =~ s/^\t\s*//) {
		@line = split(/[;\n]/,$line);
		foreach $cmd (@line) {
			$cmd =~ s/^\s+//;
			$cmd =~ s/\s+$//;
			next if !$cmd;
			&outline("\t$cmd");
		}
	} else {
		print $line;
	}
}
&wrapup();

sub outline {
	local($l) = @_;
	local(@l,$i,$x);
	if ($l =~ s/^(\s+)//) {
		$x = $i = $1;
	}
	@l = split(/\s+/,$l);
	for (@l) {
		if (length($x) + length($_) > $len) {
			print "$x\\\n";
			$x = "$i\t";
		}
		$x .= "$_ ";
	}
	$x =~ s/\s+$//;
	print "$x\n" if $x;
}

sub wrapup {
}
