#! /bin/zsh

# 2-dim transpose or rotate input
# ... online at http://www.jjj.de/
# author: Joerg Arndt ( arndt (AT) jjj.de )
# version: 2007-July-04 (04:44)


xr=''
xc=''
L=''
while getopts :rcL: OPT; do
    case $OPT in
        r|+r)  xr='1';
            ;;
        c|+c)  xc='1'
            ;;
        L|+L)  L=$OPTARG;  # max num of lines in output
            ;;
       *)
        THIS=${0##*/};
        echo "${THIS}: 2-dim transpose or rotate input.";
        echo "usage: ${THIS} [OPTION(s)]";
        echo " By default the data is transposed.";
        echo " Option -c reverses column order (90 deg CW rotation).";
        echo " Option -r reverses row order (90 deg CCW rotation).";
        echo " Options -rc give transposition around the other diagonal.";
        echo " Option -L <num> gives max number of lines of output.";
        echo " Try the following commands:";
        xstr='1-2\n| |\n3-4';
#        xstr='--\n--\n';
#        xstr='1.2\n. .\n3.4';
#        xstr='Hello\nSunny';
#        xstr='12\n34';
#        xstr='123\nABC\nXYZ';
        echo -E "  echo -e '${xstr}'";
        echo -E "  echo -e '${xstr}' | ${THIS}";
        echo -E "  echo -e '${xstr}' | ${THIS} -c";   # same as: rotate | rev
        echo -E "  echo -e '${xstr}' | ${THIS} -r";
        echo -E "  echo -e '${xstr}' | ${THIS} -rc";
#        echo " ... and compare to:";
#        echo -E "  echo -e '${xstr}' | rev";
#        echo -E "  echo -e '${xstr}' | tac";
#        echo -E "  echo -e '${xstr}' | rev | tac";
#        echo -E "  echo -e '${xstr}' | tac | rev";
        exit 2
    esac
done
shift $[ $OPTIND - 1 ]


LC_ALL=C
IFS='\0'

#set -vx

# read and count lines:
nr=1
while read -r a; do;
    txt[nr]=$a;
    nr=$(( nr+1 ));
done
nr=$(( nr-1 ));
if [[ ${nr} -eq 0 ]]; then  exit 0;  fi # nothing to do


# get maximum line length:
nc=0
for (( k=1; k<=nr; ++k )); do
    a=$txt[$k];
    z=${#a};
    if [[ $z -gt ${nc} ]]; then  nc=$z;  fi
done

[[ $L != '' ]] && nc=$L

#for (( k=1; k<=nr; ++k )); do # debug: check input
#    a=$txt[$k];
#    print -- "$k: [$a]";
#done

# get row output order:
if [ -z "$xr" ]; then
    c0=1; ce=$(($nc+1)); cs=1;
else
    ce=0; c0=$(($nc)); cs=-1;
fi

# get column output order:
if [ -z "$xc" ]; then
    r0=1; re=$(($nr+1)); rs=1;
else
    re=0; r0=$(($nr)); rs=-1;
fi


# print out transposed:
for (( c=c0; c!=ce; c+=cs )); do
    for (( r=r0; r!=re; r+=rs )); do
        a=$txt[$r];
        z=$a[$c,$c];
        test -z "$z" && z=" ";
#        print -n -- "  $c,$r=[$z] : ";  # debug
        print -n -- "$z";
    done
    print
done

exit 0;
#########################
