#!/bin/bash
#
# given a column/row, length N, print matrix with NROW elements/row 
#  	rc2mat -n NROW  {-r}  [-d DFS] {-h} infile
# DFS is single-char delimator such as , : ";" "\t"
# -r .. input is row vector (default, input is column)
# IFS for input row vector is awk default of "(\s+|\t)"

# usage: rc2mat -n 3 <(seq 9)
# 1 4 7
# 2 5 8
# 3 6 9
# usage: rc2mat -n3 -r <(echo {01..10})
#

#-----------------------------------------------------------------------
# limitations: number of rows < NMAX
#-----------------------------------------------------------------------
ROW=;  DFS="\t"; HELP=;
NMAX=100;
TF="OUT_rc2mat_"
trap "[ -e ${TF}_01.tmp ] && rm ${TF}*.tmp" EXIT
#-----------------------------------------------------------------------

while getopts n:d:rh OPTVAL
do 
    case $OPTVAL in
	n) NROW=$OPTARG;;
        d) DFS=$OPTARG;;
	r) ROW=1;;      
        h) HELP=1;;
        *) echo "choose -h for help"; exit -1;;
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
  echo -e "\n given column print matrix with row length of NROW"
  echo -e " rc2mat -n NROW [-d DFS] {-r} {-h} infile (or pipe)"
  echo -e " by default, input file or pipe is assumed to be column vector"
  echo -e " -d DFS, the field separator output"
  echo e " -r .. input is not column but row vector with awk IFS "
  exit
fi

[ -z $NROW ] && { echo "rc2mat: row length must be specified"; exit -1; }
[ $NROW -ge $NMAX ] && { echo "requested $NROW rows > max $NMAX"; exit -1; }

#-----------------------------------------------------------------------
# check to see if data is being supplied by pipe
#-----------------------------------------------------------------------

case $# in
    0) if [ -p /dev/stdin ]; then
          set -- "/dev/stdin"                     #set $1=/dev/stdin
        else
          echo "no file given nor is there a trailing pipe"
          exit -1;
       fi
       cat $1 > $TFILE; IFILE=$TFILE;;
    1) IFILE=$1;;
    *) echo "rc2mat: accpets only one input file"; exit -1;;
esac

#-----------------------------------------------------------------------
# delete stale temporary files
#-----------------------------------------------------------------------
if ls ${TF}*.tmp 1> /dev/null 2>&1; then
  rm ${TF}*.tmp
fi

#-----------------------------------------------------------------------
# finally action
#-----------------------------------------------------------------------
if [ $ROW ]; then

   cat $IFILE | xargs -n1 | \
   awk -v nr=$NROW -v TF=$TF '{i=int((NR-1)/nr+1);ind=sprintf("%02d",i)
        print $0  > TF ind ".tmp"}'	
else

    awk -v nr=$NROW -v TF=$TF '{i=int((NR-1)/nr+1);ind=sprintf("%02d",i) 
	print $0  > TF ind ".tmp"}' $IFILE
fi

paste -d "$DFS" ${TF}*.tmp 
