#!/bin/bash

inputfile=$1
outputfile=$2
removeheader=$3	
columns="$@"

cols="${columns// /,}" #make comma-separated

#skip first three arguments
firstcomma=`expr index "$cols" ,`
cols="${cols:$firstcomma}"
secondcomma=`expr index "$cols" ,`
cols="${cols:$secondcomma}"
thirdcomma=`expr index "$cols" ,`
cols="${cols:$thirdcomma}"
cols="${cols//:/}" #remove colons
echo "colums to print: $cols"

arr=$(echo $cols | tr "," "\n")

for x in $arr
do
    echo $x
done

myArray=($columns)
i=3
len=${#myArray[@]}
mycols=""
echo "len: $len"
while [ $i -le $len ]
do	
	echo "myarray: ${myArray[$i]}"
	mycols+=${myArray[$i]}
	i=$[$i+2]
done
mycols="${mycols//:/,}" #make comma-separated
mycols="${mycols%?}"
echo "mycols: $mycols"

awk 'BEGIN{
		FS="\t";
		OFS="\t";
		columns="'"$mycols"'";
		len=split(columns,arr,",")
	}{
	 if (index($1,"#")==1 || $1==""){ #print header as--s
		if("'"$removeheader"'"=="N"){
            print $0
		}
	 }	
	 else{	
		 for (i=1;i<len;i++){
			j=arr[i]
			printf $j"\t"
		 }
		 j=arr[len]
		 printf $j"\n"	
	}
	}END{

	}' $inputfile > $outputfile


