#!/usr/bin/perl -w -n
# syntax: pages-split number-of-lines-per-page
#  this program reads a text file containing FF ^L chars ('\f' == 0x0c == 12),
#  which represent page breaks, and adds ^L characters to split long pages
#  such that no page is longer than number-of-lines-per-page

use Data::Dumper;
use strict;

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

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

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

END {
	if ($page_lines) {
		print "$page\f\n";
	}
}
