#!/usr/bin/perl -w -n
# syntax: pagebreak number-of-lines-per-page
#  this program reads a text file containing FF ^L chars ('\f' == 0x0c == 12),
#  which represent section or page breaks, and adds or removes ^L characters so
#  that each section in the input document delimited by ^L characters is not
#  split across a page unless it is longer than a page, and multiple sections
#  are put on a page whenever possible.
# The section break ^L should go before the usual blank lines that may separate
# paragraphs.

use Data::Dumper;
use strict;

our ($lines_per_page, $page, $page_lines, $section, $section_lines);

BEGIN {
	$lines_per_page = shift;
	$page = "";
	$page_lines = 0;
	$section = "";
	$section_lines = 0;
}

if (/\f/) {
	if (!/^.$/) {
		die "^L must be the only character on a line by itself:\n".Dumper($_)."\n";
	}
	$page .= $section;
	$page_lines += $section_lines;
	while ($page =~ s/^\n//) { --$page_lines; }
	$section = "";
	$section_lines = 0;
} else {
	$section .= $_;
	++ $section_lines;
}

if ($page_lines && $page_lines + $section_lines > $lines_per_page) {
	print "$page\f\n";
	$page_lines = 0;
	$page = "";
}

END {
	$page .= $section;
	$page_lines += $section_lines;
	while ($page =~ s/^\n//) { --$page_lines; }
	print "$page\f\n";
}
