#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'unziplines' reads stdin and produces FILECOUNT files with lines
# "unzipped". If you combine all output files in the original order
# using 'ziplines', you get the original input stream.
# Use '%i' in outname as the placeholder for filecount
#
# $Id: unziplines,v 1.1 2007/08/02 07:05:16 bojar Exp $
#

use strict;
use Getopt::Long;
use IO::File;

my $usage = 0;
my $debug = 1;

GetOptions(
  "help" => \$usage,
  "debug" => \$debug,
);

my $modulo = shift;
my $outname = shift;

if ($usage || !defined $modulo || !defined $outname) {
  print STDERR "unziplines N OUTFILENAME < input > remaining_lines
'unziplines' reads stdin and produces FILECOUNT files with lines 'unzipped'. If
you combine all output files in the original order using 'ziplines', you get
the original input stream.
Use '\%i' in outname as the placeholder for filecount.
";
  exit 1;
}


my @streams = map {
    my $ofn = sprintf(">$outname", $_-1);
    IO::File->new($ofn) or die "Can't write $ofn";
  } (1..$modulo);

my $nr = 0;
while (<>) {
  my $mod = $nr % $modulo;
  *STREAM= $streams[$mod];
  print STREAM $_;
  $nr++;
}

