#!/bin/bash
# This script transposes column wise representation to row-wise
# It ignores comments with # in the beginning 

echo This script transposes column wise representation to row-wise
echo Transposing file 1 to file 2 ...
echo
echo You have to specify input file and output file as arguments.

echo 'Read from file ' $1
echo 'Write to file  ' $2

awk '
BEGIN{print "# Transposer for tracked data. Original header below"
 tsteps=0;
 values=0; }
{ 
    if( match($0,"#")) {
    print $0;
} else {
    tsteps++;
    values=NF;
    for (i=1; i<=NF; i++)  {
        a[NR,i] = $i
    } }
}
NF>p { p = NF }
END {    
    for(j=1; j<=p; j++) {
        str=a[1,j]
        if(j == 1) str="# "str;
        for(i=2; i<=NR; i++){
            str=str" "a[i,j];
        }
        print str
    }
}
END{ print "# done for tsteps:",tsteps," and nvalues:",values;
}' $1 > $2     
echo 'Finished transposing.'
