# get names of pdbs from list 
# IFS=$'\n' read -d '' -r -a pdbs < list.txt
homeFolder="./public/uploads"

IFS=$'\n' read -d '' -r -a pdbs < ${homeFolder}/list.txt

# printf "line 1: %s\n" "${pdbs[0]}"
# printf "line 2: %s\n" "${pdbs[1]}"

numOfPdbs=`echo "${#pdbs[@]}"`

# init array of capital letters for chain recognition
a=({A..Z} _)

if [[ $numOfPdbs -eq 1 ]]; then

	first="${pdbs[0]}"
	name=${first%.*}
	
	if [ -d "${homeFolder}/$name" ]; then
	  rm -rf ${homeFolder}/$name
	fi	
	mkdir ${homeFolder}/$name

	mv ${homeFolder}/$first ${homeFolder}/${name}/${first}

	exit 0
fi

if [[ $numOfPdbs -eq 2 ]]; then
	# 2 proteins for DeepAlign
	# printf "calculating DeepAlign on ${pdbs[0]} and ${pdbs[1]} \n"

	first="${pdbs[0]}"
	firstShort=${first%.*}
	second="${pdbs[1]}"
	secondShort=${second%.*}

	# new name for folder and deepalign output
	both=${firstShort}${secondShort}

	if [ -d "${homeFolder}/$both" ]; then
	  rm -rf ${homeFolder}/$both
	fi	
	mkdir ${homeFolder}/$both
	
	${homeFolder}/DeepAlign ${homeFolder}/$first ${homeFolder}/$second -o ${homeFolder}/${both}/${both} -P 0 || exit 1

	pdb=${homeFolder}/${both}/${first}
	touch $pdb
	awk '/^HELIX/' ${homeFolder}/$first > $pdb
	awk '/^SHEET/' ${homeFolder}/$first >> $pdb
	# copy all lines until first TER occurence
	sed '/TER/q' ${homeFolder}/${both}/${both}.pdb >> $pdb

	pdb=${homeFolder}/${both}/${second}
	touch $pdb
	awk '/^HELIX/' ${homeFolder}/$second > $pdb
	awk '/^SHEET/' ${homeFolder}/$second >> $pdb
	touch temp.pdb
	# copy all lines after first TER occurence
	sed -e '1,/TER/ d' ${homeFolder}/${both}/${both}.pdb > temp.pdb
	sed 's/./A/22' temp.pdb >> $pdb

	rm -rf temp.pdb

else

	# printf "calculating 3DCOMB \n"

	name=""
	for (( i = 0; i < numOfPdbs; i++ )); do
		temp=${pdbs[i]}
		name=$name${temp%.*}
	done
	
	if [ -d "${homeFolder}/$name" ]; then
	  rm -rf ${homeFolder}/$name
	fi	
	mkdir ${homeFolder}/$name

	touch ${homeFolder}/newList.txt
	sed "s|^|${homeFolder}/|" ${homeFolder}/list.txt > ${homeFolder}/newList.txt

	${homeFolder}/3DCOMB -i ${homeFolder}/newList.txt -o ${homeFolder}/${name}/${name} || exit 1

	rm newList.txt

	for (( i = 0; i < numOfPdbs; i++ )); do
		pdb=${homeFolder}/${name}/${pdbs[i]}
		touch ${homeFolder}/$pdb
		awk '/^HELIX/' ${homeFolder}/${pdbs[i]} > $pdb
		awk '/^SHEET/' ${homeFolder}/${pdbs[i]} >> $pdb
		touch temp.pdb
		grep -E '^.{20} '${a[$i]}'' ${homeFolder}/${name}/${name}.pdb > temp.pdb
		sed 's/./A/22' temp.pdb >> $pdb
		rm temp.pdb
	done	


fi