#!/bin/bash

if [ -z "$1" ]
then
echo "please pass an argument"
exit 1
fi

echo "Let's Roll baby"

FILENAME="$1"
OutputFileName="${FILENAME%.*f}.final"

count=0
currentsnploc=0

chr=""
snppos=0
A=""
G=""
C=""
T=""

echo "variables initialized!"

while read line 
do
	((count++))
#	echo "operating on row $count"
#	if [ "$count" -ge 20 ]
#	then
#	break
#	fi
#	if [ "$currentsnploc" -eq 0 ] #This checks if we are dealing with the first record
#	then 
		currentsnploc=$(echo "$line" | awk '{print $2}')
		echo "Current SNP Location :$currentsnploc"

#	fi
	
	if [ "$currentsnploc" -eq "$snppos" ] 
	then
		echo "the last snp loc is the same as the new one! ($snppos)" 
		if [ "$A" == "A" ] || [ $(echo "$line" | awk '{print $3}') == "A" ]
		then 
			A="A"
		fi
		if [ "$G" == "G" ] || [ $(echo "$line" | awk '{print $4}') == "G" ]
		then 
			G="G"
		fi
		if [ "$C" == "C" ] || [ $(echo "$line" | awk '{print $5}') == "C" ]
		then 
			C="C"
		fi
		if [ "$T" == "T" ] || [ $(echo "$line" | awk '{print $6}') == "T" ]
		then 
			T="T"
	fi
	else
	echo "prev snp loc is different, writing last snp to output."
	echo -e "${chr}\t${snppos}\t${A}\t${G}\t${C}\t${T}" >> $OutputFileName
	chr=$(echo "$line" | awk '{print $1}')
	snppos=$(echo "$line" | awk '{print $2}')
	A=$(echo "$line" | awk '{print $3}')
	G=$(echo "$line" | awk '{print $4}')
	C=$(echo "$line" | awk '{print $5}')
	T=$(echo "$line" | awk '{print $6}')
	currentsnploc=$(echo "$line" | awk '{print $2}')	
	fi 		
done < $1