my $pages_this_chapter = 0; while () { if (current_line_is_the_kdkhost_line()) { next } # Don't forget the special case # if (current_line_is_a_chapter_end() || $. == 1) { print OUT $chapterization_command; $pages_this_chapter = 0; next; # ??? } if (current_line_starts_a_new_page()) { $pages_this_chapter++; if ($pages_this_chapter == 3) { print OUT $send_to_binder } } if ($pages_this_chapter <= 2) # 3? { change_the_paper_output_tray() } print OUT; } #### sub current_line_is_the_kdkhost_line { m/^%KDKHost:/; } sub current_line_is_a_chapter_end { m!<>setpagedevice!; } sub current_line_starts_a_new_page { /%%BeginPageSetup/; } sub change_the_paper_output_tray { m!<>setpagedevice! and s/Stacker/top/; }