#!/usr/bin/ksh93
################################################################
#### Program: column_k93
#### 
#### Description: Emulation of the Unix "column" command
#### 
#### Author: Dana French (dfrench@mtxia.com)
####         Copyright 2004
#### 
#### Date: 07/22/2004
#### 
################################################################
function column_k93 {
  typeset TRUE="0"
  typeset FALSE="1"
  typeset VERBOSE="${FALSE}"
  typeset VERYVERB="${FALSE}"
  typeset SCRWID="80"
  typeset MAXWID="0"
  typeset IDX="0"
  typeset LINE
  typeset FNAME
  typeset TABS="						"

  while getopts ":c:vV" OPTION
  do
    case "${OPTION}" in
        'c') SCRWID="${OPTARG}";;
        'v') VERBOSE="${TRUE}";;
        'V') VERYVERB="${TRUE}";;
        '?') print "Syntax: column_k93 [-] file ..." && return 4 ;;
    esac
  done
 
  shift $(( ${OPTIND} - 1 ))

  typeset STDIN="${1:+${FALSE}}"
  STDIN="${STDIN:-${TRUE}}"

#### Read in the data either from STDIN or one or more files
  if (( STDIN == TRUE ))
  then
    while read -r -- LINE
    do
        if [[ "_${LINE}" != "_" ]]
        then
            ARRY[${IDX}]="${LINE}"
            (( ${#LINE} > MAXWID )) && MAXWID="${#LINE}"
            (( IDX++ ))
        fi
    done
  else
    for FNAME in "${@}"
    do
      exec 0<"${FNAME}"
        while read -r -- LINE
        do
          if [[ "_${LINE}" != "_" ]]
          then
            ARRY[${IDX}]="${LINE}"
            (( ${#LINE} > MAXWID )) && MAXWID="${#LINE}"
            (( IDX++ ))
          fi
        done
      exec 0<&-
    done
  fi

#### Determine the number of data elements stored
  LASTIDX="${#ARRY[*]}"
#### Determine the column Width based on the widest data value
  (( COLWID = MAXWID + ( 8 - ( MAXWID%8) ) ))
#### Determine the number of columns to display within the screen width
  (( COLNBR = SCRWID / COLWID ))
#### Determine the number of Rows Per Column
  (( RPERC = ( LASTIDX - 1 ) / COLNBR ))
#### Determine the number of Tabs Per column
  (( TPERC = COLWID / 8 ))

  ROWCNT=1
  CURCOL=1
  while (( ROWCNT <= ( RPERC + 1 ) ))
  do
      (( LASTPOS = ( COLNBR * RPERC ) + ROWCNT ))
      (( COLNBR > RPERC )) && (( LASTPOS = LASTPOS + COLNBR - RPERC ))
      for (( POS=ROWCNT; POS<LASTPOS; POS = POS + RPERC + 1 ))
      do
          if (( CURCOL != 1 )) && [[ "_${ARRY[POS-1]}" != "_" ]]
          then
              (( TFILL = TPERC - ( ${#ARRY[PREVPOS]} / 8 ) ))
              print -r -n -- "${TABS:0:TFILL}"
          fi
          print -r -n -- "${ARRY[POS-1]}"
          if (( CURCOL == COLNBR ))
          then
              CURCOL=0
              print
          fi
          (( PREVPOS = POS - 1 ))
          (( CURCOL++ ))
      done
      (( ROWCNT++ ))
  done

  return 0
}
################################################################

column_k93 "${@}"