#!/Perl
# test.pl
# AIM: Test a 'wrapping' function, 'max_sub' ...
my $LF;
my $outfile = 'temp.'.$0.'.txt';
require "logfile.pl" or die "Missing logfile.pl ...\n";
open_log($outfile);
prt( "$0 ... Hello, World... output to $outfile ...\n" );
my $maxtit = 'Domain Name Registration, Domain Transfers. Your domain name search starts here.';
my $maxwid = length($maxtit);
my $test = 'Links\Download this directory compare and file compare software - Beyond Compare lets you compare text files, synchronize folders, an';
my $test2 = 'Unix\http--rds.yahoo.com-_ylt=A0Je5EsJF3dE_ksAzOJXNyoA;_ylu=X3oDMTE2YWZxZzBjBGNvbG8DdwRsA1dTMQRwb3MDNQRzZWMDc3IEdnRpZANERlg1XzMw-SI';
my $test3 = 'Low cost domain names, domain transfers, web hosting, email accounts, and so much more.';
my $line = '';

do_one($maxtit);
do_one($test);
do_one($test2);
do_one($test3);

close_log($outfile,1);
exit(0);

sub do_one {
	my ($t) = shift;
	$line = max_sub($t, $maxwid);
	prt( "From\n[".$t."]\n" );
	prt( "Got\n[".$line."]\n" );
}

sub max_sub {
	my ($ln, $max) = @_;
	my $nln = $ln;
	if (length($ln) > $max) {
		my @arr = split(/ /,$ln);
		$nln = '';
		my $bit = '';
		my $bl = 0;
		my $sl = 0;
		my $sc = 0;
		foreach my $s (@arr) {
			$sl = length($s);
			$bl = length($bit);
			while ($sl > $max) {
				if ($bl) {
					$bit .= ' ';
				}
				$bit .= substr($s, 0, $max - $bl);
				$s = substr($s, $max - $bl);
				if (length($nln)) {
					$nln .= "<br>\n";
				}
				$nln .= $bit;
				$bit = '';
				$sl = length($s);
				$bl = length($bit);
				$sc = 0;
			}
			if ($bl) {
				if (( $bl + $sc + length($s) ) > $max ) {
					if (length($nln)) {
						$nln .= "<br>\n";
					}
					$nln .= $bit;
					$bit = $s;
					$sc = 0;
				} else {
					$bit .= ' ';
					$sc++;
					$bit .= $s;
				}
			} else {
				$bit = $s;
				$sc = 0;
			}
		}
		if (length($bit)) {
			if (length($nln)) {
				$nln .= "<br>\n";
			}
			$nln .= $bit;
		}
	}
	return $nln;
}

# eof
