#!/bin/bash

my_func(){

	ind1=$(($1*2-1))
	ind2=$(($1*2))

	aln1=$(echo $4 | awk -v var="$ind1" '{print $var}')
	aln2=$(echo $4 | awk -v var="$ind2" '{print $var}')
	oName=$(echo $5 | awk -v var="$1" '{print $var}')

	echo "Merging $aln1.aln and $aln2.aln into $oName.aln"

	l1=$(grep -c ">" $aln1.aln)
	l2=$(grep -c ">" $aln2.aln)

	if [ $l1 -eq "1" ] && [ $l2 -eq "1" ] 
	then
		cat $aln1.aln $aln2.aln > temp.$6.$1.fas
		mafft --localpair --preservecase --thread $2 --maxiterate $3 temp.$6.$1.fas > $oName.aln
	elif [ $l1 -eq "1" ] 
	then
		mafft --preservecase --thread $2 --maxiterate $3 --addfragments $aln1.aln $aln2.aln > $oName.aln
	elif [ $l2 -eq "1" ] 
	then
		mafft --preservecase --thread $2 --maxiterate $3 --addfragments $aln2.aln $aln1.aln > $oName.aln
	else
		cat $aln1.aln $aln2.aln > input.$6.$1.fas
		str1=""
		count=1
		gap=" "

		for i in $(seq 1 1 $l1)
		do
			str1=$str1$count$gap
			count=$(($count+1))
		done

		echo $str1 > msaTable.$6.$1
		str2=""
		for i in $(seq 1 1 $l2)
		do
			str2=$str2$count$gap
			count=$(($count+1))
		done

		echo $str2 >> msaTable.$6.$1
		mafft --preservecase --thread $2 --maxiterate $3 --merge msaTable.$6.$1 input.$6.$1.fas > $oName.aln

	fi

}

export -f my_func

parallel -j 1 my_func ::: $(seq 1 1 1) ::: 1 ::: 1 ::: "NODE_1 NODE_2" ::: "NODE_0" ::: "merge"
