#!/bin/bash

file=topology2.dat
MAX=100
n1=$((MAX+1))
n2=$((MAX+1))
oldn=0

rm -f $file


for i in `seq 1 $MAX`; do

	#This is so ugly
	nlines=`cat $file 2> /dev/null | wc -l`
	if [ $nlines -lt $oldn ]; then echo "ERROR ! : Restart the application please :)"; exit 1; fi
	oldn=$nlines

	while [ $n1 -gt $MAX ]; do
		n1=$((RANDOM+1))
	done

	while [ $n2 -gt $MAX ] || [ $n1 -eq $n2 ]; do
		n2=$((RANDOM+1))
	done

	#Find on which line is n1 (if no present -> line 0)
	number_lineN1=`cat $file 2> /dev/null | grep -n "^$n1 " | grep ":$n1" | cut -f1 -d":"`
	if [ "$number_lineN1" == "" ]; then
		number_lineN1=0;
	fi


	#If n1 is present in the file
	if [ $number_lineN1 -gt 0 ]; then

		#We copy the whole line corresponding to n1
		lineN1=`head -n $number_lineN1 $file 2> /dev/null | tail -n 1`

		#We write down the rest of the file
		cat $file 2> /dev/null  | grep -v "^$lineN1\$" > $file

		#And we write old + new info
		echo "$lineN1 $n2" >> $file


	#If not present in the file
	else
		echo "$n1 $n2" >> $file
	fi


	#Find on which line is n1 (if no present -> line 0)
	number_lineN2=`cat $file 2> /dev/null | grep -n "^$n2 " | grep ":$n2" | cut -f1 -d":"`
	if [ "$number_lineN2" == "" ]; then
		number_lineN2=0;
	fi


	#If n1 is present in the file
	if [ $number_lineN2 -gt 0 ]; then

		#We copy the whole line corresponding to n1
		lineN2=`head -n $number_lineN2 $file 2> /dev/null | tail -n 1`

		#We write down the rest of the file
		cat $file 2> /dev/null  | grep -v "^$lineN2\$" > $file

		#And we write old + new info
		echo "$lineN2 $n1" >> $file


	#If not present in the file
	else
		echo "$n2 $n1" >> $file
	fi

	n1=$((MAX+1))
	n2=$((MAX+1))

done

exit 1

