#!/bin/csh -f

# Transform standard input into a multicolumn format with successive
# blocks of lines forming successive columns.  The number of columns
# is $1 and must be less than 100.  $2 can be used to provide a
# replacement string for the normal column separation of a single tab,
# assuming there were no tabs (nor ^G) in the original standard input.
# Can also use $3 to specify an input file instead of standard input,
# and then the ouput will also go on $3.

set tempfile = /tmp/multicols.$USER.$$

cat $3 > $tempfile

set numlines = `cat $tempfile| wc -l`

@ linespercol = ($numlines + $1 - 1) / $1

cat $tempfile \
  | awk 'BEGIN {col=1; lineincol='$linespercol'+1}\
         {if (lineincol > '$linespercol') {\
             col++;\
             if (col<9) col = "0" col;\
             temppart = "'$tempfile'." col;\
             lineincol=1}}\
          {print > temppart; lineincol++}'

set tabreplacement = '	'

if ($#argv > 1) set tabreplacement = "$2"

if ($#argv > 2) then
  paste $tempfile.* | tr '\011' '' | sed "s$tabreplacementg" > $3
else
  paste $tempfile.* | tr '\011' '' | sed "s$tabreplacementg"
endif

\rm -f $tempfile $tempfile.*
