#!/usr/local/bin/perl

use strict;
use English;
use Socket;
use LPRng;

my(
	$Printer, $Pc_value, $Debug, $args, $pr, $remote, $port, $option,
	$options, $SOCK, $line, $prefix, $firstpart, $count, $max
);

$| = 1;

$Debug = 0;
Set_Debug($Debug);
Setup_LPRng( "P:svl");


# get the printer name
$Printer = Get_printer_name();
if( not $Printer ){
	die "missing printer name";
}

print "Printer '$Printer'\n" if $Debug;

$Pc_value = Setup_pc_entry( $Printer );

($pr, $remote, $port ) = Get_remote_pr_host( $Printer, $Pc_value );
print "pr '$pr', remote '$remote', port '$port'\n" if $Debug;

$args = Get_Args();

$option = 4;
$option = 3 if( $args->{'s'} );
$option = 8 if( $args->{'v'} );

$max = 0;
$max += $args->{'l'} if $args->{'l'};
if( $max > 4 ){
	$max = 0;
} else {
	$max = (1 << $max );
}

print "max $max\n" if $Debug;

$SOCK = getconnection( $remote, $port );

$options =  join (" ", @ARGV);
printf $SOCK "%c%s%s\n", $option, $pr, $options ? (" " . $options) : "";
$prefix = "";

while ( defined( $line = <$SOCK> ) ) { 
	if( $max ){
		($firstpart) = split( ":", $line );
		print "firstpart '$firstpart', count $count\n" if $Debug;
		$firstpart ||= "";
		if( $prefix eq $firstpart ){
			if( ++$count >= $max ){
				next;
			}
		} else {
			$count = 0;
			$prefix = $firstpart;
		}
	}
	print $line; 
} 
close ($SOCK) or die "close: $!"; 
exit 0;
