#!/bin/bash
	function append_beginning ()
        	        {       while read line1; do
					mv "$line1" "$1""$line1"
					echo "$line1" renamed to "$1$line1"
                        	done
	                }

	function append_end ()
			{	while read line1; do
					mv "$line1" "$line1""$1"
					echo "$line1" renamed to "$line1$1"
				done
			}

	function remove_beginning ()
			{	while read line1; do
					newname=${line1/#"$1"/}
					mv "$line1" "$newname"
					echo "$line1" renamed to "$newname"
				done
			}

	function remove_end ()
			{	while read line1; do
					newname=${line1/%$1/}
					mv "$line1" "$newname"
					echo $line1 renamed to $newname
				done
			}

	function abort ()
			{		
					echo "Rename aborted."
					echo
					exit 0
			}

if [ -z "$1" ] || [ -z "$2" ] || [ "$1" != "ab" ] && [ "$1" != "ae" ] && [ "$1" != "rb" ] && [ "$1" != "re" ]; then
	echo
	echo "Modify all filenames in the working directory"
	echo "Usage: modfn option "
	echo
	echo "Options:"
	echo "     ab - append string to beginning of all filenames"
	echo "     ae - append string to end of all filenames"
	echo "     rb - remove string from beginning of all filenames"
	echo "     re - remove string from end of all filenames"
	echo
	exit 1
fi

if [ "$1" == "ab" ]; then	
        echo -ne "Ready to append "$2" to the beginning of all files, are you sure? : "
	read line1
	if [ "$line1" == "y" ]; then
		ls -1 | append_beginning "$2"
		exit 0
	else
	abort
fi
fi

if [ "$1" == "ae" ]; then
        echo -ne "Ready to append "$2" to the end of all files, are you sure? : "
	read line1
	if [ "$line1" == "y" ]; then
		ls -1 | append_end "$2"
		exit 0
	else
	abort
fi
fi

if [ "$1" == "rb" ]; then
	echo -ne "Ready to remove "$2" from the beginning of all files, are you sure? : "
	read line1
	if [ "$line1" == "y" ]; then
		ls -1 | remove_beginning "$2"
		exit 0
	else
	abort
fi
fi

if [ "$1" == "re" ]; then
	echo -ne "Ready to remove "$2" from the end of all files, are you sure? : "
	read line1
	if [ "$line1" == "y" ]; then
		ls -1 | remove_end "$2"
		exit 0
	else
	abort
fi
fi