#!/bin/sh
#
# columnize [-n] gutWidth [-]ColWidth ...
#
# Program to columnize lines from stdin and put to stdout
# Adjacent input lines are placed left to right, not vertically.
#
# If -n is specified, each output entry will be prefixed by the input line 
# number for that entry (and a closing parenthesis). Similar results can
# be achieved by "cat -n - | columnize ...."
#
# gutWidth specifies the minimum number of blank spaces between two entries in
# a row.
#
# ColWidth specifies the amount of space reserved for the respective column.
# A Column entry is left adjusted if the associated ColWidth is positive, 
# right adjusted if it is negative.
# The last entry in a row will NOT be padded to ColWidth (assuming positive), 
# but may be truncated.
#
# see also: paste(1)
#

if [ "X$1" = "X-n" ]; then
    number="true"
    shift
fi
{
    echo $*
    /bin/cat -
} | awk '
    NR == 1 {
	gutW = $1						#gutter Width
	nCols = NF-1
	for( i = 2; i <= NF; i++ )				#column Widths
	    colW[i-2] = $i
	currCol = 0
    }
    NR > 1 {
	currColW = colW[currCol]
	if ( currColW < 0 ) {
	    rAdj = "true"
	    currColW = 0 - currColW
	} else
	    rAdj = "false"
	if ( "'$number'" == "true" ) {
	    lineNum = sprintf( "%2d) ", NR-1 )
	    currColW -= 4					#length(lineNum)
	} 
	prline = substr( $0, 1, currColW )			#truncate
	if ( currCol == nCols-1 ) {				#last col
	    if ( rAdj == "true" )				#pad on left
		format = "%" currColW "s\n"
	    else						#no padding
		format = "%s\n"
	    currCol = 0
	} else {
	    if ( rAdj == "true" )				#pad on left
		format = sprintf( "%%" currColW "s%" gutW "s" , "" )
	    else						#pad on right
		format = "%-" currColW + gutW "s"
	    currCol++
	}
	printf( lineNum format, prline )
    }
    END {
	if ( currCol != 0 )
	    print ""						#finish line
    }'

