#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'loopingpaste' is similar to paste but shorter files are repeated so the final output
# is as long as the longest file supplied.
#
# $Id: loopingpaste,v 1.3 2014-01-17 13:39:16 bojar Exp $
#

use strict;
use Getopt::Long;

sub usage {
  print STDERR "loopingpaste file1 file2 file3 ...
Options:
  --breaks  ... add a blank line whenever any of the input files is restarted
";
  exit 1;
}

my $usage = 0;
my $breaks = 0;
my $delimiter = "\t";
GetOptions("help" => \$usage,
  "breaks" => \$breaks,
  "delimiter=s" => \$delimiter,
);
usage() if $usage;

$delimiter =~ s/\\t/\t/g;
$delimiter =~ s/\\n/\n/g;

my @files = map { load($_) } @ARGV;

my $max = undef;
foreach my $lines (@files) {
  $max = scalar(@$lines) if !defined $max || $max < scalar(@$lines);
}

for(my $i=0; $i<$max; $i++) {
  my $break = 0;
  for(my $f=0; $f<=$#files; $f++) {
    my $lines = $files[$f];
    print $lines->[$i % scalar(@$lines)];
    $break = 1 if $breaks && 0 == ($i+1) % scalar(@$lines);
    print $delimiter if $f < $#files;
  }
  print "\n";
  print "\n" if $break;
}

sub load {
  my $fn = shift;
  my @data = ();

  my $stream;
  if ($fn eq "-") {
    $stream = *STDIN;
  } else {
    open $stream, $fn or die "Can't read $fn";
  }
  while (<$stream>) {
    chomp;
    push @data, $_;
  }
  close $stream if $fn ne "-";
  return [@data];
}
