#!/usr/bin/ksh93
################################################################
#### Program: transpose_k93
#### 
#### Description: Transposes one or more columns of data into 
#### rows.  Allows the user to specify insets and offsets within
#### the dataset to select portions of data to transpose.
#### 
#### Author: Dana French (dfrench@mtxia.com)
#### 
#### Date: 07/22/2004
#### 
################################################################
function transpose_k93 {
  typeset TRUE="0"
  typeset FALSE="1"
  typeset FNAME=""
  typeset DELIM="${IFS}"
  typeset XINSET="0"
  typeset XOFFSET="9999999999"
  typeset YINSET="0"
  typeset YOFFSET="9999999999"
  typeset VARS
  typeset VALS
  typeset STDIN="${1:+${FALSE}}"
  STDIN="${STDIN:-${TRUE}}"

  while getopts ":d:x#y#X#Y#vV" OPTION
  do
    case "${OPTION}" in
        'r') REVERSE="${TRUE}";;
        'd') DELIM="${OPTARG}";;
        'x') XINSET="${OPTARG}";;
        'y') YINSET="${OPTARG}";;
        'X') XOFFSET="${OPTARG}";;
        'Y') YOFFSET="${OPTARG}";;
        'v') VERBOSE="${TRUE}";;
        'V') VERYVERB="${TRUE}";;
        '?') print "Syntax: transpose [-d DELIMETER] [-x INSET] [-X OFFSET] [-y INSET] [-Y OFFSET]" && exit 1
    esac
  done
 
  shift $(( ${OPTIND} - 1 ))

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

  if (( STDIN == TRUE ))
  then

    IFS="${DELIM}"$'\n'
    read -r -A -- VARS
    VALS=( "${VARS[@]}" $( cat ) )
    IFS=$' \t\n'

    transposition_k93 VARS VALS "${DELIM}" ${XINSET} ${XOFFSET} ${YINSET} ${YOFFSET}

  else

    for FNAME in "${@}"
    do
      if [[ -f "${FNAME}" ]]
      then      

        IFS="${DELIM}"$'\n'
        read -r -A -- VARS < "${FNAME}"
        VALS=( $( cat "${FNAME}" ) )
        IFS=$' \t\n'

        transposition_k93 VARS VALS "${DELIM}" ${XINSET} ${XOFFSET} ${YINSET} ${YOFFSET}

      else
        print -u 2 "ERROR: \"${FNAME}\" does not exist or is not a regular file."
      fi
    done
  fi
  return 0
}
################################################################
function transposition_k93 {
    nameref VARS="${1}"
    nameref VALS="${2}"
    typeset DELIM="${3}"
    typeset XINSET="${4}"
    typeset XOFFSET="${5}"
    typeset YINSET="${6}"
    typeset YOFFSET="${7}"
    typeset CNUM COLS XCOLS
    typeset RNUM ROWS YROWS
    typeset C1="0"

    (( COLS = ${#VARS[*]} ))
    (( XCOLS = COLS ))
    (( XOFFSET <= COLS )) && (( XCOLS = XOFFSET - XINSET ))

    (( ROWS = ${#VALS[*]} / ${#VARS[*]} ))
    (( YROWS = ROWS ))
    (( YOFFSET <= ROWS )) && (( YROWS = ROWS - ( ROWS - YOFFSET + 1 ) ))

    for (( CNUM=XINSET; CNUM<XCOLS; ++CNUM ))
    do
      for (( RNUM=YINSET; RNUM<YROWS; ++RNUM ))
      do
        (( CNUM != 0 && RNUM == YINSET && C1 != 0 )) && print
        (( RNUM != YINSET )) && print -n -- "${DELIM:0:1}"
        print -r -n -- "${VALS[CNUM+(RNUM*COLS)]}"
        C1="1"
      done
    done
    print

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

transpose_k93 "${@}"