#!/usr/bin/env perl

use strict;
use warnings;

my $pagesize = $ENV{'LINES'} || 22;

open(my $tty, '<', '/dev/tty')
    or die "$0: Cannot open /dev/tty for reading: $!";

sub evalcmd {
    {
	chomp($_ = <$tty>);
	if (/^q$/) {
	    exit(0);
	} elsif (/^!(.*)/) {
	    system($1);
	    redo;
	}
    }
}

sub printfile {
    my ($fh) = @_;
    my $lines = 0;
    while (<$fh>) {
	print;
	&evalcmd unless ++$lines % $pagesize;
    }
}

unshift(@ARGV, '-') unless @ARGV;

my $n = $#ARGV;
for (@ARGV) {
    if (/^-$/) {
	&printfile(\*STDIN);
	&evalcmd if $n--;
    } elsif (/^-(\d+)$/) {
	$pagesize = $1;
    } else {
	open(my $fh, '<', $_) or die "$0: Cannot open $_ for reading: $!";
	&printfile($fh);
	&evalcmd if $n--;
	close($fh);
    }
}

close($tty);
