#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'colwise' splits the input vertically, separating the indicated column. An
# arbitary command is then executed on the cut-out column. The output of the
# command is pasted again in the (vertical) middle of the file.
#
# The output of the command is assumed to have the same number of lines as the
# input.
#
# $Id: colwise,v 1.4 2005/11/11 08:04:19 bojar Exp $

use strict;
use Getopt::Long;
use FileHandle;
use IPC::Open2;

sub usage {
  print STDERR "colwise COLUMN COMMAND <stdin >stdout
  --delim=NEW_DELIMITER
";
  exit 1;
}

my $usage = 0;
my $delim = "\t";
my $autoprefix = 0;
GetOptions("help" => \$usage, "delim=s" => \$delim,
  "auto-prefix" => \$autoprefix
);
my $col = shift;
my $cmd = shift;
usage() if $usage || !defined $cmd || !defined $col;
$col--;
 
my @prefixes = ();
my @suffixes = ();
my $pid = open2(*Reader, *Writer, $cmd );
while (<>) {
  chomp;
  my $line = $_;
  my @line = split /$delim/o, $line;
  my $prefix = join("$delim", @line[0..$col-1]);
  $prefix = 0 if $col==0;
  my $suffix = join("$delim", @line[$col+1..$#line]);
  $suffix = 0 if $col==$#line;

  # print STDERR "$line[$col]\n";

  print Writer $line[$col]."\n";

  push @prefixes, $prefix;
  push @suffixes, $suffix;
}
close Writer;

while (<Reader>) {
  chomp;
  # print STDERR "READ $_\n";
  my $data = $_;
  my $prefix = shift @prefixes;
  my $suffix = shift @suffixes;

  if ($prefix) {
    print "$prefix$delim";
  }
  print $data;
  if ($suffix) {
    print "$delim$suffix";
  }
  print "\n";
}

close Reader;
waitpid $pid, 0;
