#!/usr/bin/perl

#	texlinebreak -- This function takes a text file, and
#		forces line breaks in lines that are longer than
#		$maxlength characters.  Breaks will be inserted
#		before the last word before $maxlength characters.
#
#		Output is to standard output.
#

$maxlength = 60;	# Characters before line break.

# =========== GET Command Line Arguments  ===========
$err = 0;

if (!(@ARGV))
    {
    print("Usage:  texlinebreak <file>  \n");
    $err = 1;
    }

if ($err==0)
	{
  	$noerr = (defined(open(INFILE,$ARGV[0])));		# Source file

    	$line = <INFILE>;
    	while (defined($line)) 

		{
		chomp($line);
		while (length($line) >= $maxlength)
			{
			# find the last white-space character in the
			# first $maxlength characters.  Print out 
			# the characters before that, with line break.
			# Then leave $line as the remainder, minus the
			# white-space character.

			$maxlenline = substr($line,0,$maxlength-1);
			if ( $maxlenline =~ /(.*)(\s)(.*?)$/ )
				{
				$toprint = $1;
				$line=substr($line,length($toprint)+length($2));
				while ($line =~ /^ (.*?)$/ )	
					{
					$line = $1;	# Remove pre-spaces.
					}
				}
			else
				# No white space found.  Just print line.
				# print("\n>>>> Error - no whitespace. \n\n");
				{
				$toprint = $line;
				$line="";
				}
			print("$toprint\n");
			}
		print("$line\n");
    		$line = <INFILE>;
		}
	}


