#!/bin/bash

rm -rf outp.txt
rm -rf p4.txt
rm -rf outpp.txt
rm -rf outfnames.txt
rm -rf temp
rm -rf tempdiff
#cat outp.txt

if [ $# -lt 8 ]
then 
	echo "Usage replace2 -z1 <size> -s1 <str1> -s2 <str2> -o <filename>"
	exit
fi

if [ $1 = -help ]
then
        echo "Usage replace2 -z1 <size> -s1 <str1> -s2 <str2> -o <filename>"
        exit
fi
		


if [ $1 = -z1 ]
then
	export size=$2
	else if [ $3 = -z1 ]
	then
		export size=$4
		else if [ $5 = -z1 ]
	        then 
			export size=$6
                        else if [ $7 = -z1 ]
	                then 
				export size=$8
                        fi
	        fi
       fi
fi



if [ $1 = -s1 ]
then
	export str1=$2
else if [ $3 = -s1 ]
	then
		export str1=$4
	else if [ $5 = -s1 ]
	then 
		export str1=$6
	        else if [ $7 = -s1 ]
	        then 
			export str1=$8
                fi

        fi
    fi
fi

if [ $1 = -s2 ]
then
 	export str2=$2
else if [ $3 = -s2 ]
	then	
	export str2=$4
	else if [ $5 = -s2 ]
	then 
		export str2=$6
	         else if [ $7 = -s2 ]
	        then 
			export str2=$8
                fi

         fi
    fi
fi


if [ $1 = -o ]
then
 	export outtmp=$2
else if [ $3 = -o ]
	then	
	export outtmp=$4
	else if [ $5 = -o ]
	then 
		export outtmp=$6
                 else if [ $7 = -o ]
	        then 
			export outtmp=$8
                fi

	fi

fi
fi


export cmd="find -type f -size +"$size"w -print"
for m in `$cmd`;do

#########################################################################################
#check if output file already exist
if [ -f $outtmp ]
then
echo "Output file already exists"
exit 2
fi
#skip if file is a directory
if [ -d $m ]
then
continue
#skip if file has no read permissions
elif [ ! -r $m ]
then
continue
#skip if file has no write permissions
elif [ ! -w $m ]
then
continue
fi

#################################################################################
if [ "$m" != "./replace1" -a "$m" != "./replace2" ]
then

grep $str1 $m > outpp.txt

x=$(wc -l outpp.txt | cut -b7)
if [ $x != 0 ]
then
cat outpp.txt >> outp.txt
fi
replace -s $str1 $str2 <$m >temp
diff $m temp > tempdiff
rm -rf $m
cp temp $m
y=$(wc -w tempdiff | cut -b7)
if [ $y != 0 ]
then
 echo $m >> outfnames.txt
fi
fi 
done; 

echo "List of modified files :"
if [ -f "outfnames.txt" ]
then
cat outfnames.txt
fi


# Print list of word frequencies
awk 'BEGIN{rows=1;} \
{ str=$0; \
c = gsub(/'"$str1"'/,"'$str2'",str); \
astr[NR]=str; \
acount[NR]=c; \
rows++; } \
END{for(i=1;i<rows;i++) \
{ \
 for(j=i+1;j<=rows;j++) \
 { \
 if(acount[i]<acount[j]) \
  { \
     temp = acount[i];acount[i]=acount[j];acount[j]=temp; \
     temps=astr[i]; astr[i]=astr[j]; astr[j]=temps; \
  } \
 } \
} \
for(i=1;i<=rows;i++) \
   printf "\n %s", astr[i]; }'  outp.txt > $outtmp

       
