#!/usr/bin/ksh93
################################################################
#### Program: expand_k93
#### 
#### Description: Emulation of the Unix "expand" command
#### 
#### Author: Dana French (dfrench@mtxia.com)
####         Copyright 2004
#### 
#### Date: 07/22/2004
#### 
################################################################
function expand_k93 {
  typeset TRUE="0"
  typeset FALSE="1"
  typeset INITIAL="${FALSE}"
  typeset VERBOSE="${FALSE}"
  typeset VERYVERB="${FALSE}"
  typeset FNAME

  while getopts ":ivV" OPTION
  do
    case "${OPTION}" in
        'i') INITIAL="${TRUE}";;
        'v') VERBOSE="${TRUE}";;
        'V') VERYVERB="${TRUE}";;
        '?') print "Syntax: expand_k93 [-i] [file ...]" && exit 1 ;;
    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
      tabconvert_k93 "${INITIAL}"
  else
      for FNAME in "${@}"
      do
          exec 0<"${FNAME}"
            tabconvert_k93 "${INITIAL}"
          exec 0<&-
      done
  fi

  return 0
}
################################################################
function tabconvert_k93 {
  typeset INITIAL="${1}"
  typeset TRUE="0"
  typeset FALSE="1"
  typeset NONWHITE="${FALSE}"
  typeset PREVTAB="${FALSE}"
  typeset SPCS="        "
  typeset IDX="0"
  typeset CURCOL="0"
  typeset LINE
  typeset END
  typeset MODU

  while IFS="" read -r -- LINE
  do

    END="${#LINE}"
    NONWHITE="${FALSE}"
    PREVTAB="${FALSE}"
    CURCOL=0

    for (( IDX=0; IDX<=(END-1); ++IDX ))
    do

      if [[ "_${LINE:IDX:1}" = _$'\t' ]]
      then

        if (( INITIAL == TRUE )) && (( NONWHITE == TRUE ))
        then
          print -r -n -- "${LINE:IDX:1}"
          (( CURCOL++ ))
        else
          (( FILL = 8 - ( CURCOL % 8 ) ))
          (( PREVTAB == TRUE)) && FILL="8"
          print -r -n -- "${SPCS:0:FILL}"
          (( FILL == 8 )) && PREVTAB="${TRUE}"
          (( CURCOL = CURCOL + FILL ))
        fi

      else

        print -r -n -- "${LINE:IDX:1}"
        NONWHITE="${TRUE}"
        PREVTAB="${FALSE}"
        (( CURCOL++ ))

      fi

    done    # for loop

    print

  done    # while loop
}
################################################################

expand_k93 "${@}"