#!/usr/bin/env perl
# $Id: pack.pl,v 1.1 2012/05/07 20:44:48 ksb Exp $
# A much simpler version of binpack for items that cannont be		(ksb)
# order-permuted.  Quoted (in part) in the xapply/parallel.html page.

use lib  '/usr/local/lib/sac/perl'.join('.', unpack('c*', $^V)),
	'/usr/local/lib/sac';
use Getopt::Std;
use strict;

my($progname, %opts);
$progname = $0;
$progname =~ s/.*\///;
getopts("hVb:z", \%opts);

if ($opts{'V'}) {
	print "$progname: ", '$Id: pack.pl,v 1.1 2012/05/07 20:44:48 ksb Exp $', "\n";
	exit 0;
}
my($usage) = 'usage [-b bytes] [-z] [files]';
if ($opts{'h'}) {
	print "$progname: $usage\n",
		"$progname: usage -h\n",
		"$progname: usage -V\n",
		"-b bytes  size of each bin in bytes\n",
		"-h        only this help output\n",
		"-V        only version information\n",
		"-z        input is NUL (\\000) terminated\n";
#n files    the max number of files per bin
#o overhead how much overhead per file, after unit rounding (default "0")
#p packing  packing header size, added before rounding (default "0")
#r round    specify the round units to pack with (default "1")
# -w is always 1
	exit 0;
}

$/ = "\000" if ($opts{'z'});
my($bsize) = $opts{'b'};
my($argmax) = `sysctl -a kern.argmax 2>/dev/null` || 128*1024-16;
$bsize ||= $argmax =~ s/.*([0-9]*)\s*$/$1/;
print $bsize, "\n";
my($cur) = 0;
my($q,$l);
while ($q = <>) {
	chomp($q);
	$q =~ s/([\"\'\\\#\`\$\&;|*()?><\{~=[])/\\$1/g;
	$l = length(q)+8;
	if (0 == $cur) {
		print "$q";
		$cur = $l;
	} elsif ($cur+$l+1 < $bsize) {
		print " $q";
		$cur += $l+1;
	} else {
		print "\n$q";
		$cur = $l;
	}
}
if ($bsize > 0) {
	print "\n";
}

exit 0;
