🖥️function

➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the function command with important options and switches using examples.

▁ ▂ ▃ ▄ ꧁ 🔴☠ COMMANDLINE-KUNGFU WITH CHEATSHEETS ☠🔴꧂▅ ▃ ▂ ▁

#                ███████╗██╗   ██╗███╗   ██╗ ██████╗████████╗██╗ ██████╗ ███╗   ██╗
#                ██╔════╝██║   ██║████╗  ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗  ██║
#                █████╗  ██║   ██║██╔██╗ ██║██║        ██║   ██║██║   ██║██╔██╗ ██║
#                ██╔══╝  ██║   ██║██║╚██╗██║██║        ██║   ██║██║   ██║██║╚██╗██║
#                ██║     ╚██████╔╝██║ ╚████║╚██████╗   ██║   ██║╚██████╔╝██║ ╚████║
#                ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝   ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝
                                                                                  
                                                                                
# Define a bash function to interactively pick a subdirectory to cd into

############################################################################################################################################
###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS 
############################################################################################################################################
#if [ -f ~/.bash_functions ]; then
#    . ~/.bash_functions
#fi

# Benötigte Programme:
#===============================
# sudo apt-get install geoip-bin html2text mercurial madplay festival weather-util weather-util-data gawk w3m python-pip youtube-dl gnuplot ispell dict moreutils tree txt2html zenity lsdvd vobcopy python-webkit geoip-bin mpg321

# Benötigt Python3 und ist veraltet
# sudo pip install mps-youtube

# für mencoder werden deb-multimedia sources.list benötigt
# mencoder

# veraltet
# python-gtkmozembed xulrunner-2.0 remastersys python-pisa

###### Download all images from a 4chan thread
function 4chanimages()
{
		curl -s http://boards.4chan.org/wg/|sed -r 's/.*href="([^"]*).*/\1\n/g'|grep images|xargs wget
}

###### Urlencoding with one pure BASH builtin
function URLEncode { local dataLength="${#1}"; local index; for ((index = 0;index < dataLength;index++)); do local char="${1:index:1}"; case $char in [a-zA-Z0-9.~_-]) printf "$char"; ;; *) printf "%%%02X" "'$char"; ;; esac; done; }
# URLEncode https://www.commandlinefu.com/commands/by/emphazer
# opposite of https://www.commandlinefu.com/commands/view/10014/urldecoding-with-one-pure-bash-builtin 
# This is sample output 
https%3A%2F%2Fwww.commandlinefu.com%2Fcommands%2Fby%2Femphazer

function csv2json() { for file in $@; do python -c "import csv,json,fileinput; print(json.dumps(list(csv.reader(fileinput.input()))))" "$file" 1> "${file%%csv}json"; done; }
# Convert CSV to JSON - Python3 and Bash function Is written for python3 and is very easy to use. csv2json *csv will convert all files ending in csv to json. eg csv2json file.csv will output a file to file.json

function dockpage() { lynx -width=180 --dump https://docs.docker.com/v1.11/engine/reference/commandline/$1/ | sed -n '/^Usage/,/On this page/{/On this page/b;p}'; }
# Shows the online version of docker's man related a command. Docker is local man pages are (often) half of what you have online, so I wanted that as local man.

function curlh() { x="$(curl -Is -w '%{http_code}' "$@")"; if [[ "$(tail -n 1 <<< "$x")" == [45]* ]]; then curl -is "$@" | awk '{ if (!NF) { exit }; print }'; else head -n -1 <<< "$x"; fi; }
# Get only headers from a website with curl even if it does not support HEAD. Some sites running on basic web servers do not support the HEAD request, so using "curl -I" on them does not work. This will automatically try "curl -I" at first and if that fails with a 4xx or 5xx status code, it falls back to "curl -i" and prints only the headers from that.

# setproxy on cmd
function setproxy() {
	    	export {http,https,ftp}_proxy='http://PROXYUSER:[email protected]:8080'
	        }

function unsetproxy() {
		unset {http,https,ftp}_proxy
		}

# Check what a color code will look like by making a function to display them. I'm having one side of this conversation right now without the benefit of the other side.
function showcolor(){ 
	display -size 400x400 "xc:$1" ; 
}; showcolor '#6495ED' 

# Generate Random Text based on Length
function genRandomText() { 
	local n=$1; while [ $((n--)) -gt 0 ]; do printf "\x$(printf %x $((RANDOM % 26 + 65)))" ; done ; echo ; 
}

# function to compute what percentage of X is Y? Where percent/100 = X/Y => percent=100*X/Y
# This function make it easy to compute X/Y as a percentage. The name "wpoxiy" is an acronym of "what percentage of X is Y" Show Sample Output
# 
# $ wpoxiy 65788574 1269501
# 1.92%
# 
# $ wpoxiy 30 10
# 33.33%
# What percentage of X is Y? Where percent/100 = X/Y => percent=100*X/Y 
	# Example: wpoxiy 10 5 # 50.00% 
	# Example: wpoxiy 30 10 # 33.33% 
function wpoxiy () { 
	echo $(bc <<< "scale=2; y=${1}; x=${2}; percent=x*100/y; percent")"%"; 
}

# Generate Random Text based on Length -> Random text of length "$1" without the useless cat command.
function genRandomText() { 
	tr -cd '[:alpha:]' < /dev/urandom | head -c "$1"; 
}

# small CPU benchmark with PI, bc and time. -> 4 cores with 2500 pi digits CPUBENCH 4 2500 . every core will use 100% cpu and you can see how fast they calculate it. if you do 50000 digitits and more it can take hours or days Show Sample Output
function CPUBENCH() { 
	local CPU="${1:-1}"; local SCALE="${2:-5000}"; { for LOOP in `seq 1 $CPU`; do { time echo "scale=${SCALE}; 4*a(1)" | bc -l -q | grep -v ^"[0-9]" & } ; done }; echo "Cores: $CPU"; echo "Digit: $SCALE" ;
}

# Show all files sorted by date -> a quick function for searching changed files. just copy it in the bash Show Sample Output
function FINDDATE() { 
	LOCATION="${1:-.}"; find ${LOCATION} -type f -print0 | xargs -0 stat -c "%y %n" | sort | sed 's/.\([0-9]\)\{9,\} +0[1-2]00/\t/' | sed 's/ /\t/g' 
}

# Function to draw a regular polygon using ImageMagick commands. Ex: poly 8 280 Credit to Digital Trauma on StackEx. CodeGolf
function poly(){ 
	c=`bc -l <<<"for(;i++<$1;){t=6.28*i/$1;print s(t)*$2+$2,\",\";c(t)*$2+$2}"`;convert -size $[$2*2]x$[$2*2] xc: -draw "polygon $c" png:-|display; 
} 

# Abort the whole script from a function
trap "exit 1" TERM
export TOP_PID=$$
function fatal(){
        echo "Goodbye"
        kill -s TERM $TOP_PID
}
echo "Function call will abort"
echo $(func)
echo "This will never be printed"

# Find inside specific file type function
function findin() { 
	find . -type f -name "*.$1" | xargs ack $2 
}

###### Add a function you've defined to .bashrc
function addfunction() { declare -f $1 >> ~/.bashrc ; }

# You can put this in your shell rc to *help* protect yourself *specifically* from :(){ :|:& };: #bash
:(){ true; };readonly -f :

# 
sec2dhms() 
{  
          declare -i SS="$1"  D=$(( SS / 86400 ))   H=$(( SS % 86400 / 3600 ))  M=$(( SS % 3600 / 60 ))   S=$(( SS % 60 ))   [ "$D" -gt 0 ] && echo -n "${D}:"  [ "$H" -gt 0 ] && printf "%02g:" "$H"  printf "%02g:%02g\n" "$M" "$S" 
}

## Convert seconds to [DD:][HH:]MM:SS
# Converts any number of seconds into days, hours, minutes and seconds.
sec2dhms() 
{
	declare -i SS="$1"
	D=$(( SS / 86400 ))
	H=$(( SS % 86400 / 3600 ))
	M=$(( SS % 3600 / 60 ))
	S=$(( SS % 60 ))
	[ "$D" -gt 0 ] && echo -n "${D}:"
	[ "$H" -gt 0 ] && printf "%02g:" "$H"
	printf "%02g:%02g\n" "$M" "$S"
}

shebang () { printf '%s\n' 0a '#!'"$1" . w | ed -s "$2" ; }
# Retrofit a shebang to an existing script
# Function to add a shebang to an existing script, handy if you forgot to add it in the first place.

videospeed() { vname="$1"; speedc="$2"; vs=$(python3 -c "print(1/$speedc)"); aspeed=$(python3 -c "print(1*$speedc)"); ffmpeg -i "$vname" -filter:a "atempo=$aspeed" -filter:v "setpts=$vs*PTS" "${3:-converted_$1}"; }
# Speed up or slow down video (and audio)
# Usage:
videospeed video_filename speedchange newfilename
videospeed foo.mp4 0.5 foo_slow.mp4
# Range of 0.5 (50%) - 2.0 (200%) is valid.

lc() { od="$1"; nd="$2"; of=$3; nf=$4; cp -rl "$od" "$nd"; parallel -0 "ffmpeg -i {1} -loglevel error -q:a 6 {1.}.{2} && { rm {1}; echo {1.}.{2}; }" :::: <(find "$nd" -type f -iname \*$of -print0) ::: "$nf"; }
# Convert entire audio library in parallel
# Uses parallel processing
# Reiteration of my earlier command -> https://www.commandlinefu.com/commands/view/15246/convert-entire-music-library
# Usage
lc Old_Directory New_DIrectory Old_Format New_Format
lc ~/Music ~/Music_ogg mp3 ogg

function cdb() 
{ 
          select dir in $(find -type d -name "$1" -not -path '*/\.*' -prune)
          do cd "${dir}" && break
               done  
}

# Extract Function Linux Bash
# Extract archives - use: extract <file>
# Based on http://dotfiles.org/~pseup/.bashrc
function extract() {
    if [ -f "$1" ] ; then
	local filename=$(basename "$1")
	local foldername="${filename%%.*}"
	local fullpath=`perl -e 'use Cwd "abs_path";print abs_path(shift)' "$1"`
	local didfolderexist=false
	if [ -d "$foldername" ]; then
	    didfolderexist=true
	    read -p "$foldername already exists, do you want to overwrite it? (y/n) " -n 1
	    echo
	    if [[ $REPLY =~ ^[Nn]$ ]]; then
		return
	    fi
	fi
	mkdir -p "$foldername" && cd "$foldername"
	case $1 in
	    *.tar.bz2) tar xjf "$fullpath" ;;
	    *.tar.gz) tar xzf "$fullpath" ;;
	    *.tar.xz) tar Jxvf "$fullpath" ;;
	    *.tar.Z) tar xzf "$fullpath" ;;
	    *.tar) tar xf "$fullpath" ;;
	    *.taz) tar xzf "$fullpath" ;;
	    *.tb2) tar xjf "$fullpath" ;;
	    *.tbz) tar xjf "$fullpath" ;;
	    *.tbz2) tar xjf "$fullpath" ;;
	    *.tgz) tar xzf "$fullpath" ;;
	    *.txz) tar Jxvf "$fullpath" ;;
	    *.zip) unzip "$fullpath" ;;
	    *) echo "'$1' cannot be extracted via extract()" && cd .. && ! $didfolderexist && rm -r "$foldername" ;;
	esac
    else
	echo "'$1' is not a valid file"
    fi
}

#------------------------------------------------------------------------------#

function cdb() { select dir in $(find -type d -name "$1" -not -path '*/\.*' -prune); do cd "${dir}" && break; done }
# Define a bash function to interactively pick a subdirectory to cd into

# Bash autocomplete ssh hosts
gistfile1.txt
_complete_ssh_hosts ()
{
        COMPREPLY=()
        cur="${COMP_WORDS[COMP_CWORD]}"
        comp_ssh_hosts=`cat ~/.ssh/known_hosts | \
                        cut -f 1 -d ' ' | \
                        sed -e s/,.*//g | \
                        grep -v ^# | \
                        uniq | \
                        grep -v "\[" ;
                cat ~/.ssh/config | \
                        grep "^host " | \
                        awk '{print $2}'
                `
        COMPREPLY=( $(compgen -W "${comp_ssh_hosts}" -- $cur))
        return 0
}
complete -F _complete_ssh_hosts ssh

###### to export private OpenPGP keys to a file for safe keeping and potential restoration - using 'mykeys', put the appropriate GPG key after you type this function
function exportmykeys_private()
{
		gpg --list-secret-keys
		echo -n "Please enter the appropriate private key...
		Look for the line that starts something like "sec 1024D/".
		The part after the 1024D is the key_id.
		...like this: '2942FE31'...

		"
		read MYKEYPRIV
		gpg -ao Private_Keys-private.key --export-secret-keys "$MYKEYPRIV"
		echo -n "All done."
}

###### to export public OpenPGP keys to a file for safe keeping and potential restoration- using 'mykeys', put the appropriate GPG key after you type this function
function exportmykeys_public()
{
		gpg --list-keys
		echo -n "Please enter the appropriate public key...
		Look for line that starts something like "pub 1024D/".
		The part after the 1024D is the public key_id.
		...like this: '2942FE31'...

		"
		read MYKEYPUB
		gpg -ao Public_Keys-public.key --export "$MYKEYPUB"
		echo -n "All done."
}

###### to restore your public and private OpenPGP keys from Public_Key-public.key and Private_Keys-private.key files:
function restoremykeys()
{
		echo -n "Please enter the full path to Public keys (spaces are fine)...

		Example: '/home/(your username)/Public_Key-public.key'...

		"
		read MYKEYS_PUBLIC_LOCATION
		gpg --import "$MYKEYS_PUBLIC_LOCATION"
		echo -n "Please enter the full path to Private keys (spaces are fine)...

		Example: '/home/(your username)/Private_Keys-private.key'...

		"
		read MYKEYS_PRIVATE_LOCATION
		gpg --import "$MYKEYS_PRIVATE_LOCATION"
		echo -n "All done."
}

###### to setup new public and private OpenPGP keys
function setupmykeys()
{
		# Generate new key
		gpg --gen-key
		# Publish new key to Ubuntu keyserver
		gpg --keyserver hkp://keyserver.ubuntu.com --send-keys
		# Import an OpenPGP key
		gpg --fingerprint
		# Verify new key
		read -sn 1 -p "Before you continue, you must enter the fingerprint
		in the appropriate place in your Launchpad PPA on their website...

		Once you have successfully inputed it, wait for your email before
		you press any key to continue...

		"
		gedit $HOME/file.txt
		read -sn 1 -p "Once you have received your email from Launchpad to
		verify your new key, copy and paste the email message received upon
		import of OpenPGP key from "-----BEGIN PGP MESSAGE-----" till
		"-----END PGP MESSAGE-----" to the 'file.txt' in your home folder
		that was just opened for you

		Once you have successfully copied and pasted it, save it and
		press any key to continue...

		"
		gpg -d $HOME/file.txt
		echo -n "All done."
}

# Text alignment
#------------------------------------------////

###### center text in console with simple pipe like
function align_center() { l="$(cat -)"; s=$(echo -e "$l"| wc -L); echo "$l" | while read l;do j=$(((s-${#l})/2));echo "$(while ((--j>0)); do printf " ";done;)$l";done;} #; ls --color=none / | center

###### right-align text in console using pipe like ( command | right )
function align_right() { l="$(cat -)"; [ -n "$1" ] && s=$1 || s=$(echo -e "$l"| wc -L); echo "$l" | while read l;do j=$(((s-${#l})));echo "$(while ((j-->0)); do printf " ";done;)$l";done;} #; ls --color=none / | right 150

# Network information and IP address stuff
#------------------------------------------////

###### get all IPs via ifconfig
function allips()
{
		sudo ifconfig | awk '/inet / {sub(/addr:/, "", $2); print $2}'
}

###### clear iptables rules safely
function clearIptables()
{
		iptables -P INPUT ACCEPT; iptables -P FORWARD ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F; iptables -X; iptables -L
}

###### online check
function connected() { ping -c1 -w2 google.com > /dev/null 2>&1; }

function connected_() { rm -f /tmp/connect; http_proxy='http://a.b.c.d:8080' wget -q -O /tmp/connect http://www.google.com; if [[ -s /tmp/connect ]]; then return 0; else return 1; fi; }

###### check if a remote port is up using dnstools.com - (i.e. from behind a firewall/proxy)
function cpo() { [[ $# -lt 2 ]] && echo 'need IP and port' && return 2; [[ `wget -q "http://dnstools.com/?count=3&checkp=on&portNum=$2&target=$1&submit=Go\!" -O - |grep -ic "Connected successfully to port $2"` -gt 0 ]] && echo OPEN || echo CLOSED; }

###### find an unused unprivileged TCP port
function findtcp()
{
		(netstat  -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq 32768 61000) | sort -n | uniq -u | head -n 1
}

###### geoip lookup (need geoip database: sudo apt-get install geoip-bin)
function geoip() {
		sudo geoiplookup $1
}

###### geoip information - requires 'html2text': sudo apt-get install html2text
function geoiplookup() { curl -A "Mozilla/5.0" -s "http://www.geody.com/geoip.php?ip=$1" | grep "^IP.*$1" | html2text; }

###### get IP address of a given interface - Example: getip lo - Example: getip eth0	# this is the default
function getip()		{ lynx -dump http://whatismyip.org/; }

###### display private IP
function ippriv()
{
    sudo ifconfig eth0|grep "inet adr"|awk '{print $2}'|awk -F ':' '{print $2}'
}

###### ifconfig connection check
function ips()
{
    if [ "$OS" = "Linux" ]; then
        for i in $( /sbin/ifconfig | grep ^e | awk '{print $1}' | sed 's/://' ); do echo -n "$i: ";  /sbin/ifconfig $i | perl -nle'/dr:(\S+)/ && print $1'; done
    elif [ "$OS" = "Darwin" ]; then
        for i in $( /sbin/ifconfig | grep ^e | awk '{print $1}' | sed 's/://' ); do echo -n "$i: ";  /sbin/ifconfig $i | perl -nle'/inet (\S+)/ && print $1'; done
    fi
}

###### geolocate a given IP address
function ip2loc() { wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICountry\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g'; }

###### ip2locall
function ip2locall() {
		# best if used through a proxy, as ip2loc's free usage only lets you search a maximum of 20 times per day
		# currently set on using a proxy through tor; if don't want that, just comment out the two 'export..' and 'unset...' lines
		export http_proxy='http://localhost:8118'
		export https_proxy='http://localhost:8118'
		echo ""
		echo "Country:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICountry\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Region (State, Province, Etc.):"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIRegion\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "City:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICity\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Latitude:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblILatitude\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Longitude:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblILongitude\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "ZIP Code:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIZIPCode\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Time Zone:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblITimeZone\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Net Speed:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblINetSpeed\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "ISP:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIISP\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Domain:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIDomain\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "IDD Code:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIIDDCode\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Area Code:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIAreaCode\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Weather Station:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIWeatherStation\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "MCC:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIMCC\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "MNC:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIMNC\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Mobile Brand:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIMobileBrand\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		unset http_proxy
		unset https_proxy
}

###### ip2locate
function ip2locate() {
		# best if used through a proxy, as ip2loc's free usage only lets you search a maximum of 20 times per day
		# currently set on using a proxy through tor; if don't want that, just comment out the two 'export..' and 'unset...' lines
		export http_proxy='http://localhost:8118'
		export https_proxy='http://localhost:8118'
		echo ""
		echo "Country:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICountry\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Region (State, Province, Etc.):"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblIRegion\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "City:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICity\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Latitude:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblILatitude\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		echo "Longitude:"
		wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblILongitude\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g';
		echo ""
		unset http_proxy
		unset https_proxy
}

###### find the IP addresses that are currently online in your network
function localIps()
{
		for i in {1..254}; do
		    x=`ping -c1 -w1 192.168.1.$i | grep "%" | cut -d"," -f3 | cut -d"%" -f1 | tr '\n' ' ' | sed 's/ //g'`
		    if [ "$x" == "0" ]; then
			echo "192.168.1.$i"
		    fi
		done
}

####### Meine momentane IP-Adresse
function myipis ()
{
	echo MyIP:
	elinks -dump http://checkip.dyndns.org:8245/ | grep "Current IP Address" | cut -d":" -f2 | cut -d" " -f2
}

###### myip - finds your current IP if your connected to the internet
function myip()
{
		lynx -dump -hiddenlinks=ignore -nolist http://checkip.dyndns.org:8245/ | awk '{ print $4 }' | sed '/^$/d; s/^[ ]*//g; s/[ ]*$//g'
}

###### netinfo - shows network information for your system
function netinfo()
{
		echo "--------------- Network Information ---------------"
		/sbin/ifconfig | awk /'inet addr/ {print $2}'
		/sbin/ifconfig | awk /'Bcast/ {print $3}'
		/sbin/ifconfig | awk /'inet addr/ {print $4}'
		/sbin/ifconfig | awk /'HWaddr/ {print $4,$5}'
		myip=`lynx -dump -hiddenlinks=ignore -nolist http://checkip.dyndns.org:8245/ | sed '/^$/d; s/^[ ]*//g; s/[ ]*$//g' `
		echo "${myip}"
		echo "---------------------------------------------------"
}

###### check whether or not a port on your box is open
function portcheck() { for i in $@;do curl -s "deluge-torrent.org/test-port.php?port=$i" | sed '/^$/d;s/<br><br>/ /g';done; }

###### scp sending
function scpsend()
{
		scp -P PORTNUMBERHERE "$@" [email protected]:/var/www/html/pathtodirectoryonremoteserver/;
}

###### show ip
function show_ip()
{
	    case $1 in
		*help | "" )
		    echo -e "\n${ewhite}Usage:\n"
		    echo -e "${eorange}show_ip${ewhite} |${egreen} <interface> ${eiceblue}[show ip-address for <interface>]\
		    \n${eorange}show_ip${ewhite} |${egreen} external${eiceblue} [show external ip address]\n"
		    tput sgr0
		;;
		*external )
		    wget -q -O - http://showip.spamt.net/
		;;
		* )
		    LANG=C /sbin/ifconfig $1 | grep 'inet addr:' | cut -d: -f2 | gawk '{ print $1}'
		;;
	    esac
}

###### display the ttl of a hostname in a human readable form (packet timetrans veraltet)
#function ttl()
#{
#		/usr/sbin/timetrans -count $(dig +noquestion +noadditional +noauthority $1 | grep "^$1" | awk '{print $2}')
#}

###### show Url information - Usage:	url-info "ur"
function url-info()
{
		doms=$@
		if [ $# -eq 0 ]; then
		echo -e "No domain given\nTry $0 domain.com domain2.org anyotherdomain.net"
		fi
		for i in $doms; do
		_ip=$(host $i|grep 'has address'|awk {'print $4'})
		if [ "$_ip" == "" ]; then
		echo -e "\nERROR: $i DNS error or not a valid domain\n"
		continue
		fi
		ip=`echo ${_ip[*]}|tr " " "|"`
		echo -e "\nInformation for domain: $i [ $ip ]\nQuerying individual IPs"
		 for j in ${_ip[*]}; do
		echo -e "\n$j results:"
		whois $j |egrep -w 'OrgName:|City:|Country:|OriginAS:|NetRange:'
		done
		done
}

###### cleanly list available wireless networks (using iwlist)
function wscan()
{
		iwlist wlan0 scan | sed -ne 's#^[[:space:]]*\(Quality=\|Encryption key:\|ESSID:\)#\1#p' -e 's#^[[:space:]]*\(Mode:.*\)$#\1\n#p'
}

####### Show all strings (ASCII & Unicode) in a file
function allStrings() { cat "$1" | tr -d "\0" | strings ; }

####### Find all videos under current directory using	 - MIME a.k.a not using extension
function allVideos() { find ./ -type f -print0 | xargs -0 file -iNf - | grep ": video/" | cut -d: -f1 ; }

# Miscellaneous Fun	
#------------------------------------------////

###### anagrams
function anagrams()
{
cat > "/tmp/anagrams.py" <<"End-of-message"
#!/usr/bin/python
infile = open ("/usr/share/dict/words", "r")
## "dict" is a reserved word
words_in = infile.readlines()
scrambled = raw_input("Enter the scrambled word: ")
scrambled = scrambled.lower()
scrambled_list = list(scrambled)
scrambled_list.sort()
for word in words_in:
    word_list = list(word.strip().lower())
    word_list.sort()
    ## you don't really have to compare lengths when using lists as the
    ## extra compare takes about as long as finding the first difference
    if word_list == scrambled_list:
        print word, scrambled
End-of-message
chmod +x "/tmp/anagrams.py"
"/tmp/anagrams.py" "$1"
rm "/tmp/anagrams.py"
}

function anagram_() { function s() { sed 's/[[:space:]]*//g;s/./\n\0/g'<<<"$@"|tr A-Z a-z|sort;};cmp -s <(s $1) <(s $2)||echo -n "not ";echo anagram; }

###### random Cyanide and Happiness comics from explosm.net
function cyanide() { display "$(wget -q http://explosm.net/comics/random/ -O - | grep -Po 'http://www.explosm.net/db/files/Comics/*/[^"]+(png|jpg|jpeg)')"; }

###### fake error string
function error()
{
		while true; do awk '{ print ; system("let R=$RANDOM%10; sleep $R") }' compiler.log; done
}

###### stupid funny face
function funny_face() {
		_ret=$?; if test $_ret -ne 0; then echo "0_0->ret=$_ret"; set ?=$_ret; unset _ret; else echo "^_^"; fi
}

###### pretend to be busy in office to enjoy a cup of coffee
function grepcolor()
{
		cat /dev/urandom | hexdump -C | grep --color=auto "ca fe"
}

###### a simple number guessing game
function hilow()
{
		biggest=1000                            # maximum number possible
		guess=0                                 # guessed by player
		guesses=0                               # number of guesses made
		number=$(( $$ % $biggest ))             # random number, 1 .. $biggest
		while [ $guess -ne $number ] ; do
		  echo -n "Guess? " ; read guess
		  if [ "$guess" -lt $number ] ; then
		    echo "... bigger!"
		  elif [ "$guess" -gt $number ] ; then
		    echo "... smaller!"
		  fi
		  guesses=$(( $guesses + 1 ))
		done
		echo "Right!! Guessed $number in $guesses guesses."
}

###### watch the National debt clock
function natdebt()
{
		watch -n 10 "wget -q http://www.brillig.com/debt_clock -O - | grep debtiv.gif | sed -e 's/.*ALT=\"//' -e 's/\".*//' -e 's/ //g'"
}

######
function oneliners()
{
		w3m -dump_source http://www.onelinerz.net/random-one-liners/1/ | awk ' /.*<div id=\"oneliner_[0-9].*/ {while (! /\/div/ ) { gsub("\n", ""); getline; }; gsub (/<[^>][^>]*>/, "", $0); print $0}'
}

###### random cowsay stuff
function random_cow()
{
		files=(/usr/share/cowsay/cows/*)
		printf "%s\n" "${files[RANDOM % ${#files}]}"
}

####### Temporarily add to PATH
function apath()
{
	    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
		   echo "Temporarily add to PATH"
		   echo "usage: apath [dir]"
	    else
		   PATH=$1:$PATH
	    fi
}

###### Function you want after you've overwritten some - important file using > instead of >> ^^
function append() {
        lastarg="${!#}"
        echo "${@:1:$(($#-1))}" >> "$lastarg"
}

####### Common commands piped through grep
function aptg()		# debian specific.
{
	    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
		   echo "search debian package list"
		   echo "usage: aptg [program/keyword]"
	    else
		   apt-cache search $1 | sort | less
	    fi
}

###### grep by paragraph instead of by line
function grepp() { [ $# -eq 1 ] && perl -00ne "print if /$1/i" || perl -00ne "print if /$1/i" < "$2";}

function hgg()
{
	    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
		   echo "search bash history"
		   echo "usage: mg [search pattern]"
	    else
		   history | grep -i $1 | grep -v hg
	    fi
}

function lsofg()
{
	    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
		   echo "grep lsof"
		   echo "usage: losfg [port/program/whatever]"
	    else
		   lsof | grep -i $1 | less
	    fi
}

function psg()
{
	    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
		   echo "grep running processes"
		   echo "usage: psg [process]"
	    else
		   ps aux | grep USER | grep -v grep
		   ps aux | grep -i $1 | grep -v grep
	    fi
}

####### To show Apt Log History
function apt-history() {
      case "$1" in
        install)
              cat /var/log/dpkg.log | grep 'install '
              ;;
        upgrade|remove)
              cat /var/log/dpkg.log | grep $1
              ;;
        rollback)
              cat /var/log/dpkg.log | grep upgrade | \
                  grep "$2" -A10000000 | \
                  grep "$3" -B10000000 | \
                  awk '{print $4"="$5}'
              ;;
        *)
              cat /var/log/dpkg.log
              ;;
      esac
}

####### Undo apt-get build-dep (remove build dependencies)					 #
function aptitude-remove-dep() { sudo aptitude markauto $(apt-cache showsrc "$1" | grep Build-Depends | perl -p -e 's/(?:[\[(].+?[\])]|Build-Depends:|,|\|)//g'); }

####### Arch-wiki-docs simple search
function archwikisearch() {
    # old version
    # cd /usr/share/doc/arch-wiki/html/
    # grep -i "$1" index.html | sed 's/.*HREF=.\(.*\.html\).*/\1/g' | xargs opera -newpage
    cd /usr/share/doc/arch-wiki/html/
    for i in $(grep -li $1 *)
    do
	STRING=`grep -m1 -o 'wgTitle = "[[:print:]]\+"' $i`
	LEN=${#STRING}
	let LEN=LEN-12
	STRING=${STRING:11:LEN}
	LOCATION="/usr/share/doc/arch-wiki/html/$i"
	echo -e " \E[33m$STRING   \E[37m$LOCATION"
    done
}

# Numerical conversions and numbers stuff
#------------------------------------------////

###### convert arabic to roman numerals
function arabic2roman() {

  echo $1 | sed -e 's/1...$/M&/;s/2...$/MM&/;s/3...$/MMM&/;s/4...$/MMMM&/
s/6..$/DC&/;s/7..$/DCC&/;s/8..$/DCCC&/;s/9..$/CM&/
s/1..$/C&/;s/2..$/CC&/;s/3..$/CCC&/;s/4..$/CD&/;s/5..$/D&/
s/6.$/LX&/;s/7.$/LXX&/;s/8.$/LXXX&/;s/9.$/XC&/
s/1.$/X&/;s/2.$/XX&/;s/3.$/XXX&/;s/4.$/XL&/;s/5.$/L&/
s/1$/I/;s/2$/II/;s/3$/III/;s/4$/IV/;s/5$/V/
s/6$/VI/;s/7$/VII/;s/8$/VIII/;s/9$/IX/
s/[0-9]//g'

}

###### convert ascii
function asc2all() {
    if [[ $1 ]]; then
	echo "ascii $1 = binary $(asc2bin $1)"
	echo "ascii $1 = octal $(asc2oct $1)"
	echo "ascii $1 = decimal $(asc2dec $1)"
	echo "ascii $1 = hexadecimal $(asc2hex $1)"
	echo "ascii $1 = base32 $(asc2b32 $1)"
	echo "ascii $1 = base64 $(asc2b64 $1)"
    fi
}

######
function asc2bin() {
    if [[ $1 ]]; then
	echo "obase=2 ; $(asc2dec $1)" | bc
    fi
}

######
function asc2b64() {
    if [[ $1 ]]; then
	echo "obase=64 ; $(asc2dec $1)" | bc
    fi
}

######
function asc2b32() {
    if [[ $1 ]]; then
	echo "obase=32 ; $(asc2dec $1)" | bc
    fi
}

######
function asc2dec() {
    if [[ $1 ]]; then
	printf '%d\n' "'$1'"
    fi
}

######
function asc2hex() {
    if [[ $1 ]]; then
	echo "obase=16 ; $(asc2dec $1)" | bc
    fi
}

######
function asc2oct() {
    if [[ $1 ]]; then
	echo "obase=8 ; $(asc2dec $1)" | bc
    fi
}

###### Averaging columns of numbers - Computes a columns average in a file. Input parameters = column number and optional pattern.
function avg() { awk "/$2/{sum += \$$1; lc += 1;} END {printf \"Average over %d lines: %f\n\", lc, sum/lc}"; }

###### convert binaries
function bin2all() {
    if [[ $1 ]]; then
	echo "binary $1 = octal $(bin2oct $1)"
	echo "binary $1 = decimal $(bin2dec $1)"
	echo "binary $1 = hexadecimal $(bin2hex $1)"
	echo "binary $1 = base32 $(bin2b32 $1)"
	echo "binary $1 = base64 $(bin2b64 $1)"
	echo "binary $1 = ascii $(bin2asc $1)"
    fi
}

######
function bin2asc() {
    if [[ $1 ]]; then
	echo -e "\0$(printf %o $((2#$1)))"
    fi
}

######
function bin2b64() {
    if [[ $1 ]]; then
	echo "obase=64 ; ibase=2 ; $1" | bc
    fi
}

######
function bin2b32() {
    if [[ $1 ]]; then
	echo "obase=32 ; ibase=2 ; $1 " | bc
    fi
}

######
function bin2dec() {
    if [[ $1 ]]; then
	echo $((2#$1))
    fi
}

######
function bin2hex() {
    if [[ $1 ]]; then
	echo "obase=16 ; ibase=2 ; $1" | bc
    fi
}

######
function bin2oct() {
    if [[ $1 ]]; then
	echo "obase=8 ; ibase=2 ; $1" | bc
    fi
}

###### simple calculator to 4 decimals
function calc() {
	echo "scale=4; $1" | bc
}

###### temperature conversion
function cel2fah() {

  if [[ $1 ]]; then
    echo "scale=2; $1 * 1.8  + 32" | bc
  fi

}

######
function cel2kel() {

  if [[ $1 ]]; then
    echo "scale=2; $1 + 237.15" | bc
  fi

}

######
function fah2cel() {

  if [[ $1 ]]; then
    echo "scale=2 ; ( $1 - 32  ) / 1.8" | bc
  fi

}

######
function fah2kel() {

  if [[ $1 ]]; then
    echo "scale=2; ( $1 + 459.67 ) / 1.8 " | bc
  fi

}

######
function kel2cel() {

  if [[ $1 ]]; then
    echo "scale=2; $1 - 273.15" | bc
  fi

}

######
function kel2fah() {

  if [[ $1 ]]; then
    echo "scale=2; $1 * 1.8 - 459,67" | bc
  fi

}

###### Output an ASCII character given its decimal equivalent
function chr() { printf \\$(($1/64*100+$1%64/8*10+$1%8)); }

###### the notorious "hailstone" or Collatz series.
function collatz()
{
	# get the integer "seed" from the command-line to generate the integer "result"
	# if NUMBER is even, divide by 2, or if odd, multiply by 3 and add 1
	# the theory is that every sequence eventually settles down to repeating "4,2,1..." cycles
	MAX_ITERATIONS=200
	# For large seed numbers (>32000), try increasing MAX_ITERATIONS.
	h=${1:-$$}                      #  Seed. #  Use $PID as seed, #+ if not specified as command-line arg.
	echo
	echo "C($h) --- $MAX_ITERATIONS Iterations"
	echo
	for ((i=1; i<=MAX_ITERATIONS; i++))
	do
	COLWIDTH=%7d
	printf $COLWIDTH $h
	  let "remainder = h % 2"
	  if [ "$remainder" -eq 0 ]   # Even?
	  then
	    let "h /= 2"              # Divide by 2.
	  else
	    let "h = h*3 + 1"         # Multiply by 3 and add 1.
	  fi
	COLUMNS=10                    # Output 10 values per line.
	let "line_break = i % $COLUMNS"
	if [ "$line_break" -eq 0 ]
	then
	  echo
	fi
	done
	echo
}

###### temperature conversion script that lets the user enter a temperature in any of Fahrenheit, Celsius or Kelvin and receive the equivalent temperature in the other two units as the output. - usage:	convertatemp F100 (if don't put F,C, or K, default is F)
function convertatemp(){
	if uname | grep 'SunOS'>/dev/null ; then
	  echo "Yep, SunOS, let\'s fix this baby"
	  PATH="/usr/xpg4/bin:$PATH"
	fi
if [ $# -eq 0 ] ; then
  cat << EOF >&2
Usage: $0 temperature[F|C|K]
where the suffix:
   F	indicates input is in Fahrenheit (default)
   C	indicates input is in Celsius
   K	indicates input is in Kelvin
EOF
fi
	unit="$(echo $1|sed -e 's/[-[[:digit:]]*//g' | tr '[:lower:]' '[:upper:]' )"
	temp="$(echo $1|sed -e 's/[^-[[:digit:]]*//g')"
	case ${unit:=F}
	in
	  F ) # Fahrenheit to Celsius formula:  Tc = (F -32 ) / 1.8
	  farn="$temp"
	  cels="$(echo "scale=2;($farn - 32) / 1.8" | bc)"
	  kelv="$(echo "scale=2;$cels + 273.15" | bc)"
	  ;;
	  C ) # Celsius to Fahrenheit formula: Tf = (9/5)*Tc+32
	  cels=$temp
	  kelv="$(echo "scale=2;$cels + 273.15" | bc)"
	  farn="$(echo "scale=2;((9/5) * $cels) + 32" | bc)"
	  ;;
	  K ) # Celsius = Kelvin + 273.15, then use Cels -> Fahr formula
	  kelv=$temp
	  cels="$(echo "scale=2; $kelv - 273.15" | bc)"
	  farn="$(echo "scale=2; ((9/5) * $cels) + 32" | bc)"
	esac
	echo "Fahrenheit = $farn"
	echo "Celsius    = $cels"
	echo "Kelvin     = $kelv"
}

###### convert hexadecimal numbers to decimals
function dec()		{ printf "%d\n" $1; }

###### convert decimals to hexadecimal numbers
function hex()		{ printf "0x%08x\n" $1; }

###### convert decimals
function dec2all() {
    if [[ $1 ]]; then
	echo "decimal $1 = binary $(dec2bin $1)"
	echo "decimal $1 = octal $(dec2oct $1)"
	echo "decimal $1 = hexadecimal $(dec2hex $1)"
	echo "decimal $1 = base32 $(dec2b32 $1)"
	echo "decimal $1 = base64 $(dec2b64 $1)"
	echo "deciaml $1 = ascii $(dec2asc $1)"
    fi
}

######
function dec2asc() {
    if [[ $1 ]]; then
	echo -e "\0$(printf %o 97)"
    fi
}

######
function dec2bin() {
    if [[ $1 ]]; then
	echo "obase=2 ; $1" | bc
    fi
}

######
function dec2b64() {
    if [[ $1 ]]; then
	echo "obase=64 ; $1" | bc
    fi
}

######
function dec2b32() {
    if [[ $1 ]]; then
	echo "obase=32 ; $1" | bc
    fi
}

######
function dec2hex() {
    if [[ $1 ]]; then
	echo "obase=16 ; $1" | bc
    fi
}

######
function dec2oct() {
    if [[ $1 ]]; then
	echo "obase=8 ; $1" | bc
    fi
}

###### number --- convert decimal integer to english words - total number Usage:	dec2text 1234 -> one thousand two hundred thirty-four
function dec2text()
{
	prog=`echo "$0" | sed -e 's/[^\/]*\///g'`
	garbage=`echo "$*" | sed -e 's/[0-9,.]//g'`
	if test ".$garbage" != "."; then
	  echo "$prog: Invalid character in argument." 1>&2
	fi
	case "$*" in
	# This doesn't always seem to work.
	#   *[!0-9,.]* ) echo "$prog: Invalid character in argument." 1>&2; ;;
	   *.* ) echo "$prog: fractions not supported (yet)." 1>&2; ;;
	   '' ) echo "Usage: $prog [decimal integer]" 1>&2; ;;
	esac
	result=
	eval set - "`echo ${1+\"$@\"} | sed -n -e '
	  s/[, ]//g
	  s/^00*/0/g
	  s/\(.\)\(.\)\(.\)$/\"\1 \2 \3\"/
	  :l
	  /[0-9][0-9][0-9]/{
		s/\([^\" ][^\" ]*\)\([^\" ]\)\([^\" ]\)\([^\" ]\)/\1\"\2 \3 \4\"/g
		t l
	  }
	  /^[0-9][0-9][0-9]/s/\([^\" ]\)\([^\" ]\)\([^\" ]\)/\"\1 \2 \3\"/
	  /^[0-9][0-9]/s/\([^\" ]\)\([^\" ]\)/\"\1 \2\"/
	  /^[0-9]/s/^\([^\" ][^\" ]*\)/\"\1\"/g;s/\"\"/\" \"/g
	  p'`"
	while test $# -ne 0 ; do
	  eval `set - $1;
		   d3='' d2='' d1=''
		   case $# in
			1 ) d1=$1 ;;
			2 ) d2=$1 d1=$2 ;;
			3 ) d3=$1 d2=$2 d1=$3 ;;
		   esac
		   echo "d3=\"$d3\" d2=\"$d2\" d1=\"$d1\""`
	  val1='' val2='' val3=''
	  case "$d3" in
	    1 ) val3=one   ;;     6 ) val3=six   ;;
	    2 ) val3=two   ;;     7 ) val3=seven ;;
	    3 ) val3=three ;;     8 ) val3=eight ;;
	    4 ) val3=four  ;;     9 ) val3=nine  ;;
	    5 ) val3=five  ;;
	  esac
	  case "$d2" in
	    1 ) val2=teen   ;;    6 ) val2=sixty   ;;
	    2 ) val2=twenty ;;    7 ) val2=seventy ;;
	    3 ) val2=thirty ;;    8 ) val2=eighty  ;;
	    4 ) val2=forty  ;;    9 ) val2=ninety  ;;
	    5 ) val2=fifty  ;;
	  esac
	  case "$val2" in
	    teen )
		 val2=
		 case "$d1" in
		   0 ) val1=ten      ;;     5 ) val1=fifteen   ;;
		   1 ) val1=eleven   ;;     6 ) val1=sixteen   ;;
		   2 ) val1=twelve   ;;     7 ) val1=seventeen ;;
		   3 ) val1=thirteen ;;     8 ) val1=eighteen  ;;
		   4 ) val1=fourteen ;;     9 ) val1=nineteen  ;;
		 esac
		;;
	    0 ) : ;;
	    * )
		 test ".$val2" != '.' -a ".$d1" != '.0' \
		  && val2="${val2}-"
		 case "$d1" in
		   0 ) val2="$val2 " ;;     5 ) val1=five  ;;
		   1 ) val1=one      ;;     6 ) val1=six   ;;
		   2 ) val1=two      ;;     7 ) val1=seven ;;
		   3 ) val1=three    ;;     8 ) val1=eight ;;
		   4 ) val1=four     ;;     9 ) val1=nine  ;;
		 esac
		;;
	  esac
	  test ".$val3" != '.' && result="$result$val3 hundred "
	  test ".$val2" != '.' && result="$result$val2"
	  test ".$val1" != '.' && result="$result$val1 "
	  if test ".$d1$d2$d3" != '.000' ; then
	    case $# in
		  0 | 1 ) ;;
		  2 ) result="${result}thousand "          ;;
		  3 ) result="${result}million "           ;;
		  4 ) result="${result}billion "           ;;
		  5 ) result="${result}trillion "          ;;
		  6 ) result="${result}quadrillion "       ;;
		  7 ) result="${result}quintillion "       ;;
		  8 ) result="${result}sextillion "        ;;
		  9 ) result="${result}septillion "        ;;
		 10 ) result="${result}octillion "         ;;
		 11 ) result="${result}nonillion "         ;;
		 12 ) result="${result}decillion "         ;;
		 13 ) result="${result}undecillion "       ;;
		 14 ) result="${result}duodecillion "      ;;
		 15 ) result="${result}tredecillion "      ;;
		 16 ) result="${result}quattuordecillion " ;;
		 17 ) result="${result}quindecillion "     ;;
		 18 ) result="${result}sexdecillion "      ;;
		 19 ) result="${result}septendecillion "   ;;
		 20 ) result="${result}octodecillion "     ;;
		 21 ) result="${result}novemdecillion "    ;;
		 22 ) result="${result}vigintillion "      ;;
		 * ) echo "Error: number too large (66 digits max)." 1>&2; ;;
	    esac
	  fi
	  shift
	done
	set $result > /dev/null
	case "$*" in
	  '') set zero ;;
	esac
	echo ${1+"$@"}
	# number ends here
}

####### individual numbers - Usage:	dec2text 1234 -> one two three four
function dec2text_()
{
	n=$1
	len=$(echo $n | wc -c)
	len=$(( $len - 1 ))
	for (( i=1; i<=$len; i++ ))
	do
	   # get one digit at a time
	    digit=$(echo $n | cut -c $i)
	   # use case control structure to find digit equivalent in words
	    case $digit in
		   0) echo -n "zero " ;;
		   1) echo -n "one " ;;
		   2) echo -n "two " ;;
		   3) echo -n "three " ;;
		   4) echo -n "four " ;;
		   5) echo -n "five " ;;
		   6) echo -n "six " ;;
		   7) echo -n "seven " ;;
		   8) echo -n "eight " ;;
		   9) echo -n "nine " ;;
	    esac
	done
	# just print new line
	echo ""
}

###### d2u
function d2u() {
    
    if [[ -e "$1" ]]; then
	sed -r 's/\r$//' -i "$1"
    fi
}

###### u2d
function u2d() {
    
    if [[ -e "$1" ]]; then
	sed -r 's/$/\r/' -i "$1"
    fi
}

###### factorial for integers
function factorial()
{
	echo "Enter an integer: "
	read n
	# Below we define the factorial function in bc syntax
	fact="define f (x) {
	i=x
	fact=1
	while (i > 1) {
		fact=fact*i
		i=i-1
	}
		return fact
	}"
	# Below we pass the function defined above, and call it with n as a parameter and pipe it to bc
	factorial=`echo "$fact;f($n)" | bc -l`
	echo "$n! = $factorial"
}

###### convert hexadecimal numbers - hex2all
function hex2all() {
    if [[ $1 ]]; then
	echo "hexadecimal $1 = binary $(hex2bin $1)"
	echo "hexadecimal $1 = octal $(hex2oct $1)"
	echo "hexadecimal $1 = decimal $(hex2dec $1)"
	echo "hexadecimal $1 = base32 $(hex2b32 $1)"
	echo "hexadecimal $1 = base64 $(hex2b64 $1)"
	echo "hexadecimal $1 = ascii $(hex2asc $1)"
    fi
}

###### convert hexadecimal numbers - hex2asc
function hex2asc() {
    if [[ $1 ]]; then
	echo -e "\0$(printf %o $((16#$1)))"
    fi
}

###### convert hexadecimal numbers - hex2bin
function hex2bin() {
    if [[ $1 ]]; then
	echo "obase=2 ; ibase=16 ; $1" | bc
    fi
}

###### convert hexadecimal numbers - hex2b64
function hex2b64() {
    if [[ $1 ]]; then
	echo "obase=64 ; ibase=16 ; $1" | bc
    fi
}

###### convert hexadecimal numbers - hex2b32
function hex2b32() {
    if [[ $1 ]]; then
	echo "obase=32 ; ibase=16 ; $1" | bc
    fi
}

###### convert hexadecimal numbers - hex2dec
function hex2dec() {
    if [[ $1 ]]; then
	 echo $((16#$1))
    fi
}

###### convert hexadecimal numbers - 
function hex2oct() {
    if [[ $1 ]]; then
	echo "obase=8 ; ibase=16 ; $1" | bc
    fi
}

###### length
function length()
{
    if [ $# -lt 1 ]; then
        echo "count # of chars in arugment"
        echo "usage: length [string]"
    else
        echo -n $@ | wc -c
    fi
}

###### finding logs for numbers
function math-log()
{
	echo "Enter value: "
	read x
	echo "Natural Log: ln($x) :"
	echo "l($x)" | bc -l
	echo "Ten Base Log: log($x) :"
	echo "l($x)/l(10)" | bc -l
}

###### magic square generator (odd-order squares only!)
function msquare()
{
	# Author: mendel cooper
	EVEN=2
	MAXSIZE=31   # 31 rows x 31 cols.
	E_usage=90   # Invocation error.
	dimension=
	declare -i square
	function usage_message()
	{
	  echo "Usage: $0 square-size"
	  echo "   ... where \"square-size\" is an ODD integer"
	  echo "       in the range 3 - 31."  #  Works for squares up to order 159
	}
	function calculate()       # Here's where the actual work gets done.
	{
	  local row col index dimadj j k cell_val=1
	  dimension=$1
	  let "dimadj = $dimension * 3"; let "dimadj /= 2"   # x 1.5, then truncate.
	  for ((j=0; j < dimension; j++))
	  do
	    for ((k=0; k < dimension; k++))
	    do  # Calculate indices, then convert to 1-dim. array index.
		   # Bash doesn't support multidimensional arrays. Pity.
		 let "col = $k - $j + $dimadj"; let "col %= $dimension"
		 let "row = $j * 2 - $k + $dimension"; let "row %= $dimension"
		 let "index = $row*($dimension) + $col"
		 square[$index]=cell_val; ((cell_val++))
	    done
	  done
	}     # Plain math, no visualization required.
	function print_square()               # Output square, one row at a time.
	{
	  local row col idx d1
	  let "d1 = $dimension - 1"   # Adjust for zero-indexed array.
	  for row in $(seq 0 $d1)
	  do
	    for col in $(seq 0 $d1)
	    do
		 let "idx = $row * $dimension + $col"
		 printf "%3d " "${square[idx]}"; echo -n "  "
	    done   # Displays up to 13-order neatly in 80-column term window.
	    echo   # Newline after each row.
	  done
	}
	if [[ -z "$1" ]] || [[ "$1" -gt $MAXSIZE ]]
	then
	  usage_message
	fi
	let "test_even = $1 % $EVEN"
	if [ $test_even -eq 0 ]
	then           # Can't handle even-order squares.
	  usage_message
	fi
	calculate $1
	print_square   # echo "${square[@]}"   # DEBUG
}

###### print multiplication tables
function multitables()
{
	for i in {1..9}; do for j in `seq 1 $i`; do echo -ne "${j}x${i}=$((j*i))\t"; done; echo; done
}

###### given a number, show it with comma separated values
function nicenumber()
{
	# expects DD and TD to be instantiated. instantiates nicenum
	# or, if a second arg is specified, the output is echoed to stdout
	function nice_number()
	{
		  # Note that we use the '.' as the decimal separator for parsing
		  # the INPUT value to this script. The output value is as specified
		  # by the user with the -d flag, if different from a '.'
		  integer=$(echo $1 | cut -d. -f1)		# left of the decimal
		  decimal=$(echo $1 | cut -d. -f2)		# right of the decimal
		  if [ $decimal != $1 ]; then
		    # there's a fractional part, let's include it.
		    result="${DD:="."}$decimal"
		  fi
		  thousands=$integer
		  while [ $thousands -gt 999 ]; do
		    remainder=$(($thousands % 1000))	# three least significant digits
		    while [ ${#remainder} -lt 3 ] ; do	# force leading zeroes as needed
			 remainder="0$remainder"
		    done
		    thousands=$(($thousands / 1000))	# to left of remainder, if any
		    result="${TD:=","}${remainder}${result}"	# builds right-to-left
		  done
		  nicenum="${thousands}${result}"
		  if [ ! -z $2 ] ; then
		    echo $nicenum
		  fi
	}
	DD="."	# decimal point delimiter, between integer & fractional value
	TD=","	# thousands delimiter, separates every three digits
	while getopts "d:t:" opt; do
	  case $opt in
	    d ) DD="$OPTARG"	;;
	    t ) TD="$OPTARG"	;;
	  esac
	done
	shift $(($OPTIND - 1))
	if [ $# -eq 0 ] ; then
  cat << "EOF" >&2
Usage: $(basename $0) [-d c] [-t c] numeric value
       -d specifies the decimal point delimiter (default '.')
       -t specifies the thousands delimiter (default ',')
EOF
fi
nice_number $1 1	# second arg forces this to 'echo' output
}

###### convert normal to unix
function normal2unix()
{
    echo "${@}" | awk '{print mktime($0)}';
}

###### convert unix to normal
function unix2normal()
{
    echo $1 | awk '{print strftime("%Y-%m-%d %H:%M:%S",$1)}';
}

###### list of numbers with equal width
function nseq()
{
	seq -w 0 "$1"
}

###### convert octals - oct2all
function oct2all() {
    if [[ $1 ]]; then
	echo "octal $1 = binary $(oct2bin $1)"
	echo "octal $1 = decimal $(oct2dec $1)"
	echo "octal $1 = hexadecimal $(oct2hex $1)"
	echo "octal $1 = base32 $(oct2b32 $1)"
	echo "octal $1 = base64 $(oct2b64 $1)"
	echo "octal $1 = ascii $(oct2asc $1)"
    fi
}

###### convert octals - oct2asc
function oct2asc() {
    if [[ $1 ]]; then
	echo -e "\0$(printf %o $((8#$1)))"
    fi
}

###### convert octals - oct2bin
function oct2bin() {
    if [[ $1 ]]; then
	echo "obase=2 ; ibase=8 ; $1" | bc
    fi
}

###### convert octals - oct2b64
function oct2b64() {
    if [[ $1 ]]; then
	echo "obase=64 ; ibase=8 ; $1" | bc
    fi
}

###### convert octals - oct2b32
function oct2b32() {
    if [[ $1 ]]; then
	echo "obase=32 ; ibase=8 ; $1" | bc
    fi
}

###### convert octals - oct2dec
function oct2dec() {
    if [[ $1 ]]; then
	echo $((8#$1))
    fi
}

###### convert octals - oct2hex
function oct2hex() {
    if [[ $1 ]]; then
	echo "obase=16 ; ibase=8 ; $1" | bc
    fi
}

###### Pascal's triangle
function pascal() { l=15;for((i=0;i<$l;i++));do eval "a$i=($(pv=1;v=1;for((j=0;j<$l-$i;j++));do [ $i -eq 0 -o $j -eq 0 ]&&{ v=1 && pv=1; }||v=$((pv+a$((i-1))[$((j))]));echo -n "$v ";pv=$v;done;));";o="$(eval echo "$(for((k=0;k<=$i;k++)); do eval "echo -n \"\$((a\$((i-k))[k])) \""; done)")";echo "$o";s="${#o}"; done; } | while read l; do j=$((s-${#l}/2)); echo "$(while ((i++ < j)); do echo -n " ";done;)$l";done

###### convert phone numbers to letters/potentially english words
function phone2text()
{
	echo -n "Enter number: "
	read num
	# Create a list of possibilites for expansion by the shell
	# the "\}" is an ugly hack to get "}" into the replacment string -
	# this is not a clean escape sequence - the litteral "\" is left behind!
	num="${num//2/{a,b,c\}}"
	num="${num//3/{d,e,f\}}"
	num="${num//4/{g,h,i\}}"
	num="${num//5/{j,k,l\}}"
	num="${num//6/{m,n,o\}}"
	num="${num//7/{p,q,r,s\}}"
	num="${num//8/{t,u,v\}}"
	num="${num//9/{w,x,y,z\}}"
	# cleaup from the hack - remove all litteral \'s
	num="${num//\\/}"
	echo ""
	echo "Possible words are:"
	for word in $( eval echo "$num" )
	do
	    echo '>' "$word"
	done
	# End of File
}

###### powers of numerals
function power() {
    if [[ $1 ]]; then
	if [[ $2 ]]; then
	    echo "$1 ^ $2" | bc
	else	echo "$1 ^ 2" | bc
	fi
    fi
}

###### generate prime numbers, without using arrays.
function primes()
{
	LIMIT=1000                    		# Primes, 2 ... 1000.
		Primes()
		{
			 (( n = $1 + 1 ))             # Bump to next integer.
			 shift                        # Next parameter in list.
			#  echo "_n=$n i=$i_"
			 if (( n == LIMIT ))
			 then echo $*
			 return
			 fi
			 for i; do                    # "i" set to "@", previous values of $n.
			#   echo "-n=$n i=$i-"
			   (( i * i > n )) && break   # Optimization.
			   (( n % i )) && continue    # Sift out non-primes using modulo operator.
			   Primes $n $@               # Recursion inside loop.
			   return
			   done
			   Primes $n $@ $n            #  Recursion outside loop.
									#  Successively accumulate
									#+ positional parameters.
									#  "$@" is the accumulating list of primes.
		}
	Primes 1
}

###### radicals of numbers
function radical() {
    if [[ $1 ]]; then
	echo "sqrt($1)" | bc -l
    fi
}

###### convert to roman numerals
function roman-numeral()
{
python -c 'while True: print (lambda y,x=[],nums={ 1000:"M",900:"CM",500:"D",400:"CD",100:"C",90:"XC",
50:"L",40:"XL",10:"X",9:"IX",5:"V",4:"IV",1:"I"}: (lambda ro=(lambda : map(lambda g,r=lambda b:x.append(
y[-1]/b),t=lambda v:y.append(y[-1]%v):map(eval,["r(g)","t(g)"]),sorted(nums.keys())[::-1]))():"".join(
map(lambda fg: map(lambda ht: nums[ht],sorted(nums.keys())[::-1])[fg] * x[fg],range(len(x)))))())([int(
raw_input("Please enter a number between 1 and 4000: "))])'
}

###### round numerals to whole numbers
function round() {
    if [[ $1 ]]; then
	if [[ $2 ]]; then
	    echo "$(printf %.${2}f $1)"
	else	echo "$(printf %.0f $1)"
	fi
    fi
}

###### ruler that stretches across the terminal
function ruler() { for s in '....^....|' '1234567890'; do w=${#s}; str=$( for (( i=1; $i<=$(( ($COLUMNS + $w) / $w )) ; i=$i+1 )); do echo -n $s; done ); str=$(echo $str | cut -c -$COLUMNS) ; echo $str; done; }

###### convert seconds to minutes, hours, days, and etc. - inputs a number of seconds, outputs a string like "2 minutes, 1 second" $1: number of seconds
function sec2all()
{
    local millennia=$((0))
    local centuries=$((0))
    local years=$((0))
    local days=$((0))
    local hour=$((0))
    local mins=$((0))
    local secs=$1
    local text=""
    # convert seconds to days, hours, etc
    millennia=$((secs / 31536000000))
    secs=$((secs % 31536000000))
    centuries=$((secs / 3153600000))
    secs=$((secs % 3153600000))
    years=$((secs / 31536000))
    secs=$((secs % 31536000))
    days=$((secs / 86400))
    secs=$((secs % 86400))
    hour=$((secs / 3600))
    secs=$((secs % 3600))
    mins=$((secs / 60))
    secs=$((secs % 60))
    # build full string from unit strings
    text="$text$(seconds-convert-part $millennia "millennia")"
    text="$text$(seconds-convert-part $centuries "century")"
    text="$text$(seconds-convert-part $years "year")"
    text="$text$(seconds-convert-part $days "day")"
    text="$text$(seconds-convert-part $hour "hour")"
    text="$text$(seconds-convert-part $mins "minute")"
    text="$text$(seconds-convert-part $secs "second")"
    # trim leading and trailing whitespace
    text=${text## }
    text=${text%% }
    # special case for zero seconds
    if [ "$text" == "" ]; then
        text="0 seconds"
    fi
    # echo output for the caller
    echo ${text}
}

# formats a time unit into a string - $1: integer count of units: 0, 6, etc - $2: unit name: "hour", "minute", etc
function seconds-convert-part()
{
    local unit=$1
    local name=$2
    if [ $unit -ge 2 ]; then
        echo " ${unit} ${name}s"
    elif [ $unit -ge 1 ]; then
        echo " ${unit} ${name}"
    else
        echo ""
    fi
}

###### finding the square root of numbers
function sqrt()
{
echo "sqrt ("$1")" | bc -l
}

###### converts a string (words, text) to binary
function string2bin()
{
	perl -nle 'printf "%0*v8b\n"," ",$_'
}

###### trigonmetry calculations with angles
function trig-angle()
{
	echo "Enter angle in degree: "
	read deg
	# Note: Pi calculation
	# tan(pi/4) = 1
	# atan(1) = pi/4 and
	# pi = 4*atan(1)
	pi=`echo "4*a(1)" | bc -l`
	rad=`echo "$deg*($pi/180)" | bc -l`
	echo "$deg Degree = $rad Radian"
	echo "Sin($deg): "
	echo "s($rad)" | bc -l
	echo "Cos($deg): "
	echo "c($rad)" | bc -l
	echo "Tan($deg): "
	echo "s($rad)/c($rad)" | bc -l
}

####### Ask
function ask()
{
    echo -n "$@" '[y/n] ' ; read ans
    case "$ans" in
        y*|Y*) return 0 ;;
        *) return 1 ;;
    esac
}

######## Escape potential tarbombs
function atb() { l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.tar.gz} && tar xf $1 -C ${1%.tar.gz}; fi ; }

######### Get the headlines of an atom feed
function atomtitles()
{
	curl --silent $1 | xmlstarlet sel -N atom="http://www.w3.org/2005/Atom" -t -m /atom:feed/atom:entry -v atom:title -n
}

####### backupsfolder
function backupsfolder()
{
    if [ -d $HOME/backups_html ]; then
        chown -R $USER:www-data $HOME/backups_html
        chmod 755 $HOME/backups_html
        find $HOME/backups_html/ -type d -exec chmod 775 {} \;
        find $HOME/backups_html/ -type f -exec chmod 664 {} \;
        chmod 755 $HOME
    fi
}

####### private
function private()
{
    find $HOME -type d -exec chmod 700 {} \;
    find $HOME -type f -exec chmod 600 {} \;
    find $HOME/bin -type f -exec chmod +x {} \;
    find $HOME/.dropbox-dist/dropbox* -type f -exec chmod +x {} \;
}

####### publicfolder
function publicfolder()
{
    if [ -d $HOME/public_html ]; then
        chown -R $USER:www-data $HOME/public_html
        chmod 755 $HOME/public_html
        find $HOME/public_html/ -type d -exec chmod 775 {} \;
        find $HOME/public_html/ -type f -exec chmod 664 {} \;
        chmod 755 $HOME
    fi
}

####### setperms
function setperms()
{
    echo "setting proper permissions in ~/"
    private
    public
}

####### wwwrc
function wwwrc()
{
    alias mv="mv"
    mv -f ~/.[a-z]*.html ~/public_html/
    chmod 644 ~/public_html/.[a-z]*.html
    chown $USER:www-data ~/public_html/.[a-z]*.html
    alias mv="mv -i"
}

####### Backup .bash* files
function backup_bashfiles()
{
  ARCHIVE="$HOME/bash_dotfiles_$(date +%Y%m%d_%H%M%S).tar.gz";
  cd ~
  tar -czvf $ARCHIVE .bash_profile .bashrc .bash_functions .bash_aliases .bash_prompt
  echo "All backed up in $ARCHIVE";
}

####### Creates a backup of the file passed as parameter with the date and time
function bak()
{
  cp $1 $1_`date +%H:%M:%S_%d-%m-%Y`
}

####### Good bash tips for everyone
function bashtips() {

cat <<EOF
DIRECTORIES
-----------
~-          Previous working directory
pushd tmp   Push tmp && cd tmp
popd        Pop && cd
GLOBBING AND OUTPUT SUBSTITUTION
--------------------------------
ls a[b-dx]e Globs abe, ace, ade, axe
ls a{c,bl}e Globs ace, able
\$(ls)      \`ls\` (but nestable!)
HISTORY MANIPULATION
--------------------
!!        Last command
!?foo     Last command containing \`foo'
^foo^bar^ Last command containing \`foo', but substitute \`bar'
!!:0      Last command word
!!:^      Last command's first argument
!\$       Last command's last argument
!!:*      Last command's arguments
!!:x-y    Arguments x to y of last command
C-s       search forwards in history
C-r       search backwards in history
LINE EDITING
------------
M-d     kill to end of word
C-w     kill to beginning of word
C-k     kill to end of line
C-u     kill to beginning of line
M-r     revert all modifications to current line
C-]     search forwards in line
M-C-]   search backwards in line
C-t     transpose characters
M-t     transpose words
M-u     uppercase word
M-l     lowercase word
M-c     capitalize word
COMPLETION
----------
M-/     complete filename
M-~     complete user name
M-@     complete host name
M-\$    complete variable name
M-!     complete command name
M-^     complete history
EOF
}

###### # Execute a given Linux command on a group of files - Example1: batchexec sh ls # lists all files that have the extension 'sh' - Example2: batchexec sh chmod 755	# 'chmod 755' all files that have the extension 'sh'
function batchexec()
{
	find . -type f -iname '*.'${1}'' -exec ${@:2}  {} \; ;
}

# Clock - A bash clock that can run in your terminal window.
#------------------------------------------////

###### binary clock
function bclock()
{
	watch -n 1 'echo "obase=2;`date +%s`" | bc'
}

###### binary clock
function bclock2()
{
	perl -e 'for(;;){@d=split("",`date +%H%M%S`);print"\r";for(0..5){printf"%.4b ",$d[$_]}sleep 1}'
}

###### clock
function clock()
{
	while true;do clear;echo "===========";date +"%r";echo "===========";sleep 1;done
}

###### Appends a '&' to a command so it will run in the background - useful for aliases
function bg_wrapper()
{
    "$@" &
}

####### Substitutes underscores for blanks in all the  - filenames in a directory
function blank_rename()
{
	ONE=1                     # For getting singular/plural right (see below).
	number=0                  # Keeps track of how many files actually renamed.
	FOUND=0                   # Successful return value.
	for filename in *         #Traverse all files in directory.
	do
		echo "$filename" | grep -q " "         #  Check whether filename
		if [ $? -eq $FOUND ]                   #+ contains space(s).
		then
		  fname=$filename                      # Yes, this filename needs work.
		  n=`echo $fname | sed -e "s/ /_/g"`   # Substitute underscore for blank.
		  mv "$fname" "$n"                     # Do the actual renaming.
		  let "number += 1"
		fi
	done
	if [ "$number" -eq "$ONE" ]                 # For correct grammar.
	then
	 echo "$number file renamed."
	else
	 echo "$number files renamed."
	fi
}

####### Convert bluray to xvid	# example: bluray2xvid bluraydisc.m2ts desired_name.avi
function bluray2xvid()

{
	mencoder $1 -oac mp3lame -lameopts cbr:br=128 -ofps 24 -vf harddup -vf scale=1280:720 -ovc xvid -xvidencopts fixed_quant=3 -o $2
}

# Bookmarking 
#------------------------------------------////

###### bookmarking the current directory in 'alias' form
function bookmark() {
    
    if [[ $1 != "" && $(alias | grep -w go-$1) == "" ]]; then
	echo "alias go-$1='cd $PWD'" >> $HOME/.bookmarks
	. $HOME/.bookmarks
    elif [[ $1 == "" ]]; then
	echo "need name for the bookmark."
    else	echo "bookmark go-$1 already exists."
    fi
}

###### unmark
function unmark() {
    
    if [[ $(alias | grep -w go-$1= ) != "" ]]; then
	sed -e "/go-$1/d" -i $HOME/.bookmarks
	xunalias go-$1
    fi
}

###### copies files to a bookmarked dir - cto file1.jpg file2.jpg file3.jpg pics
function cto() {
    eval lastarg=\${$#}
    targetdir=`getBookmark $lastarg`
    echo "Copying files to $targetdir"
    if [ -n "$targetdir" ]; then
        for dir in "$@";
            do
                if [ "$dir" != $lastarg ]; then
                    cp -iv "$dir" "$targetdir"
                fi
            done
    fi
}

###### moves files to a bookmarked dir - mto vid1.avi vid2.avi videos
function mto() {
    eval lastarg=\${$#}
    targetdir=`getBookmark $lastarg`
    echo "Moving files to $targetdir"
    if [ -n "$targetdir" ]; then
        for dir in "$@";
            do
                if [ "$dir" != $lastarg ]; then
                    mv -iv "$dir" "$targetdir"
                fi
            done
    fi
}

###### Directory Bookmarks for BASH (c) 2009, Ira Chayut, Version 090927
# DirB and its implementation in this file are the product of, and
# copyrighted by Ira Chayut.  You are granted a non-exclusive, royalty-free
# license to use, reproduce, modify and create derivative works from DirB;
# providing that credit is given to DirB as a source material.
# The lastest version is available from: http://www.dirb.info/bashDirB.  Ira can
# be reached at [email protected].
# By default DirB will have the shell echo the current working directory out
# to the title bars of Xterm windows.  To disable this behavior, comment
# out the next line.
# PS1="\[\033]0;\w\007\]\t \!> "
# If the repository of bookmarks does not exist, create it
if  [ ! -e ~/.DirB ]
then
    mkdir ~/.DirB
fi

###### "d" - Display (or Dereference) a saved bookmark - to use: cd "$(d xxx)"
function d() {
    # if the bookmark exists, then extract its directory path and print it
    if [ -e ~/.DirB/"$1" ]
    then
        sed -e 's/\$CD //' -e 's/\\//g' ~/.DirB/"$1"

    # if the bookmark does not exists, complain and exit with a failing code
    else
        echo bash: DirB: ~/.DirB/"$1" does not exist >&2
        false
    fi
}

###### "g" - Go to bookmark
function g() {
    # if no arguments, then just go to the home directory
    if [ -z "$1" ]
    then
        cd
    else
        # if $1 is in ~/.DirB and does not begin with ".", then go to it
        if [ -f ~/.DirB/"$1" -a ${1:0:1} != "." ]
        then
            # update the bookmark's timestamp and then execute it
            touch ~/.DirB/"$1" ;
            CD=cd source ~/.DirB/"$1" ;
        # else just do a "cd" to the argument, usually a directory path of "-"
        else
            cd "$1"
        fi
    fi
}

###### "p" - Push a bookmark
function p() {
    # Note, the author's preference is to list the directory stack in a single
    # column.  Thus, the standard behavior of "pushd" and "popd" have been
    # replaced by discarding the normal output of these commands and using a
    # "dirs -p" after each one.

    # if no argument given, then just pushd and print out the directory stack
    if [ -z "$1" ]
    then
        pushd > /dev/null && dirs -p

    # if $1 is a dash, then just do a "popd" and print out the directory stack
    elif [ "$1" == "-" ]
    then
        popd > /dev/null
        dirs -p
    else
        # if $1 is in ~/.DirB and does not begin with ".", then go to it
        # and then print out the directory stack
        if [ -f ~/.DirB/"$1" -a "${1:0:1}" != "." ]
            then
                touch ~/.DirB/$1 ;
                CD=pushd source ~/.DirB/$1 > /dev/null && dirs -p ;

        # else just do a "pushd" and print out the directory stack
        else
            pushd "$1" > /dev/null && dirs -p
        fi
    fi
}

###### "r" - Remove a saved bookmark
function r() {
    # if the bookmark file exists, remove it
    if [ -e ~/.DirB/"$1" ]
    then
        rm ~/.DirB/"$1"

    # if the bookmark file does not exist, complain and exit with a failing code
    else
        echo bash: DirB: ~/.DirB/"$1" does not exist >&2
        false
    fi
}

###### "s" - Save bookmark
function s() {
    if [ -n "$2" ]
    then
        # build the bookmark file with the contents "$CD directory_path"
        ( echo '$CD ' \"$2\" > ~/.DirB/"$1" ;) > /dev/null 2>&1
    else
        # build the bookmark file with the contents "$CD directory_path"
        ( echo -n '$CD ' > ~/.DirB/"$1" ;
          pwd | sed "s/ /\\\\ /g" >> ~/.DirB/"$1" ; ) > /dev/null 2>&1
    fi
    # if the bookmark could not be created, print an error message and
    # exit with a failing return code
    if [ $? != 0 ]
    then
        echo bash: DirB: ~/.DirB/"$1" could not be created >&2
        false
    fi
}

###### "sl" - Saved bookmark Listing
function sl() {
    # if the "-l" argument is given, then do a long listing, passing any
    # remaining arguments to "ls", printing in reverse time order.  Pass the
    # output to "less" to page the output if longer than a screen in length.
    if [ "$1" == "-l" ]
    then
        shift
        ( cd ~/.DirB ;
        ls -lt $* |
            sed -e 's/  */ /g' -e '/^total/d' \
                -e 's/^\(... \)\([0-9] \)/\1 \2/' |
            cut -d ' ' -s -f6- | sed -e '/ [0-9] /s// &/' | less -FX ; )

    # else print the short form of the bookmarks in reverse time order
    else
        ( cd ~/.DirB ; ls -xt $* ; )
    fi
}

###### simple bookmark system
function getBookmark() {
    case "$1" in
    video|vids|vid) echo "~/Videos" ;; # video, vids and vid are shortcuts to use with the functions below, the bookmarked directory is "~/videos"
    images|img|pics|pictures) echo "~/Pictures";;
    *) echo "" ;;
    esac
}

###### list contents of a bookmarked dir without - going there: list vids
function list() {
    dir=`getBookmark $1`
    echo $dir
    if [ -n "$dir" ]; then
        ls "$dir"
    fi
}

###### same as "list" but with details: llist vids
function llist() {
    dir=`getBookmark $1`
    echo $dir
    if [ -n "$dir" ]; then
        ll "$dir"
    fi
}

###### Create box of '#' characters around given string
function box() { t="$1xxxx";c=${2:-#}; echo ${t//?/$c}; echo "$c $1 $c"; echo ${t//?/$c}; }

# Download all videos in your Boxee queue Gets all videos in your boxee queue with a URL associated with them and attempts to download each using get_flash_videos
function boxeedl()
{
	for i in $(curl -u <username> http://app.boxee.tv/api/get_queue | xml2 | grep /boxeefeed/message/object/url | cut -d "=" -f 2,3); do get_flash_videos $i; done
}

# Randomness					 #
#------------------------------------------////

###### This script models Brownian motion: random wanderings of tiny particles in fluid, as they are buffeted by random currents and collisions (colloquially known as "Drunkard's Walk")
function brownian()
{
	PASSES=500            		#  Number of particle interactions / marbles.
	ROWS=10               		#  Number of "collisions" (or horiz. peg rows).
	RANGE=3               		#  0 - 2 output range from $RANDOM.
	POS=0                 		#  Left/right position.
	RANDOM=$$             		#  Seeds the random number generator from PID of script.
	declare -a Slots      		# Array holding cumulative results of passes.
	NUMSLOTS=21           		# Number of slots at bottom of board.
	function Initialize_Slots() { 	# Zero out all elements of the array.
	for i in $( seq $NUMSLOTS )
	do
	  Slots[$i]=0
	done
	echo                  		# Blank line at beginning of run.
	  }
	function Show_Slots() {
	echo -n " "
	for i in $( seq $NUMSLOTS )   	# Pretty-print array elements.
	do
	  printf "%3d" ${Slots[$i]}   	# Allot three spaces per result.
	done
	echo 				# Row of slots:
	echo " |__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|"
	echo "                                ^^"
	echo 				#  Note that if the count within any particular slot exceeds 99,
			#+ it messes up the display.
			#  Running only(!) 500 passes usually avoids this.
	  }
	function Move() {              	# Move one unit right / left, or stay put.
	  Move=$RANDOM         		# How random is $RANDOM? Well, let's see ...
	  let "Move %= RANGE"  		# Normalize into range of 0 - 2.
	  case "$Move" in
	    0 ) ;;      	        # Do nothing, i.e., stay in place.
	    1 ) ((POS--));;     	# Left.
	    2 ) ((POS++));;     	# Right.
	    * ) echo -n "Error ";;   	# Anomaly! (Should never occur.)
	  esac
	  }
	function Play() {               # Single pass (inner loop).
	i=0
	while [ "$i" -lt "$ROWS" ]   	# One event per row.
	do
	  Move
	  ((i++));
	done
	SHIFT=11                     	# Why 11, and not 10?
	let "POS += $SHIFT"          	# Shift "zero position" to center.
	(( Slots[$POS]++ ))          	# DEBUG: echo $POS
	  }
	function Run() {                # Outer loop.
	p=0
	while [ "$p" -lt "$PASSES" ]
	do
	  Play
	  (( p++ ))
	  POS=0                      	# Reset to zero. Why?
	done
	  }
	# main()
	Initialize_Slots
	Run
	Show_Slots
}

###### flip a single coin 1000 times and show results
function coin-flip()
{
	SEED=$"(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')"
	RANDOM=$SEED
	SIDES=2          	# A coin has 2 sides.
	MAXTHROWS=1000   	# Increase this if you have nothing better to do with your time.
	throw=0         	# Throw count.
	heads=0          	# Must initialize counts to zero,
	tails=0          	# since an uninitialized variable is null, not zero.
	function print_result()
	{
		echo
		echo "heads =   $heads"
		echo "tails =   $tails"
		echo
	}
	function update_count()
	{
		case "$1" in
		  0) let "heads += 1";; # Since coin has no "zero", this corresponds to 1.
		  1) let "tails += 1";; # And this to 2, etc.
		esac
	}
	echo
	while [ "$throw" -lt "$MAXTHROWS" ]
	do
	  let "coin1 = RANDOM % $SIDES"
	  update_count $coin1
	  let "throw += 1"
	done
	print_result
	echo "Out of a total of "$MAXTHROWS" tosses."
	echo "Change \"MAXTHROWS=1000\" if you want a different number of tosses."
}

###### roll a single die of "$1" sides, just once default number of sides is 6
function one-die()
{
	function roll_die() {
		  # capture parameter
		  declare -i DIE_SIDES=$1
		  # check for die sides
		  if [ ! $DIE_SIDES -gt 0 ]; then
		    # default to 6
		    DIE_SIDES=6
		  fi
		  # echo to screen
		  echo $[ ( $RANDOM % $DIE_SIDES )  + 1 ]
	}
	# roll_die 10  # returns 1 to 10 as per 10 sides
	# roll_die 2   # returns 1 or 2 as per 2 sides
	roll_die "$1"
}

###### select random card from a deck
function pick-card()
{
	# This is an example of choosing random elements of an array.
	# Pick a card, any card.
	Suites="Clubs
	Diamonds
	Hearts
	Spades"
	Denominations="2
	3
	4
	5
	6
	7
	8
	9
	10
	Jack
	Queen
	King
	Ace"
	# Note variables spread over multiple lines.
	suite=($Suites)                # Read into array variable.
	denomination=($Denominations)
	num_suites=${#suite[*]}        # Count how many elements.
	num_denominations=${#denomination[*]}
	echo -n "${denomination[$((RANDOM%num_denominations))]} of "
	echo ${suite[$((RANDOM%num_suites))]}
	# $bozo sh pick-cards.sh
	# Jack of Clubs
	# Thank you, "jipe," for pointing out this use of $RANDOM.
}

###### random number (out of whatever you input) example:	random 10	=	4
function random() {
    if [[ $1 == -l ]]; then
	echo $(cat /dev/urandom | tr -cd '[:digit:]' | head -c ${2-5})
    elif [[ $1 == -r ]]; then
	echo $((RANDOM%${2}))
    else	echo $((RANDOM%${1}))
    fi
}

###### create random blank files
function randomblanks()
{
	for ((  i = 0 ;  i < $1;  i++  )); do touch $RANDOM; done
}

###### random file
function randomfile() {
    case $1 in
	    *first)
		sed -n '1p' $HOME/.randomhistory
	    ;;
	    *last)
		sed -n '$p' $HOME/.randomhistory
	    ;;
	    *n)
		sed -n "${2}p" $HOME/.randomhistory
	    ;;
	    *l)
		wc -l $HOME/.randomhistory | gawk '{print $1}'
	    ;;
	    *c)
		rm $HOME/.randomhistory
	    ;;
	    *help )
		echo -e "\n${ewhite}Usage:\n"
		echo -e "${eorange}randomfile${ewhite} | ${egreen}--first ${eiceblue}[get the first file in the history]\
		\n${eorange}randomfile${ewhite} | ${egreen}--last ${eiceblue}[get the last file in the history]\
		\n${eorange}randomfile${ewhite} | ${egreen}--n ${eiceblue}[get the NUMBERth file in the history]\
		\n${eorange}randomfile${ewhite} | ${egreen}--l ${eiceblue}[get the number of files in history]\
		\n${eorange}randomfile${ewhite} | ${egreen}--c ${eiceblue}[clear the history]\n" | column -t
		tput sgr0
	    ;;
	    *)
		if [[ ! "$FILES" ]]; then
		    files=(*)
		else	files=("$FILES")
		fi
		n=${#files[@]}
		RANDOMFILE="${files[RANDOM % n]}"
		echo "$RANDOMFILE" >> $HOME/.randomhistory
		if [[ ! "$@" ]]; then
		    echo "$RANDOMFILE"
		else	"$@" "$RANDOMFILE"
		fi
	    ;;
    esac
}

###### pulls a random line from text file
function randomline()
{
	# AUTHOR: David Ivan Stark (clyphox), [email protected]
	if [ "$1" ];then  #checking if we were passed a filename/variable
		FileName="$1"  #just an easier variable to work with
		if [ ! -f "$FileName" ];then  #check if it is a file
		    echo "Err: $FileName is not a file"
		fi
		#Count how many lines in the file
		LineCount="$(wc -l "$FileName" | cut -f 1 -d ' ')"
		#Dont continue if we have less than 1 line
		if [ "$LineCount" -gt "1" ];then
			#Test past.. selecting random line
			TargetLine=$[ ( $RANDOM % $LineCount )  + 1 ]
			Output="$(sed -n "${TargetLine}p" "$FileName")"
			echo "$Output"
		    else
			echo need a file with more than 1 line... cmon...
		fi
	    else	#seems we didnt get any input
		echo "Please specify a text file"
	fi
}

###### Generates neverending list of random numbers
function randomnumbers()
{
	while :
	do
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	 echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
	done
}

###### Random wallpaper (add whatever wallpaper directory(s) you wish after 'BACKGROUND_DIRS')
# function randomwp()
	# # for GNOME2
	# {
	# cat > "/tmp/randomwp.py" <<"End-of-message"
	# #!/usr/bin/env python
	# BACKGROUND_DIRS = ['/usr/share/backgrounds', '~/Pictures/Backgrounds']
	# EXTENSIONS = ['jpeg', 'jpg', 'bmp', 'png', 'svg']
	# import os, glob, random, itertools, gconf
	# files = list(itertools.chain(*[[os.path.join(dirpath, name)
	#                                 for name in filenames]
	#                                for dirpath, dirnames, filenames in
	#                                itertools.chain(*[os.walk(os.path.expanduser(d))
	#                                                  for d in BACKGROUND_DIRS])]))
	# gconf.client_get_default().set_string(
	#     '/desktop/gnome/background/picture_filename',
	#     random.choice(files))
	# End-of-message
	# chmod +x "/tmp/randomwp.py"
	# "/tmp/randomwp.py"
	# /bin/rm "/tmp/randomwp.py"
# }

###### Random-Gnome3-Wallpaper.sh - for GNOME3 Script to randomly set desktop/gdm background - Requires: sudo-apt get install randomize-lines
function randomwp()
{
	###### just add/remove as many directories as wish
	find "/usr/share/backgrounds" "$HOME/Pictures/Backgrounds" -type f \( -name "*.bmp" -or -name "*.BMP" -or -name "*.jpeg" -or -name "*.JPEG" -or -name "*.jpg" -or -name "*.JPG" -or -name "*.png" -or -name "*.PNG" -or -name "*.svg" -or -name "*.SVG" \)|rl|head -n 1|xargs -I{} bash -c "gsettings set org.gnome.desktop.background picture-uri \"file://{}\""
}

###### Random-Gnome3-Wallpaper-2.sh - Script to randomly set desktop/gdm background
function randomwp_()
{
	###### Directories Containing Pictures (to add more folders here, just "/path/to/your/folder")
	arr[0]="/usr/share/backgrounds"
	arr[1]="$HOME/Pictures/Backgrounds"
	# arr[2]=
	# arr[3]=
	# arr[4]=
	# arr[5]=
	# arr[6]=
	# arr[7]=
	# arr[8]=
	# arr[9]=
	# arr[10]=
	###### How many picture folders are there? (currently = 2)
	rand=$[ $RANDOM % 2 ]
	###### Command to select a random folder
	DIR=`echo ${arr[$rand]}`
	###### Command to select a random file from directory
	# The *.* should select only files (ideally, pictures, if that's all that's inside)
	PIC=$(ls $DIR/*.* | shuf -n1)
	###### Command to set background Image
	gsettings set org.gnome.desktop.background picture-uri "file://$PIC"
}

###### randomwpt automatic wallpaper switcher for GNOME2 - Usage: randomwpt "bash directory_name" "timeout_in_seconds" - for GNOME2 only
function randomwpt()
{
	if [ $# -ne 2 ];then
	    echo -n "Usage: $0 directory_name timeout_in_seconds
	    Leave the directory name blank for Current Directory
	    For you lazy pal, I assume timeout as 5 sec and Directory as current
	    Do you want to accept this settings? (Y/n): ";
	    read response
	    if [[ "$response" =~ ^[^yY] ]];then
		exit 0
	    fi
	fi
	function set_wallpaper() {
	    gconftool-2 -s /desktop/gnome/background/picture_options "centered" -t string;
	    gconftool-2 -s /desktop/gnome/background/picture_filename "$1" -t string;
	}
	TIMEOUT=${2-5};
	WALL_DIR=${1-`pwd`};
	echo "Timeout value is: $TIMEOUT";
	echo "Directory is: $WALL_DIR";
	echo
	if [ ! -d "$WALL_DIR" ];then
	    echo "The Directory Specified is invalid..";
	    exit 1;
	fi
	filelst="$(find "$WALL_DIR" -type f -name '*.jpg' -o -name '*.png')";
	if [ -z "$filelst" ];then
	    echo "No Suitable files found in this location: $WALL_DIR";
	    exit 1;
	fi
	while true;do
	    filename=`echo "$filelst" | shuf -n 1`
	    set_wallpaper "$filename";
	    sleep $TIMEOUT;
	done
}

###### rename a file with a random name The function will rename files but maintain their extensions. BUG: If a file doesn't have an extension it will end up with a dot at the end of the name. The parameter '8' for pwgen controls the length of filenames - eight random characters.
function rf() { for i in "$@"; do mv "$i" "$(pwgen 8 1).${i##*.}"; done }

###### roll a single die 1000 times and show results
function roll-die()
{
	SEED=$"(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')"
	RANDOM=$SEED
	PIPS=6          	# A die has 6 pips.
	MAXTHROWS=1000   	# Increase this if you have nothing better to do with your time.
	throw=0         	# Throw count.
	ones=0          	#  Must initialize counts to zero,
	twos=0          	#+ since an uninitialized variable is null, not zero.
	threes=0
	fours=0
	fives=0
	sixes=0
	function print_result()
	{
		echo
		echo "ones =   $ones"
		echo "twos =   $twos"
		echo "threes = $threes"
		echo "fours =  $fours"
		echo "fives =  $fives"
		echo "sixes =  $sixes"
		echo
	}
	function update_count()
	{
		case "$1" in
		  0) let "ones += 1";;   # Since die has no "zero", this corresponds to 1.
		  1) let "twos += 1";;   # And this to 2, etc.
		  2) let "threes += 1";;
		  3) let "fours += 1";;
		  4) let "fives += 1";;
		  5) let "sixes += 1";;
		esac
	}
	echo
	while [ "$throw" -lt "$MAXTHROWS" ]
	do
	  let "die1 = RANDOM % $PIPS"
	  update_count $die1
	  let "throw += 1"
	done
	print_result
	echo "Out of a total of "$MAXTHROWS" rolls."
	echo "Change \"MAXTHROWS=1000\" if you want a different number of rolls."
}

###### Backup a file with a date-time stamp - Usage "bu filename.txt"
function bu() { cp $1 ${1}-`date +%Y%m%d%H%M`.backup ; }

###### buf Backup a file with a date-time stamp
function buf() { cp -v $1 ${1/${1%%.*}/$f-$(date +"%Y%m%d_%H%M%S")}; }

###### Extract a file and cd into the new folder	
function build()
{
   extract "$1" && cd
}

###### Needs fixing
function build_() {
	args=($@)
	args[0]=
	reset
	tcc -o $1 ${1}.c ${args[@]}
	if [ $? -eq 0 ]; then
	./$1;
	fi
}

###### Buffer in order to avoir mistakes with redirections that empty your files
function buffer() { tty -s && return; tmp=$(mktemp); cat > "${tmp}"; if [ -n "$1" ] && ( ( [ -f "$1" ] && [ -w "$1" ] ) || ( ! [ -a "$1" ] && [ -w "$(dirname "$1")" ] ) ); then mv -f "${tmp}" "$1"; else echo "Can't write in \"$1\""; rm -f "${tmp}"; fi }

###### Generate a case-insensitive pattern
function casepat() { perl -pe 's/([a-zA-Z])/sprintf("[%s%s]",uc($1),$1)/ge' ; }

###### Concatenate PDF files - e.g. cat_pdfs -o combined.pdf file1.pdf file2.pdf file3.pdf
function cat_pdfs() { python '/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py' "$@" ; }

# Copy & paste files and folders from the command line
#------------------------------------------////

###### Usage: "ccopy FILE/FOLDER#1 FILE/FOLDER#2 FILE/FOLDER#3 FILE/FOLDER#4 ..." Note: You must 'cd' into the folder first ("whatever" works, while "~/myfolder/whatever" doesn't)
function ccopy() { for i in $*; do cp -a $i /tmp/ccopy.$i; done }
alias cpaste="ls -d /tmp/ccopy* | sed 's|[^\.]*.\.||' | xargs -I % mv /tmp/ccopy.% ./%"

# Power cd (add some of useful features to 'cd') #
#------------------------------------------////

###### Move efficiently between directories. - This command adds a couple of extra features to cd, without affecting normal use. CDPATH use is also unaffected. It introduces and environment variable CDDIR which is used as an alternate home directory. `export CDDIR="$HOME/work"` and `alias cdd="CDDIR=$(pwd)"` must also be uncommented/enabled for this to work
function cd() { if [ -n "$1" ]; then [ -f "$1" ] && set -- "${1%/*}"; else [ -n "$CDDIR" ] && set -- "$CDDIR"; fi; command cd "$@"; }

alias cdd="CDDIR=$(pwd)"

###### Print working directory after a cd.
# function cd() {
#     if [[ $@ == '-' ]]; then
#         builtin cd "$@" > /dev/null  # We'll handle pwd.
#     else
#         builtin cd "$@"
#     fi
#     echo -e "   \033[1;30m"`pwd`"\033[0m"
# }

###### # Change directory and list files
function cds() {
    # only change directory if a directory is specified
    [ -n "${1}" ] && cd $1
    lls
}

# Grep, grep, grep				 #
#------------------------------------------////

###### randomize GNU grep's colors 31-36 excluding black and white.
function cgrep() { GREP_COLOR="1;3$((RANDOM%6+1))" grep --color=always "$@" ; }

###### to grep through files found by find, e.g. grepf pattern '*.c' - note that 'grep -r pattern dir_name' is an alternative if want all files
function grepfind() { find . -type f -name "$2" -print0 | xargs -0 grep "$1" ; }

###### to grep through the /usr/include directory
function grepincl() { (cd /usr/include; find . -type f -name '*.h' -print0 | xargs -0 grep "$1" ) ; }

###### hgrep, hgrepl (I use these so much I miss them not being on my other machines and should copy them over)
function hgrepl() {
	history | sed s/.*\ \ // | grep $@
}

###### hgrep
function hgrep() {
	history | sed s/.*\ \ // | grep $@ | tail -n 30
}

###### hhgrep
function hhgrep() {
	history | egrep "$@" | egrep -v "hgrep $@"
}

###### Analyze your bash usage
function check_()
{
	cut -f1 -d" " .bash_history | sort | uniq -c | sort -nr | head -n 30
}

####### Checksum
function checksum()
{
    action=$1
    shift
    if [[ ( $action == "-c" || $action == "--check" ) && $1 == *.* ]]; then
	type="${1/*./}"
    else	type=$1
	shift
    fi
    case $type in
	md5 )
	    checktool=md5sum
	;;
	sha1 | sha )
	    checktool=sha1sum
	;;
	sha224 )
	    checktool=sha224sum
	;;
	sha256 )
	    checktool=sha256sum
	;;
	sha384 )
	    checktool=sha384sum
	;;
	sha512 )
	    checktool=sha512sum
	;;
    esac
    case $action in
	-g | --generate )
	    for file in "${@}"; do
		$checktool "${file}" > "${file}".$type
	    done
	;;
	-c | --check )
	    for file in "${@}"; do
		if [[ "${file}" == *.$type ]]; then
		    $checktool --check "${file}"
		else	$checktool --check "${file}".$type
		fi
	    done
	;;
	-h | --help )
	;;
    esac
}

###### MD5 checksum
function md5()
{
    echo -n $@ | md5sum
}

###### Encode a string in md5 hash of 32 characters
# You can short the length with the second parameter.
#  @param string $1 string (required)
#  @param integer $2 length (option, default: 32)
#  @return string
#  @example:    md5 "Hello World" 8
function md5_() {
      local length=${2:-32}
      local string=$( echo "$1" | md5sum | awk '{ print $1 }' )
      echo ${string:0:${length}}
}

###### cifsmount Mount CIFS shares; pseudoreplacement for smbmount -  $1 = remote share name in form of //server/share $2 = local mount point
function cifsmount() { sudo mount -t cifs -o username=${USER},uid=${UID},gid=${GROUPS} $1 $2; }

###### cifsumount unmount CIFS shares; pseudoreplacement for smbmount 
function cifsumount() { sudo umount $1; }

# Commandlinefu.com and Shell-fu.org stuff	 #
#------------------------------------------////

###### Search commandlinefu.com from the command line- using the API - Usage: cmdfu hello world
function cmdfu() { curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext" --silent | sed "s/\(^#.*\)/\x1b[32m\1\x1b[0m/g" | less -R ; }

###### cmdfu
# function cmdfu() { curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext"; }

###### automatically downloads all commands from http://www.commandlinefu.com into a single text file
alias cmdfu_dl='mkdir /tmp/commandlinefu && cd /tmp/commandlinefu && curl -O http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/[0-2400:25] && ls -1 | sort -n | while read mork ; do cat $mork >> commandlinefu.txt ; ls -ald $mork; done && mv commandlinefu.txt $HOME && rm -rf /tmp/commandlinefu'

###### find a CommandlineFu users average command rating
function cmdfu_rating()
{
	wget -qO- www.commandlinefu.com/commands/by/PhillipNordwall | awk -F\> '/class="num-votes"/{S+=$2; I++}END{print S/I}'
}

###### cmdfu_rating_
function cmdfu_rating_()
{
	curl -s www.commandlinefu.com/commands/by/PhillipNordwall | awk -F\> '/class="num-votes"/{S+=$2; I++}END{print S/I}'
}

##### key binding to search commandlinefu.com
function ds_() { echo -n "search : "; read ST; EST=`php -r "echo rawurlencode('$ST');"`; B64=`echo -n $ST| openssl enc -base64`; curl -s "http://www.commandlinefu.com/commands/matching/$EST/$B64/plaintext" | less -p "$ST"; } ; bind '"\C-k"':"\"ds\C-m\""

###### command examples from shell-fu
function examples() { 
	lynx -width=$COLUMNS -nonumbers -dump "http://www.shell-fu.org/lister.php?tag=$1" | \
	sed -n '/^[a-zA-Z]/,$p' | egrep -v '^http|^javas|View Comm|HIDE|] \+|to Share|^ +\*|^ +[HV][a-z]* l|^ .*efu.*ep.*!$' | \
	sed -e '/^  *__*/N;s/\n$//g' | less -r; 
}

###### fuman, an alternative to the 'man' command that shows commandlinefu.com examples
function fuman() { 
	lynx -width=$COLUMNS -nonumbers -dump "http://www.commandlinefu.com/commands/using/$1" |sed '/Add to favourites/,/This is sample output/!d' |sed 's/ *Add to favourites/----/' |less -r; 
}

###### Random Commandlinefu command
function fur() { curl -sL 'http://www.commandlinefu.com/commands/random/plaintext' | grep -v "^# commandlinefu" ; }

###### Prepare a commandlinefu command
function goclf()
{
	type "$1" | sed '1d' | tr -d "\n" | tr -s '[:space:]'; echo
}

###### What package does that command come from?
function cmdpkg() { PACKAGE=$(dpkg -S $(which $1) | cut -d':' -f1); echo "[${PACKAGE}]"; dpkg -s "${PACKAGE}" ;}

# Sets custom Catalog Number ID3 tag for all	MP3 files in current directory
#------------------------------------------////

###### $1 = catalog number
function cn() { for i in *.mp3; do id3v2 --TXXX "Catalog Number":"$1" "$i"; done; }

# Quick reference color charts & color stuff 	 #
#------------------------------------------////

###### shows a gui color chart
#function color-picker()
#{
#	# for GNOME2 only - sudo apt-get install python-gtkmozembed xulrunner-2.0 
#    # (Packete gibt es nicht mehr)
#	# also requires: "~/.gnome2/nemo-scripts/.colorchart/view.html"
#	echo "When you are finished, press "Control C" to continue..."
#cat > "/tmp/color-picker.py" <<"End-of-message"
##!/usr/bin/python
#import os
#import pygtk
#pygtk.require('2.0')
#import gtk
#import gtkmozembed
#homedir = os.path.expanduser('~')
#try:
#    from win32com.shell import shellcon, shell
#    homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
#except ImportError:
#    homedir = os.path.expanduser("~/.gnome2/nemo-scripts/.colorchart/view.html")
#class ColorChart:
#    def __init__(self):
#                self.moz = gtkmozembed.MozEmbed()
#	box = gtk.VBox(False,0)
#	win = gtk.Window()
#	win.add(box)
#	hbox = gtk.HBox(False,0)
#               box.pack_start(hbox,False,False)
#                hbox.show()
#	box.pack_start(self.moz,True,True,0)
#                self.moz.show()
#	self.moz.load_url(homedir)
#                self.moz.set_size_request(650,550)
#	title=self.moz.get_title()
#	win.set_title("RGB/HEX Color Picker")
#	win.show_all()
#if __name__ == "__main__":
#    ColorChart()
#    gtk.main()
#End-of-message
#	chmod +x "/tmp/color-picker-.py"
#	/usr/bin/python "/tmp/color-picker.py"
#	/bin/rm "/tmp/color-picker.py"
#}

###### takes a name of a color and some text and then echoes out the text in the named color - Usage:	colorize_text "color" "whatever text"
function colorize-text()
{
	b='[0;30m'
	# Implement command-line options
	while getopts "nr" opt
	 do
	  case $opt in
	   n  )  o='-n' ;;
	   r  )  b=''   ;;
	  esac
	 done
	shift $(($OPTIND - 1))
	# Set variables
	col=$1
	shift
	text="$*"
	# Set a to console color code
	case $col in
	 'black'  ) a='[0;30m' ;;
	 'blue'   ) a='[0;34m' ;;
	 'green'  ) a='[0;32m' ;;
	 'cyan'   ) a='[0;36m' ;;
	 'red'    ) a='[0;31m' ;;
	 'purple' ) a='[0;35m' ;;
	 'brown'  ) a='[0;33m' ;;
	 'ltgray' ) a='[0;37m' ;;
	 'white'  ) a='[1;30m' ;;
	 'ltblue' ) a='[1;34m' ;;
	 'ltgreen') a='[1;32m' ;;
	 'ltcyan' ) a='[1;36m' ;;
	 'ltred'  ) a='[1;31m' ;;
	 'pink'   ) a='[1;35m' ;;
	 'yellow' ) a='[1;33m' ;;
	 'gray'   ) a='[1;37m' ;;
	esac
	# Display text in designated color, no newline
	echo -en "\033$a$text"
	# If 'b' switch not on, restore color to black
	if [ -n $b ]
	 then
	  echo -en "\033$b"
	fi
	# If 'n' switch on, do not display final newline
	# otherwise output newline
	echo $o
}

###### shows the colors in a kewl way...partially stolen from HH
function colors()
{
       # Display ANSI colours.
    esc="\033["
    echo -e "\t  40\t   41\t   42\t    43\t      44       45\t46\t 47"
    for fore in 30 31 32 33 34 35 36 37; do
        line1="$fore  "
        line2="    "
        for back in 40 41 42 43 44 45 46 47; do
            line1="${line1}${esc}${back};${fore}m Normal  ${esc}0m"
            line2="${line2}${esc}${back};${fore};1m Bold    ${esc}0m"
        done
        echo -e "$line1\n$line2"
    done
    echo ""
    echo "# Example:"
    echo "#"
    echo "# Type a Blinkin TJEENARE in Swedens colours (Yellow on Blue)"
    echo "#"
    echo "#           ESC"
    echo "#            |  CD"
    echo "#            |  | CD2"
    echo "#            |  | | FG"
    echo "#            |  | | |  BG + m"
    echo "#            |  | | |  |         END-CD"
    echo "#            |  | | |  |            |"
    echo "# echo -e '\033[1;5;33;44mTJEENARE\033[0m'"
    echo "#"
    echo "# Sedika Signing off for now ;->"
}

###### displays all 256 possible background colors, using ANSI escape sequences. - used in ABS Guide with permission.
function colors2()
{
	T1=8
	T2=6
	T3=36
	offset=0
	for num1 in {0..7}
	do {
	   for num2 in {0,1}
		  do {
			shownum=`echo "$offset + $T1 * ${num2} + $num1" | bc`
			echo -en "\E[0;48;5;${shownum}m color ${shownum} \E[0m"
			}
		  done
	   echo
	   }
	done
	offset=16
	for num1 in {0..5}
	do {
	   for num2 in {0..5}
		  do {
			for num3 in {0..5}
			    do {
				  shownum=`echo "$offset + $T2 * ${num3} \
				  + $num2 + $T3 * ${num1}" | bc`
				  echo -en "\E[0;48;5;${shownum}m color ${shownum} \E[0m"
				  }
				done
			echo
			}
		  done
	}
	done
	offset=232
	for num1 in {0..23}
	do {
	   shownum=`expr $offset + $num1`
	   echo -en "\E[0;48;5;${shownum}m ${shownum}\E[0m"
	}
	done
	echo
}

###### print all 256 colors for testing TERM or for a quick reference - show numerical values for each of the 256 colors in bash
function colors2nums()
{
	for code in {0..255}; do echo -e "\e[38;05;${code}m $code: Test"; done
}

###### replaces a color in PDF document (useful for removing dark background for printing) - usage:	remove_color input.pdf output.pdf
function uncolorpdf()
{
convert -density 300 "$1" -fill "rgb(255,255,255)" -opaque "rgb(0,0,0)" "$2"
}

####### View daily comics (set on Viewnior as image - viewer...can use 'eog' or whatever instead)
function comics() {
    # xkcd
    XKCD_FILE="/tmp/xkcd"
    wget -q $(curl -s http://xkcd.com/ | sed -n 's/<h3>Image URL.*: \(.*\)<\/h3>/\1/p') -O $XKCD_FILE
    # Geek and Poke
    GAP_FILE="/tmp/geekandpoke"
    wget -q $(lynx --dump 'http://geekandpoke.typepad.com/' | grep '\/.a\/' | grep '\-pi' | head -n 1 | awk '{print $2}') -O $GAP_FILE
    viewnior $XKCD_FILE
    viewnior $GAP_FILE
}

###### Run a command until a specified time - Example: command-timer 04:00
function command-timer() { echo "notify-send TimeToQuit" | at "$@" ; }

###### Run a program on a timer - Example: program-timer 20 viewnior arg1
function program-timer() { perl -e 'alarm shift; exec @ARGV' "$@" & exit; }

####### Computer the speed of two commands
function comp() { # compare the speed of two commands (loop $1 times)
  if [[ $# -ne 3 ]] ; then return 1 ; fi
  echo -n 1
  time for ((i=0;i<$1;i++)) ; do $2 ; done >/dev/null 2>&1
  echo -n 2
  time for ((i=0;i<$1;i++)) ; do $3 ; done >/dev/null 2>&1
}

# Remove text from file1 which is in file2 and store it in an other file			 #
#------------------------------------------////

###### handy if you have file where file1 was the original and you want to remove the original data from your file2 - usage: grep -Fvf nameofinputfile1 nameofinputfile2 > nameofoutputfile
function comparenclean() { grep -Fvf $1 $2 > $3 ; }

###### save lines unique to file2 - if both file1 and file2 are already sorted: comm -13 nameofinputfile1 nameofinputfile2 > nameofoutputfile
function comparenclean_() { comm -13 <(sort $1) <(sort $2) > $3 ; }

####### Compress stuff
function compress_() {
   # Credit goes to: Daenyth
   FILE=$1
   shift
   case $FILE in
      *.tar.bz2) tar cjf $FILE $*  ;;
      *.tar.gz)  tar czf $FILE $*  ;;
      *.tgz)     tar czf $FILE $*  ;;
      *.zip)     zip $FILE $*      ;;
      *.rar)     rar $FILE $*      ;;
      *)         echo "Filetype not recognized" ;;
   esac
}

####### Sets the compression level for file-roller
function compression_level()
{
	echo -n "Please enter the number for the compression level desired:

	(1) very_fast
	(2) fast
	(3) normal
	(4) maximum

	Press 'Enter' for default (default is '3')...

	"
	read COMPRESSION_LEVEL_NUMBER
	# extra blank space
	echo "
	"
	# default
	if [[ -z $COMPRESSION_LEVEL_NUMBER ]] ; then
	# If no COMPRESSION_LEVEL passed, default to '3'
	    COMPRESSION_LEVEL=normal
	fi
	# preset
	if [[ $COMPRESSION_LEVEL_NUMBER = 1 ]] ; then
	    COMPRESSION_LEVEL=very_fast
	fi
	if [[ $COMPRESSION_LEVEL_NUMBER = 2 ]] ; then
	    COMPRESSION_LEVEL=fast
	fi
	if [[ $COMPRESSION_LEVEL_NUMBER = 3 ]] ; then
	    COMPRESSION_LEVEL=normal
	fi
	if [[ $COMPRESSION_LEVEL_NUMBER = 4 ]] ; then
	    COMPRESSION_LEVEL=maximum
	fi

	gconftool-2 --set /apps/file-roller/general/compression_level --type string "$COMPRESSION_LEVEL"
}

####### Convert to avi
function conv2avi() {
    
    if [[ $(which mencoder-mt) != "" ]]; then
    mencoder-mt "$1" -lavdopts threads=8 \
      -ovc xvid -xvidencopts fixed_quant=4 -of avi \
      -oac mp3lame -lameopts vbr=3 \
      -o "$1".avi
    else
    mencoder "$1" -lavdopts \
      -ovc xvid -xvidencopts fixed_quant=4 -of avi \
      -oac mp3lame -lameopts vbr=3 \
      -o "$1".avi
    fi
}

####### Get name of app that created a corefile
function corename()
{
    for file ; do
        echo -n $file : ; gdb --core=$file --batch | head -1
    done
}

######## Count opening and closing braces in a string
function countbraces() { COUNT_OPENING=$(echo $1 | grep -o "(" | wc -l); COUNT_CLOSING=$(echo $1 | grep -o ")" | wc -l); echo Opening: $COUNT_OPENING; echo Closing: $COUNT_CLOSING; }

######## Count files in current directory
function count_files()
{
    case $1 in
	*+h)
	    echo $(($(ls --color=no -1 -la . | grep -v ^l | wc -l)-1))
	;;
	*-h)
	    echo $(($(ls --color=no -1 -l . | grep -v ^l | wc -l)-1))
	;;
	*+d)
	    echo $(($(ls --color=no -1 -la . | grep -v ^- | wc -l)-1))
	;;
	*-d)
	    echo $(($(ls --color=no -1 -l . | grep -v ^- | wc -l)-1))
	;;
	*+f)
	    echo $(($(ls --color=no -1 -la . | grep -v ^d | wc -l)-1))
	;;
	*-f)
	    echo $(($(ls --color=no -1 -l . | grep -v ^d | wc -l)-1))
	;;
	*)
	    echo -e "\n${ewhite}Usage:"
	    echo -e "\n${eorange}count_files${ewhite} | ${egreen}+h ${eiceblue}[count files and folders - include hidden ones] \
	    \n${eorange}count_files${ewhite} | ${egreen}-h ${eiceblue}[count files and folders - exclude hidden ones] \
	    \n${eorange}count_files${ewhite} | ${egreen}+d ${eiceblue}[count folders - include hidden ones] \
	    \n${eorange}count_files${ewhite} | ${egreen}-d ${eiceblue}[count folders - exclude hidden ones] \
	    \n${eorange}count_files${ewhite} | ${egreen}+f ${eiceblue}[count files - include hidden ones] \
	    \n${eorange}count_files${ewhite} | ${egreen}-f ${eiceblue}[count files - exclude hidden ones]\n"
	    tput sgr0
	;;
    esac
}

######## Count files by extension
function count_files_by_ext() { find . -type f | sed -n 's/..*\.//p' | sort -f | uniq -ic ; }

######## Count processes that are running
function count_processes()

{
    case $1 in
	*help )
	    echo -e "\n${ewhite}Usage:"
	    echo -e "\n${eorange}count_processes${ewhite} | ${egreen}! no options !\n"
	    tput sgr0
	;;
	* )
	    procs=$(ps ax | wc -l | awk '{print $1}')
	    if [[ $procs -lt 10 ]]; then
		echo "000$procs"
	    elif [[ $procs -lt 100 ]]; then
		echo "00$procs"
	    elif [[ $procs -lt 1000 ]]; then
		echo "0$procs"
	    fi
	;;
    esac
}

# Copies currently played song in Audacious to selected directory
function cp_mp3_to() { PID=`pidof audacious2`; FILEPATH=`lsof -p $PID| grep mp3| sed s/[^\/]*//`; cp "$FILEPATH" "$1"; }

######## Cp with progress bar (using pv)
function cp_p() {
    if [ `echo "$2" | grep ".*\/$"` ]
    then
	pv "$1" > "$2""$1"
    else
	pv "$1" > "$2"/"$1"
    fi
}

######## Create User List usage: create_user_list
function create_user_list()
{
    local users u
    while IFS=: read -r u _; do
        users+=("$u")
    done
    printf '%s\n' "${users[@]:1}"
}

######### Print a cron formatted time for 2 minutes in - the future (for crontab testing)
function crontest() { date '-d +2 minutes' +'%M %k %d %m *'; }

# Encryption / decryption			 #
#------------------------------------------////

###### do twice to decrypt
function crypt() {
    if [[ -e "$1" ]]; then
	tr a-zA-Z n-za-mN-ZA-M < "$1" > "$1".crypt
	rm -f "$1"
	mv "$1".crypt "$1"
    fi
}

###### basic encrypt / decrypt - example: "encry filename" or "decry filename"
function encry()
{
	gpg -ac --no-options "$1"
}

function decry()
{
	gpg --no-options "$1"
}

###### More advanced encryption / decryption - example: "encrypt filename" or "decrypt filename"
function encrypt()
{
	case $LANG in
	  cs* )
	    err_title="Chyba"
	    err_files="Neoznačen soubor"
	    encrypt="Šifrovat"
	    decrypt="Dešifrovat"
	    file_msg="soubor:"
	    pass_msg="Vložte heslo";;
	  * )
	    err_title="Error"
	    err_files="No file selected"
	    encrypt="Encrypt"
	    decrypt="Decrypt"
	    file_msg="file:"
	    pass_msg="Enter passphrase";;
	esac
	if [ "$1" != "" ]
	then
	  i=1
	  file=`echo "$1" | sed ''$i'!d'`
	  while [ "$file" != "" ]
	  do
	    ext=`echo "$file" | grep [.]gpg$ 2>&1`
	    if [ "$ext" != "" ]
	    then
		 pass_decrypt=`zenity --entry --entry-text "$pass_decrypt" --hide-text --title "$pass_msg" --text "$decrypt $file_msg ${file##*/}" "" 2>&1`
		 if [ "$pass_decrypt" != "" ]
		 then
		   output=${file%.*}
		   echo "$pass_decrypt" | gpg -o "$output" --batch --passphrase-fd 0 -d "$file"
		 fi
	    else
		 pass_encrypt=`zenity --entry --hide-text --entry-text "$pass_encrypt" --title "$pass_msg" --text "$encrypt $file_msg ${file##*/}" "" 2>&1`
		 if [ "$pass_encrypt" != "" ]
		 then
		   echo "$pass_encrypt" | gpg --batch --passphrase-fd 0 --cipher-algo aes256 -c "$file"
		 fi
	    fi
	    i=$(($i+1))
	    file=`echo "$1" | sed ''$i'!d'`
	  done
	else
	  zenity --error --title "$err_title" --text "$err_files"
	fi
}
alias decrypt='encrypt'

###### rot13 ("rotate alphabet 13 places" Caesar-cypher encryption)
function rot13()
{
    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
        echo "Seriously?  You don't know what rot13 does?"
    else
        echo $@ | tr A-Za-z N-ZA-Mn-za-m
    fi
}

###### rot47 ("rotate ASCII characters from '!" to '~' 47 places" Caesar-cypher encryption)
function rot47()
{
    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
        echo "Seriously?  You don't know what rot47 does?"
    else
        echo $@ | tr '!-~' 'P-~!-O'
    fi
}

# Google stuff					 #
#------------------------------------------////

###### convert currencies usage:	currency_convert 1 usd eur - for currency shorthand: http://www.xe.com/currency/
function currency_convert() { wget -qO- "http://www.google.com/finance/converter?a=$1&from=$2&to=$3&hl=es" | sed '/res/!d;s/<[^>]*>//g'; }

###### convert currencies usage:	currency_convert 1 usd eur - for currency shorthand: http://www.xe.com/currency/
function currency_convert_() { curl "http://www.xe.com/wap/2co/convert.cgi?Amount=$1&From=$2&To=$3" -A "Mozilla" -s | sed -n "s/.*>\(.*\) $3<.*/\1/p"; }

###### convert currencies help
function currency_convert_help() {
cat <<EOF
AED - Emirati Dirham
AFN - Afghan Afghani
ALL - Albanian Lek
AMD - Armenian Dram
ANG - Dutch Guilder
AOA - Angolan Kwanza
ARS - Argentine Peso
AUD - Australian Dollar
AWG - Aruban or Dutch Guilder
AZN - Azerbaijani New Manat
BAM - Bosnian Convertible Marka
BBD - Barbadian or Bajan Dollar
BDT - Bangladeshi Taka
BGN - Bulgarian Lev
BHD - Bahraini Dinar
BIF - Burundian Franc
BMD - Bermudian Dollar
BND - Bruneian Dollar
BOB - Bolivian Boliviano
BRL - Brazilian Real
BSD - Bahamian Dollar
BTN - Bhutanese Ngultrum
BWP - Batswana Pula
BYR - Belarusian Ruble
BZD - Belizean Dollar
CAD - Canadian Dollar
CDF - Congolese Franc
CHF - Swiss Franc
CLP - Chilean Peso
CNY - Chinese Yuan Renminbi
COP - Colombian Peso
CRC - Costa Rican Colon
CUC - Cuban Convertible Peso
CUP - Cuban Peso
CVE - Cape Verdean Escudo
CZK - Czech Koruna
DJF - Djiboutian Franc
DKK - Danish Krone
DOP - Dominican Peso
DZD - Algerian Dinar
EEK - Estonian Kroon
EGP - Egyptian Pound
ERN - Eritrean Nakfa
ETB - Ethiopian Birr
EUR - Euro
FJD - Fijian Dollar
FKP - Falkland Island Pound
GBP - British Pound
GEL - Georgian Lari
GGP - Guernsey Pound
GHS - Ghanaian Cedi
GIP - Gibraltar Pound
GMD - Gambian Dalasi
GNF - Guinean Franc
GTQ - Guatemalan Quetzal
GYD - Guyanese Dollar
HKD - Hong Kong Dollar
HNL - Honduran Lempira
HRK - Croatian Kuna
HTG - Haitian Gourde
HUF - Hungarian Forint
IDR - Indonesian Rupiah
ILS - Israeli Shekel
IMP - Isle of Man Pound
INR - Indian Rupee
IQD - Iraqi Dinar
IRR - Iranian Rial
ISK - Icelandic Krona
JEP - Jersey Pound
JMD - Jamaican Dollar
JOD - Jordanian Dinar
JPY - Japanese Yen
KES - Kenyan Shilling
KGS - Kyrgyzstani Som
KHR - Cambodian Riel
KMF - Comoran Franc
KPW - Korean Won
KRW - Korean Won
KWD - Kuwaiti Dinar
KYD - Caymanian Dollar
KZT - Kazakhstani Tenge
LAK - Lao or Laotian Kip
LBP - Lebanese Pound
LKR - Sri Lankan Rupee
LRD - Liberian Dollar
LSL - Basotho Loti
LTL - Lithuanian Litas
LVL - Latvian Lat
LYD - Libyan Dinar
MAD - Moroccan Dirham
MDL - Moldovan Leu
MGA - Malagasy Ariary
MKD - Macedonian Denar
MMK - Burmese Kyat
MNT - Mongolian Tughrik
MOP - Macau Pataca
MRO - Mauritian Ouguiya
MUR - Mauritian Rupee
MVR - Maldivian Rufiyaa
MWK - Malawian Kwacha
MXN - Mexican Peso
MYR - Malaysian Ringgit
MZN - Mozambican Metical
NAD - Namibian Dollar
NGN - Nigerian Naira
NIO - Nicaraguan Cordoba
NOK - Norwegian Krone
NPR - Nepalese Rupee
NZD - New Zealand Dollar
OMR - Omani Rial
PAB - Panamanian Balboa
PEN - Peruvian Nuevo Sol
PGK - Papua New Guinean Kina
PHP - Philippine Peso
PKR - Pakistani Rupee
PLN - Polish Zloty
PYG - Paraguayan Guarani
QAR - Qatari Riyal
RON - Romanian New Leu
RSD - Serbian Dinar
RUB - Russian Ruble
RWF - Rwandan Franc
SAR - Saudi or Saudi Arabian Riyal
SBD - Solomon Islander Dollar
SCR - Seychellois Rupee
SDG - Sudanese Pound
SEK - Swedish Krona
SGD - Singapore Dollar
SHP - Saint Helenian Pound
SLL - Sierra Leonean Leone
SOS - Somali Shilling
SPL - Seborgan Luigino
SRD - Surinamese Dollar
STD - Sao Tomean Dobra
SVC - Salvadoran Colon
SYP - Syrian Pound
SZL - Swazi Lilangeni
THB - Thai Baht
TJS - Tajikistani Somoni
TMT - Turkmenistani Manat
TND - Tunisian Dinar
TOP - Tongan Pa'anga
TRY - Turkish Lira
TTD - Trinidadian Dollar
TVD - Tuvaluan Dollar
TWD - Taiwan New Dollar
TZS - Tanzanian Shilling
UAH - Ukrainian Hryvna
UGX - Ugandan Shilling
USD - US Dollar
UYU - Uruguayan Peso
UZS - Uzbekistani Som
VEF - Venezuelan Bolivar Fuerte
VND - Vietnamese Dong
VUV - Ni-Vanuatu Vatu
WST - Samoan Tala
XAF - Central African CFA Franc BEAC
XCD - East Caribbean Dollar
XDR - IMF Special Drawing Rights
XOF - CFA Franc
XPF - CFP Franc
YER - Yemeni Rial
ZAR - South African Rand
ZMK - Zambian Kwacha
ZWD - Zimbabwean Dollar
EOF
}

###### define a word - USAGE: define dog
function define() {
	  local LNG=$(echo $LANG | cut -d '_' -f 1)
	  local CHARSET=$(echo $LANG | cut -d '.' -f 2)
	  lynx -accept_all_cookies -dump -hiddenlinks=ignore -nonumbers -assume_charset="$CHARSET" -display_charset="$CHARSET" "http://www.google.com/search?hl=${LNG}&q=define%3A+${1}&btnG=Google+Search" | grep -m 5 -C 2 -A 5 -w "*" > /tmp/define
	  if [ ! -s /tmp/define ]; then
	    echo "Sorry, google doesn't know this one..."
	    rm -f /tmp/define
	    return 1
	  else
	    cat /tmp/define | grep -v Search
	    echo ""
	  fi
	  rm -f /tmp/define
	  return 0
}

###### detect language of a string
function detectlanguage() { curl -s "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=$@" | sed 's/{"responseData": {"language":"\([^"]*\)".*/\1\n/'; }

###### find a location's coordinates - usage:	findlocation "Las Vegas, Nevada" = coordinates: [ -115.1728160, 36.1146460, 0 ]
function findlocation() { place=`echo $1 | sed 's/ /%20/g'` ; curl -s "http://maps.google.com/maps/geo?output=json&oe=utf-8&q=$place" | grep -e "address" -e "coordinates" | sed -e 's/^ *//' -e 's/"//g' -e 's/address/Full Address/';}

###### your GeoIP location on Google Maps
function geoipme()
{
	curl -s http://geoiplookup.wikimedia.org/|awk -F, '{print $3,$4}'|awk -F'"' '{print "http://maps.google.com/maps?q="$4 "," $8}'
}

###### Google search (example: google dog)
function google() {
	firefox "http://www.google.com/search?&num=100&q=${@}" &
}

###### Google chart
function google_chart()
{
	wget -O chart.png 'http://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World'
}

###### Google-Fonts.sh - Google search (example: google dog) Descripton: For those who want an extremely easy method to download and install the entire Google font repository.
function google-fonts() {
	###### Installation of Mercurial Needed for Downloading of Fonts ######
	sudo apt-get install mercurial
	###### Setting of Default Directories ######
	_hgroot="https://googlefontdirectory.googlecode.com/hg/"
	_hgrepo="googlefontdirectory"
	_hgoutdir="google-fonts"
	###### Google Font Choice Decision ######
	echo "
	"
	echo -n "What do you want to do with the fonts from Google
	once they are downloaded?:

	(1)  Download Only (and keep all fonts in a single folder)
	(2)  Download Only (and keep all fonts in separate folders (pure hg copy))
	(3)  Download and Install

	Press 'Enter' for default (default is '1')...

	"
	read GOOGLE_FONT_CHOICE
	###### Actual Downloading of the Google Fonts ######
	if [ ! -d $HOME/$_hgrepo ] ; then
	echo "
	"
	echo "Connecting to Mercurial server...."
	if [ -d $HOME/$_hgrepo ] ; then
	    cd $HOME/$_hgrepo
	    hg pull -u || return 1
	    echo "The local files have been updated."
	    cd ..
	else
	    hg clone $_hgroot $HOME/$_hgrepo || return 1
	fi
	echo "Mercurial checkout done or server timeout"
	echo "
	"
	else
	echo "The directory $HOME/$_hgrepo already exists."
	echo ""
	echo "No need to redownload all of the Google fonts."
	fi
	###### Google Font Choice Selection ######
	###### default
	if [[ -z $GOOGLE_FONT_CHOICE ]] ; then
	    # If no file passed, default to 1
	    mkdir -p $HOME/$_hgoutdir/
	    find $HOME/$_hgrepo/ -name "*.ttf"|xargs -I{} bash -c "cp -rf \"{}\" $HOME/$_hgoutdir/"
	    rm -rf $HOME/$_hgrepo/
	fi
	###### preset
	if [[ $GOOGLE_FONT_CHOICE = 1 ]] ; then
	    mkdir -p $HOME/$_hgoutdir/
	    find $HOME/$_hgrepo/ -name "*.ttf"|xargs -I{} bash -c "cp -rf \"{}\" $HOME/$_hgoutdir/"
	    rm -rf $HOME/$_hgrepo/
	fi
	if [[ $GOOGLE_FONT_CHOICE = 2 ]] ; then
	    mv $HOME/$_hgrepo/ $HOME/$_hgoutdir/
	fi
	if [[ $GOOGLE_FONT_CHOICE = 3 ]] ; then
	    sudo mkdir -p /usr/share/fonts/truetype/google-fonts/
	    find $HOME/$_hgrepo/ -name "*.ttf" -exec sudo install -m644 {} /usr/share/fonts/truetype/google-fonts/ \; || return 1
	    fc-cache -f > /dev/null
	    rm -rf $HOME/$_hgrepo/
	fi
	###### Wrap Up ######
	echo "
	"
	echo "done."
	echo "
	"
	read -sn 1 -p "You have finished downloading/installing all the Google Fonts currently available. Press any key to finish...
	"
}

###### get Google PageRank
function pagerank()
{
	curl pagerank.bz/$1
}

###### Google text-to-speech in mp3/wav format
function say() { mplayer -user-agent Mozilla "http://translate.google.com/translate_tts?tl=en&q=$(echo $* | sed 's#\ #\+#g')" > /dev/null 2>&1 ; }

function say_()
{
	# Saironiq's bash script
	# Usage: say_ en lol # says "lol" in english ; somecommand | say_ fr - # read text to say from a pipe
	# requires madplay: sudo apt-get install madplay
	lang=$1
	shift
	if [ "$1" = "-" ]
	then
	  read text
	  echo $text
	else
	  text=$*
	fi
	len=`expr length "$text"`
	if [ -z "$text" ] ; then
		   echo "Please specify string to translate (up to 100 characters incl.)."
		   exit 4
	elif [ "$len" -gt "100" ] ; then
		   echo "Can't translate more than 100 characters at once! (entered $len)"
		   exit 2
	fi
	wget -qU Mozilla -O - "http://translate.google.com/translate_tts?tl=$lang&q=$text" | madplay -Q -o wave:- - | aplay -q -
}

###### translate a word using Google - usage: translate <phrase> <output-language> - example: translate "hello" es = hola (will auto-detect source language) - for a list of language codes: http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
function translate() { wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=%7C${2:-en}" | sed 's/.*{"translatedText":"\([^"]*\)".*/\1\n/'; }
function translate_help() {
cat <<EOF
Language	ISO
(Afan) Oromo	om
Abkhazian	ab
Afar		aa
Afrikaans	af
Albanian	sq
Amharic		am
Arabic		ar
Armenian	hy
Assamese	as
Aymara		ay
Azerbaijani	az
Bashkir		ba
Basque		eu
Bengali		bn
Bhutani		dz
Bihari		bh
Bislama		bi
Breton		br
Bulgarian	bg
Burmese		my
Byelorussian	be
Cambodian	km
Catalan		ca
Chinese		zh
Corsican	co
Croatian	hr
Czech		cs
Danish		da
Dutch		nl
English		en
Esperanto	eo
Estonian	et
Faeroese	fo
Fiji		fj
Finnish		fi
French		fr
Frisian		fy
Galician	gl
Georgian	ka
German		de
Greek		el
Greenlandic	kl
Guarani		gn
Gujarati	gu
Hausa		ha
Hebrew 		he
(former iw)
Hindi		hi
Hungarian	hu
Icelandic	is
Indonesian 	id
(former in)
Interlingua	ia
Interlingue	ie
Inupiak		ik
Inuktitut 	iu
(Eskimo)
Irish		ga
Italian		it
Japanese	ja
Javanese	jw
Kannada		kn
Kashmiri	ks
Kazakh		kk
Kinyarwanda	rw
Kirghiz		ky
Kirundi		rn
Korean		ko
Kurdish		ku
Laothian	lo
Latin		la
Latvian, 	lv
Lettish
Lingala		ln
Lithuanian	lt
Macedonian	mk
Malagasy	mg
Malay		ms
Malayalam	ml
Maltese		mt
Maori		mi
Marathi		mr
Moldavian	mo
Mongolian	mn
Nauru		na
Nepali		ne
Norwegian	no
Occitan		oc
Oriya		or
Pashto, Pushto	ps
Persian		fa
Polish		pl
Portuguese	pt
Punjabi		pa
Quechua		qu
Rhaeto-Romance	rm
Romanian	ro
Russian		ru
Samoan		sm
Sangro		sg
Sanskrit	sa
Scots Gaelic	gd
Serbian		sr
Serbo-Croatian	sh
Sesotho		st
Setswana	tn
Shona		sn
Sindhi		sd
Singhalese	si
Siswati		ss
Slovak		sk
Slovenian	sl
Somali		so
Spanish		es
Sudanese	su
Swahili		sw
Swedish		sv
Tagalog		tl
Tajik		tg
Tamil		ta
Tatar		tt
Tegulu		te
Thai		th
Tibetan		bo
Tigrinya	ti
Tonga		to
Tsonga		ts
Turkish		tr
Turkmen		tk
Twi		tw
Uigur		ug
Ukrainian	uk
Urdu		ur
Uzbek		uz
Vietnamese	vi
Volapuk		vo
Welch		cy
Wolof		wo
Xhosa		xh
Yiddish 	yi
(former ji)
Yoruba		yo
Zhuang		za
Zulu		zu
EOF
}

###### Cut last n lines in file, 10 by default
function cuttail()
{
    nlines=${2:-10}
    sed -n -e :a -e "1,${nlines}!{P;N;D;};N;ba" $1
}

######  Continuously print string as if being entered  from the keyboard
function cycle() { while :;do((i++));echo -n "${3:$(($i%${#3})):1}";sleep .$(($RANDOM%$2+$1));done;}

######  Super stealth background launch
function daemon()
{
    (exec "$@" >&/dev/null &)
}

###### Shows what processes need to be restarted after system upgrade
function deadlib() { lsof | grep 'DEL.*lib' | cut -f 1 -d ' ' | sort -u; }

######  Show dead links
function deadlink() {
    
    find -L -type l
}

# Stuff for easy debian package extracting, making, remaking, and uploading
#------------------------------------------////

###### deb extraction- extracts a deb file & organizes for easy deb manipulation and repacking using "debremaker"
function debextract()
{
    read -sn 1 -p "Press any key to continue...
"
    # Set IFS so that it won't consider spaces as entry separators.  Without this, spaces in file/folder names can make the loop go wacky.
    IFS=$'\n'
    NEWDIRNAME=${1%.*}
    FILENAME=${1##*/}
    NAME=${1##*/.*}
    mkdir "$NEWDIRNAME"
    cp -fv -R "$1" "$NEWDIRNAME"
    cd "$NEWDIRNAME"
    ar vx "$FILENAME"
    rm -fv -R "$FILENAME"
    for FILE in *.tar.gz; do tar xvpf $FILE; done
    for FILE in *.tar.lzma; do tar xvpf $FILE; done
    rm -fv -R "control.tar.gz"
    rm -fv -R "data.tar.gz"
    rm -fv -R "data.tar.lzma"
    rm -fv -R "debian-binary"
    mkdir "DEBIAN"
    mv -fv "changelog" "DEBIAN"
    mv -fv "config" "DEBIAN"
    mv -fv "conffiles" "DEBIAN"
    mv -fv "control" "DEBIAN"
    mv -fv "copyright" "DEBIAN"
    mv -fv "postinst" "DEBIAN"
    mv -fv "preinst" "DEBIAN"
    mv -fv "prerm" "DEBIAN"
    mv -fv "postrm" "DEBIAN"
    mv -fv "rules" "DEBIAN"
    mv -fv "shlibs" "DEBIAN"
    mv -fv "templates" "DEBIAN"
    mv -fv "triggers" "DEBIAN"
    mv -fv ".svn" "DEBIAN"
    rm -fv -R "md5sums"
    echo "Finished Successfully"
}

###### deb remaking- easily remakes a debian file after "debextract" (not authentically or correct according to Launchpad standards)
function debremaker()
{
    read -sn 1 -p "Make sure you have this function directed to the original debian file (previously extracted from and made into a folder with \"debextract\"; otherwise, it will fail (Note: This will take a minute): Press any key to continue...
"
    # Set IFS so that it won't consider spaces as entry separators.  Without this, spaces in file/folder names can make the loop go wacky.
    IFS=$'\n'
    NEWDIRNAME=${1%.*}
    FILENAME=${1##*/}
    NAME=${1##*/.*}
    cd "$NEWDIRNAME"
    rm -fv -R "$1"
    find . -type f ! -regex '.*\.hg.*' ! -regex '.*?debian-binary.*' ! -regex '.*?DEBIAN.*' -printf '%P ' | xargs md5sum > DEBIAN/md5sums
    cd ..
    dpkg-deb -b "$NEWDIRNAME"
    rm -rf "$NEWDIRNAME"
    echo "Finished Successfully"
}

####### Download a web page and show info on what took time
function debug_http() { /usr/bin/curl $@ -o /dev/null -w "dns: %{time_namelookup} connect: %{time_connect} pretransfer: %{time_pretransfer} starttransfer: %{time_starttransfer} total: %{time_total}\n" ; }

####### Defragmentation of selected files/folder (use at your own risk) & fragmentation-checking#
function defrag()
{
	cd "$1"
	read -sn 1 -p "Warning! Pressing enter will defrag the current directory. Close this now if you are in the wrong directory and/or you forgot to type the name of the directory you wish to defrag after \"defrag\": Press any key to continue...
	"
	read -sn 1 -p "I'm serious. It's now or never...: Press any key to continue...
	"
cat > "/tmp/defrag.sh" <<"End-of-message"
#!/bin/bash
# defrag v0.08 by Con Kolivas <[email protected]
# Braindead fs-agnostic defrag to rewrite files in order largest to smallest
# Run this in the directory you want all the files and subdirectories to be
# reordered. It will only affect one partition. It works best when run twice.
# Are you really crazy enough to be using this? It might blow your data
# into tiny little useless chunks.
trap 'abort' 1 2 15
renice 19 $$ > /dev/null
function abort()
{
    echo -e "\nAborting"
    rm -f tmpfile dirlist
    exit 1
}
function fail()
{
    echo -e "\nFailed"
    abort
}
declare -i filesize=0
declare -i numfiles=0
# The maximum size of a file we can easily cache in ram
declare -i maxsize=$((`awk '/MemTotal/ {print $2}' /proc/meminfo`*1024))
(( maxsize-= `awk '/Mapped/ {print $2}' /proc/meminfo` ))
(( maxsize/= 2))
if [[ -a tmpfile || -a dirlist  ]] ; then
    echo dirlist or tmpfile exists
    exit 1
fi
# Sort in the following order:
# 1) Depth of directory
# 2) Size of directory descending
# 3) Filesize descending
# I made this crap up. It's completely unvalidated.
echo "Creating list of files..."
# stupid script to find max directory depth
find -xdev -type d -printf "%d\n" | sort -n | uniq > dirlist
# sort directories in descending size order
cat dirlist | while read d;
do
    find -xdev -type d -mindepth $d -maxdepth $d -printf "\"%p\"\n" | \
	xargs du -bS --max-depth=0 | \
	sort -k 1,1nr -k 2 |\
	cut -f2 >> tmpfile
    if (( $? )) ; then
	fail
    fi
done
rm -f dirlist
# sort files in descending size order
cat tmpfile | while read d;
do
    find "$d" -xdev -type f -maxdepth 1 -printf "%s\t%p\n" | \
	sort -k 1,1nr | \
	cut -f2 >> dirlist
    if (( $? )) ; then
	fail
    fi
done
rm -f tmpfile
numfiles=`wc -l dirlist | awk '{print $1}'`
echo -e "$numfiles files will be reordered\n"
# copy to temp file, check the file hasn't changed and then overwrite original
cat dirlist | while read i;
do
    (( --numfiles ))
    if [[ ! -f $i ]]; then
	continue
    fi
    # We could be this paranoid but it would slow it down 1000 times
    # if [[ `lsof -f -- "$i"` ]]; then
    # 	echo -e "\n File $i open! Skipping"
    # 	continue
    # fi
    filesize=`find "$i" -printf "%s"`
    # read the file first to cache it in ram if possible
    if (( filesize < maxsize ))
    then
	echo -e "\r $numfiles files left                                                            \c"
	cat "$i" > /dev/null
    else
	echo -e "\r $numfiles files left - Reordering large file sized $filesize ...                \c"
    fi
    datestamp=`find "$i" -printf "%s"`
    cp -a -f "$i" tmpfile
    if (( $? )) ; then
	fail
    fi
    # check the file hasn't been altered since we copied it
    if [[ `find "$i" -printf "%s"` != $datestamp ]] ; then
	continue
    fi
    mv -f tmpfile "$i"
    if (( $? )) ; then
	fail
    fi
done
echo -e "\nSucceeded"
rm -f dirlist
End-of-message
	chmod +x "/tmp/defrag.sh"
	sudo "/tmp/defrag.sh" "$1"
	read -sn 1 -p "When you are finished, press any key to continue...
	"
	rm "/tmp/defrag.sh"
}

###### if run this in your $HOME directory, you will have to change permissions back
function defrag2()
{
	cd "$1"
	read -sn 1 -p "Warning! Pressing enter will defrag the current directory. Close this now if you are in the wrong directory and/or you forgot to type the name of the directory you wish to defrag after \"defrag\": Press any key to continue...
	"
	read -sn 1 -p "I'm serious. It's now or never...: Press any key to continue...
	"
cat > "/tmp/defrag2.sh" <<"End-of-message"
#!/bin/bash
# Creator:	private_lock
# Recursively descend in a folder-structure and recreate every folder on ascending, to ensure it is
# sorted (check with 'ls -lU'). This will defrag the FAT32 file-system but not touch the files.
# count some statistics
directories=0
invalid=0
unreadable=0
# the latest modification date of a file within the given directory
function getMaxDate {
    # read the output of ls (one file per line, sorted for descending modification time)
    ls -1t "$1" | while read line; do
        # "return value" is piped through standard out
        echo "-d $(stat -c %y "$1"/"$line")"
        # stop after first line
        return
    done
}
# expect a single directory as argument
function rewrite {
    # get canonical path
    local canonical="$(readlink -f "$1")"
    if [[ ! -d "$1" || -h "$1" ]]; then
        echo "Skipping symbolic link \"$1\" -> \"$canonical\"!"
        let invalid+=1
        return
    fi
    if [[ ! -d "$1" || -h "$1" ]]; then
        echo \"$canonical\" is not a valid directory!
        let invalid+=1
        return
    fi
    cd "$canonical"
    if [[ $? != 0 ]]; then
        echo Cannot change to directory \"$canonical\"! Skipping ...
        let unreadable+=1
        return
    fi
    echo $canonical
    let directories+=1
    local isEmpty=true
    # recursive descend
    for d in *; do
        if [[ -d "$d" ]]; then
            rewrite "$d"
        fi
        let isEmpty=false
    done
    # ascend to parent of canonical (But don't ascend blindly)
    cd "$canonical"/..
    if [[ $isEmpty == true ]]; then
        # no need to recreate an empty directory, as it's zero entries are always sorted
        return
    fi
    # check for an empty temporary directory-name
    local tempdir="$canonical".bak
    if [[ -e "$tempdir" ]]; then
        # echo $tempdir exits
        local counter=1
        while [[ -e "$tempdir$counter" ]]; do
            # echo ${tempdir}${counter} exits
            let counter+=1
        done
        tempdir="${tempdir}${counter}"
    fi
    # TODO check file-system boundaries (don't move across)
    # rename the current directory
    mv "$canonical" "$tempdir"
    # create a new directory
    mkdir "$canonical"
    # move all the content from the old to the new directory
    # The whole script is build around the side-effect of mv to sort the entries.
    mv "$tempdir"/* "$canonical"
    # check, that the old directory is really empty
    if [[ "$(ls -A "$tempdir")" ]]; then
        echo ERROR: "$tempdir" is not empty!
        exit -2
    fi
    # restore permissions
    chmod --reference="$tempdir" "$canonical"
    # delete the old directory
    rmdir "$tempdir"
    # update the timestamp of the new directory
    # start off with today
    local maxDate=$(date)
    # evaluate the latest modification time of a file within this directory
    # empty directories would be set to now
    touch "$(getMaxDate "$canonical")" "$canonical"
}
# check commandline for help option
for a in "$@"; do
    if [[ ${a} = "-?" || ${a} = "-h"  || ${a} = "--help" ]]; then
        echo -e "\nUsage: folderSort [-?|-h|--help] [directories]\n"
        exit -1
    fi
done
# start processing the directories
if [[ "$#" -eq 0 ]]; then
    # no commandline argument was given -> work on the current directory
    rewrite .
else
    for a in "$@"; do
        rewrite ${a}
    done
fi
echo Processed a total of $directories directories!
if [[ $invalid > 0 ]]; then
    echo Found $invalid invalid directories!
fi
if [[ $unreadable > 0 ]]; then
    echo Found $unreadable directories, that could not be changed into!
fi
exit $(($invalid + $unreadable))
End-of-message
	chmod +x "/tmp/defrag2.sh"
	sudo "/tmp/defrag2.sh" "$1"
	read -sn 1 -p "When you are finished, press any key to continue...
	"
	rm "/tmp/defrag2.sh"
}

###### fragmentation check (basic check, which will generate a percentage of fragmentation)
function fragcheck()
{
	cd "$1"
	read -sn 1 -p "Warning! Pressing enter will do a search for fragmentation in the current directory. Close this now if you are in the wrong directory and/or you forgot to type the name of the directory you wish to do a fragcheck after \"fragcheck\": Press any key to continue...
	"
cat > "/tmp/fragcheck.pl" <<"End-of-message"
#!/usr/bin/perl -w
# Original creator: _droop_
# Updated by: as
# Updated again by: user11
# this script search for frag on a fs
use strict;
# number of files
my $files = 0;
# number of fragment
my $fragments = 0;
# number of fragmented files
my $fragfiles = 0;
my $verbose;
if ($ARGV[0] eq '-v') { shift @ARGV; $verbose++; }
open (REPORT, "find " . $ARGV[0] . " -xdev -type f -print0 | xargs -0 filefrag |");
while (defined (my $res = <REPORT>)) {
        if ($res =~ m/.*:\s+(\d+) extents? found$/) {
                my $fragment = $1;
                $fragments += $fragment;
                if ($fragment > 1) {
                        $fragfiles++;
                }
                $files++;
        } else {
                print ("Failed to parse: $res\n");
        }
}
close (REPORT);
if ($verbose) {
   print "Total files:      $files\n";
   print "Fragmented files: $fragfiles\n";
   print "Fragments:        $fragments\n";
}
sub round($$) {
   my $v = shift; # value
   my $p = shift; # rouding divisor (1 for '123', 10 for '123.4', 100 for '123.45')
   return int($v * $p) / $p;
}
print ( $fragfiles / $files * 100 . "% non contiguous files, " . $fragments / $files . " average fragments.\n");
End-of-message
	chmod +x "/tmp/fragcheck.pl"
	sudo "/tmp/fragcheck.pl" "$1"
	read -sn 1 -p "When you are finished, press any key to continue...
	"
	rm "/tmp/fragcheck.pl"
}

###### will generate a percentage for fragmentation and several other things: takes longer than first one
function fragcheck2()
{
	cd "$1"
	read -sn 1 -p "Warning! Pressing enter will do a search for fragmentation in the current directory. Close this now if you are in the wrong directory and/or you forgot to type the name of the directory you wish to do a fragcheck after \"fragcheck\": Press any key to continue...
	"
cat > "/tmp/fragcheck2.pl" <<"End-of-message"
#! /usr/bin/perl -w
#  Original creator: _droop_
#  Updated by: as
#  Updated again by: c07
use strict;
@ARGV >= 1 && @ARGV <= 2 or die "usage: $0 <dir> [<block size in KB>]";
$/= "\0";
my ($files, $blocks, $fragments, $frag, $fragblocks, $multi, $empty)= (0) x 7;
my $dir= shift;
my $blocksize= (shift || 4) + 0;
print qq|scanning "$dir", using block size $blocksize KB ...\n|;
open my $find, "-|", "find", $dir, qw"-xdev -type f -print0";
while ( my $file= <$find> ) {
  { open my $fh, "-|", "filefrag", $file; $_= <$fh> }
  /:\s+(\d+) extents? found/ or (print qq|"$_"?\n|), next;
  my $n= $1 + 0;
  { open my $fh, "-|", "ls", "-sk", $file; $_= <$fh> }
  /^(\d+)\s/ or (print qq|"$_" (ls)?\n|), next;
  my $s= $1 / $blocksize;
  ++$files;
  $s or ++$empty, next;
  $blocks += $s;
  $fragments += $n;
  ++$frag, $fragblocks += $s if $n > 1;
  ++$multi if $s > 1;
}
my $single= $files - $multi - $empty;
my $nonfrag= $files - $frag - $empty;
if ( ! $files ) { print "no files\n" }
else {
  printf "$files files, $frag (%.3f %%) fragmented\n", 100 * $frag / $files;
  if ( ! $multi ) { print "no multi-block files\n" }
  else {
    printf "$multi multi-block files, %.3f %% fragmented\n",
      100 * $frag / $multi;
  }
  print "$blocks blocks, $fragments fragments, $empty empty files\n";
  if ( $fragments ) {
    printf "average %.3f fragments per file, %.3f blocks per fragment,\n",
      $fragments / $files, $blocks / $fragments;
    if ( $multi ) {
      printf "%.3f fragments per multi-block file, %.3f blocks each,\n",
        ($fragments - $single) / $multi,
        ($blocks - $single) / ($fragments - $single);
      if ( $frag ) {
        printf "%.3f fragments per fragmented file, %.3f blocks each\n",
        ($fragments - $nonfrag) / $frag,
        $fragblocks / ($fragments - $nonfrag);
} } } }
End-of-message
	chmod +x "/tmp/fragcheck2.pl"
	sudo "/tmp/fragcheck2.pl" "$1"
	read -sn 1 -p "When you are finished, press any key to continue...
	"
	rm "/tmp/fragcheck2.pl"
}

####### Del function
function del()
{
    mv "$@" "/${HOME}/.local/share/Trash/files/"
}

###### Delete function
function delete() {
    DIR=$1
    shift
    for i in $*; do
        if [ -f $DIR/$i ]; then
            rm $DIR/$i
        fi
    done
}

# Lookup a word with dict.org
#------------------------------------------////

###### define "whatever"
function dic() { curl dict://dict.org/d:"$@" ; }

###### find matches of $1, with optional strat $2 and optional db $3
function ref()
{
    if [[ -z $3 ]]; then
        curl dict://dict.org/m:${1}:english:${2};
    else
        curl dict://dict.org/m:${1}:${3}:${2};
    fi
}

###### look in Webster
function webster() { curl dict://dict.org/d:${1}:web1913; }

###### look in WordNet
function wordnet() { curl dict://dict.org/d:${1}:wn; }

####### Shell function to exit script with error in exit status and print optional message to stderr
function die() { result=$1;shift;[ -n "$*" ]&&printf "%s\n" "$*" >&2;exit $result;}

####### Diffs two xml files by formatting them first - using xmllint and then invoking diff - usage: diffxml XMLFile1 XMLFile2
function diffxml() { diff -wb <(xmllint --format "$1") <(xmllint --format "$2"); }

######## Dirsize - finds directory sizes and lists them for the current directory
function dirsize()
{
	du -shx * .[a-zA-Z0-9_]* 2> /dev/null | \
	egrep '^ *[0-9.]*[MG]' | sort -n > /tmp/list
	egrep '^ *[0-9.]*M' /tmp/list
	egrep '^ *[0-9.]*G' /tmp/list
	rm /tmp/list
}

# Display off (Turns the display off)		 #
#------------------------------------------////

###### turns the display off and will stay off until any key/cursor is touched
function display-off()
{
cat > "/tmp/display-off.py" <<"End-of-message"
#!/usr/bin/python
import time
import subprocess
from Xlib import X
from Xlib.display import Display
display = Display(':0')
root = display.screen().root
root.grab_pointer(True,
        X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,
        X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime)
root.grab_keyboard(True,
        X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)
subprocess.call('xset dpms force off'.split())
p = subprocess.Popen('gnome-screensaver-command -i'.split())
time.sleep(1)
while True:
    print display.next_event()
    p.terminate()
    break
End-of-message
chmod +x "/tmp/display-off.py"
"/tmp/display-off.py"
/bin/rm "/tmp/display-off.py"
}

###### turns the display off and will stay off until this command is run again or cancelled, even after key/cursor is touched
function display-offed() { LF=/tmp/screen-lock; if [ -f $LF ]; then /bin/rm $LF; else touch $LF; sleep .5; while [ -f  $LF ]; do xset dpms force off; sleep 2; done; fi ; }

###### turns the display off and will stay off until any key/cursor is touched Display off with login (Turns the display off)
function display-oft()
{
cat > "/tmp/display-oft.py" <<"End-of-message"
#!/usr/bin/python
import time
import subprocess
from Xlib import X
from Xlib.display import Display
display = Display(':0')
root = display.screen().root
root.grab_pointer(True,
        X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,
        X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime)
root.grab_keyboard(True,
        X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)
subprocess.call('xset dpms force off'.split())
p = subprocess.Popen('gnome-screensaver-command -i'.split())
time.sleep(1)
while True:
    print display.next_event()
    p.terminate()
    subprocess.Popen('gnome-screensaver-command -l'.split())
    break
End-of-message
chmod +x "/tmp/display-oft.py"
"/tmp/display-oft.py"
/bin/rm "/tmp/display-oft.py"
}

###### Change to specified pkg's documentation dir and display the files - Usage: doc
function doc() {
    pushd "/usr/share/doc/$1" && ls
}

####### Lists unique IPs currently connected to logged-in system & how many concurrent connections each IP has
function doscheck()
{
	"netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n"
}

####### Symlinks all hidden files in a directory to the same names without the dot
function dot_ln()
{
    for file in `/bin/ls -a | /bin/egrep "^\.[^./]"` ; do
        if [[ "$1" == "-f" ]] ; then
            /bin/ln -svif $file ${file:1}
        else
            /bin/ln -svi $file ${file:1}
        fi
    done
}

####### Site down for everyone or just me?
function downforme() {
    RED='\e[1;31m'
    GREEN='\e[1;32m'
    YELLOW='\e[1;33m'
    NC='\e[0m'
    if [ $# = 0 ]
    then
	echo -e "${YELLOW}usage:${NC} downforme website_url"
    else
	JUSTYOUARRAY=(`lynx -dump http://downforeveryoneorjustme.com/$1 | grep -o "It's just you"`)
	if [ ${#JUSTYOUARRAY} != 0 ]
	then
	    echo -e "${RED}It's just you. \n${NC}$1 is up."
	else
	    echo -e "${GREEN}It's not just you! \n${NC}$1 looks down from here."
	fi
    fi
}

####### Size of directories in MB
function ds()
{
    echo "size of directories in MB"
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        echo "you did not specify a directy, using pwd"
        DIR=$(pwd)
        find $DIR -maxdepth 1 -type d -exec du -sm \{\} \; | sort -nr
    else
        find $1 -maxdepth 1 -type d -exec du -sm \{\} \; | sort -nr
    fi
}

####### Size of items in directory
function dubigf() {
  du -sh * | awk '/[[:space:]]*[[:digit:]]+,*[[:digit:]]*G/' | sort -nr
  du -sh * | awk '/[[:space:]]*[[:digit:]]+,*[[:digit:]]*M/' | sort -nr
}

###### # Find duplicate/non-duplicate lines in series of files or in stdin	- find duplicate lines
function dups() { sort "$@" | uniq -d; }

###### find duplicate lines, keep just 1 of them, and output to txt file
function dupscleaner() { sort "$@" | uniq -d > dupscleaned.txt; }

###### find duplicate lines, remove all non-duplicate lines and output to txt file
function dupsonly() { sort "$@" | uniq -D > dupsonly.txt; }

###### find non-duplicate lines
function nondups() { sort "$@" | uniq -u; }

###### find duplicate lines, remove all of them, keeping just non-duplicate lines and output to txt file
function nondupsonly() { sort "$@" | uniq -u > nondupsonly.txt; }

###### View portage changelog for specified package - $1 = package name
function echange() {
    PACKAGE="$(eix -e --only-names $1)"
    if [ "$PACKAGE" != "" ]; then
        view /usr/portage/$PACKAGE/ChangeLog
    fi
}

# Directory operations: editd, flipd, popd, printd, pushd, rotd, swapd			 #
#------------------------------------------////

###### Edit directory stack
function editd() {
  export EDITDNO=$((${EDITDNO:=0} + 1))
  typeset FiLe=/tmp/`basename -- $0`$$.${EDITDNO}
  printd >${FiLe}
  ${EDITOR} ${FiLe}
  DS=`while read ea; do echo -n "$ea:"; done <${FiLe}`
  rm -f ${FiLe}
}

###### flip back-and-forth between current dir and top of stack (like "cd -")
function flipd() {
  if [ "$DS" ]
  then
    cd "${DS%%:*}"
    export DS="$OLDPWD:${DS#*:}"
  else
    echo "$0: empty directory stack" >&2
  fi
}

###### pop top dir off stack and cd to it
function popd() {
  if [ "$DS" ]
  then
    cd "${DS%%:*}"
    export DS="${DS#*:}"
  else
    echo "$0: empty directory stack" >&2
  fi
}

###### Print directory stack
function printd() {
  ( IFS=:; for each in $DS; do echo $each; done; )
}

###### Change to new dir, pushing current onto stack
function pushd() {
  export DS="$PWD:$DS"
  if [ -n "$1" ]; then cd "$1"; else cd; fi || export DS="${DS#*:}"
}

###### rotate thru directory stack (from bottom to top)
function rotd() {
  if [ "$DS" ]
  then
    typeset DSr="${DS%:*:}"
    [ "${DSr}" = "${DS}" ] || export DS="${DS##${DSr}:}$DSr:"
    flipd
  else
    echo "$0: directory stack is empty" >&2
  fi
}

###### swap top two dir stack entries
function swapd() {
  typeset DSr="${DS#*:}"
  if [ "$DSr" ]
  then
    export DS="${DSr%%:*}:${DS%%:*}:${DSr#*:}"
  else
    echo "$0: less than two on directory stack" >&2
  fi
}

if [ ! -f ${HOME}/.lastdir ];then
    cat > ${HOME}/.lastdir
fi

alias lastd="cd $(cat ~/.lastdir)"         # change to last dir at 'bye'

###### save current dir for lastd on exit if not $HOME
alias saved='[ ${PWD} != ${HOME} ] && pwd >~/.lastdir; [ -n "${DS}" ] && echo "${DS}" >~/.dirstak'

###### get dir stack back on login
[ -s ${HOME}/.dirstak ] && export DS=`cat ${HOME}/.dirstak`

###### Download ed2k file
function ed2k()
{
	wget -q -O - "$1" | grep "ed2k://" |  sed -e 's/^.*=//g;s/..$//g'
}

####### Edit your history file
function eh() { history -a ; vi ~/.bash_history ; history -r ; }

####### Elements database
function ele() {
    dict -d elements $@
}

####### Show empty files in the directed directory
function empty() {
    
    find "$1" -empty
}

####### Surround lines with quotes (useful in pipes)
function enquote() { /usr/bin/sed 's/^/"/;s/$/"/' ; }

####### Determining the meaning of error codes
function err()
{
    grep --recursive --color=auto --recursive -- "$@" /usr/include/*/errno.h
    if [ "${?}" != 0 ]; then
        echo "Not found."
    fi
}

####### View latest installable portage ebuild for	specified package - $1 = package name
function eview() {
    FILE=$(equery which $1)
    if [ -f "$FILE" ]; then
        view $FILE
    fi
}

####### Exchange stuff from two places
function exchange()

{
    typeset temp
    SAVE=$IFS
    IFS=''
    eval $(echo "temp=\"\$$1\"")
    eval $(echo "$1=\"\$$2\"")
    eval $(echo "$2=\"$temp\"")
    IFS=$SAVE
}

####### URLs ... -  expand shortened URLs
function expandurl() { curl -sIL $1 2>&1 | awk '/^Location/ {print $2}' | tail -n1; }

###### short URLs with is.gd
function isgd() { /usr/bin/wget -qO - "http://is.gd/create.php?format=simple&url=$1" ;}

###### resolve short URLs
function resolve() { curl -Is $1 | sed -n 's/^Location: //p'; }

####### CIA world fact book
function fact() {
    dict -d world02 $@
}

####### Passwording - fake name and pass
function fakepass()
{
  local l=8
  [ -n "$1" ] && l=$1
  dd if=/dev/urandom count=1 2> /dev/null | uuencode -m - | head -n 2 | tail -n 1 | cut -c $l
}
alias fakename='nc koeln.ccc.de 23 | cut -d \  -f 4,5'

###### password file
function pw()
{
    if [ "$OS" = "Linux" ]; then
        gpg $HOME/priv.asc
        vi -n $HOME/priv
        gpg -ea $HOME/priv
        wipe -f $HOME/priv
    elif [ "$OS" = "Darwin" ]; then
        gpg $HOME/Documents/priv.asc
        vi -n $HOME/Documents/priv
        gpg -ea $HOME/Documents/priv
        srm -f $HOME/Documents/priv
    fi
}

###### generate a random password - $1 = number of characters; defaults to 32 - $2 = include special characters; 1 = yes, 0 = no; defaults to 1
function randompw() {
    if [[ $2 == "!" ]]; then
	echo $(cat /dev/urandom | tr -cd '[:graph:]' | head -c ${1:-32})
    else	echo $(cat /dev/urandom | tr -cd '[:alnum:]' | head -c ${1:-32})
    fi
}

###### generate a random left-hand password
alias randompwl='</dev/urandom tr -dc '12345!@#$%qwertQWERTasdfgASDFGzxcvbZXCVB' | head -c8; echo ""'

###### generate a unique and secure password for every website that you login to
function sitepass() { 
	echo -n "$@" |  md5sum | sha1sum | sha224sum | sha256sum | sha384sum | sha512sum | gzip - | strings -n 1 | tr -d "[:space:]"  | tr -s '[:print:]' | tr '!-~' 'P-~!-O' | rev | cut -b 2-11; history -d $(($HISTCMD-1)); 
}

###### generates a unique and secure password with SALT for every website that you login to
function sitepass2()
{
	salt="this_salt";pass=`echo -n "$@"`;for i in {1..500};do pass=`echo -n $pass$salt|sha512sum`;done;echo$pass|gzip -|strings -n 1|tr -d "[:space:]"|tr -s '[:print:]' |tr '!-~' 'P-~!-O'|rev|cut -b 2-15;history -d $(($HISTCMD-1));
}

###### trunc	password
function trunc_pwd()
{
    case $1 in
	*help )
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}trunc_pwd ${ewhite}|${egreen} ! no options !\n"
	    tput sgr0
	;;
	* )
	    pwdmaxlen=$(get_key pwdmaxlength)
	    trunc_symbol=$(get_key pwdchar)
	    dirchar=$(get_key dirchar)
	    newsepacolor=$(echo $sepacolor | sed -e 's/\\\[//g' -e 's/\\\]//g')
	    newwdircolor=$(echo $wdircolor | sed -e 's/\\\[//g' -e 's/\\\]//g')
	    newpscoloror=$(echo $pscolor | sed -e 's/\\\[//g' -e 's/\\\]//g')
	    if [ ${#PWD} -gt $pwdmaxlen ]; then
		pwdoffset=$(( ${#PWD} - $pwdmaxlen ))
		if [[ $pstyle_supported == true ]]; then
		    xPWD="$newpscoloror${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
		else	xPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
		fi
		if [[ $enabcol == true && $pstyle_supported == true ]]; then
		    newPWD="${xPWD//\//$newsepacolor$dirchar$newwdircolor}"
		else	newPWD="${xPWD//\//$dirchar}"
		fi
	    else
		if [[ $enabcol == true && $pstyle_supported == true ]]; then
		newPWD="${PWD//\//$newsepacolor$dirchar$newwdircolor}"
	    else	newPWD="${PWD//\//$dirchar}"
	    fi
	    fi
	    echo -e $newPWD
	;;
    esac
}

# Find a file(s) ... with pattern $1 in name and Execute $2 on it
function fe() { find . -type f -iname '*'$1'*' -exec "${2:-file}" {} \;  ; }

###### ... under the current directory
function ff() { /usr/bin/find . -name "$@" ; }

###### ... whose name ends with a given string
function ffe() { /usr/bin/find . -name '*'"$@" ; }

###### ... fast find (by filename; uses sh, less and sed)
function ffind() { local a=$1; local b=$2; local c="$a"*/*"$b"*; case $# in [01])echo usage: ff drive string [match-no\(s\)];; 2)printf "%s\n" $c|less -SN;; 3)less $(printf "%s\n" $c|sed -n "$3"p|tr '\n' ' ');; esac; }

###### ... whose name starts with a given string
function ffs() { /usr/bin/find . -name "$@"'*' ; }

###### ... larger than a certain size (in bytes)
function find_larger() { find . -type f -size +${1}c ; }

###### find a file with a pattern in name in the local directory
function fp()
{
    find . -type f -iname '*'$*'*' -ls ;
}

###### find pattern in a set of files and highlight them
function fstr()
{
	    OPTIND=1
	    local case=""
	    local usage="fstr: find string in files.
	Usage: fstr [-i] \"pattern\" [\"filename pattern\"] "
	    while getopts :it opt
	    do
		   case "$opt" in
		   i) case="-i " ;;
		   *) echo "$usage"; return;;
		   esac
	    done
	    shift $(( $OPTIND - 1 ))
	    if [ "$#" -lt 1 ]; then
		   echo "$usage"
		   return;
	    fi
	    local SMSO=$(tput smso)
	    local RMSO=$(tput rmso)
	    find . -type f -name "${2:-*}" -print0 | xargs -0 grep -sn ${case} "$1" 2>&- | \
	sed "s/$1/${SMSO}\0${RMSO}/gI" | more
}

###### searches through the text of all the files in your current directory # http://seanp2k.com/?p=13 # Good for debugging a PHP script you didn't write and can't trackdown where MySQL connect string actually is
function grip() {
	grep -ir "$1" "$PWD"
}

###### ... who is the newest file in a directory
function newest() { find ${1:-\.} -type f |xargs ls -lrt ; }

###### Festival - text-to-speech -> requires festival: sudo apt-get install festival - Usage:	fest "text"
function fest() {
    echo $1 | festival --tts
}

####### Find in file and ( AND relation )  Will search PWD for text files that contain $1 AND $2 AND $3 etc... Actually it does the same as grep word1|grep word2|grep word3 etc, but in a more elegant way.
function ffa() { (($# < 2)) && { echo "usage: ffa pat1 pat2 [...]" >&2; return 1; };awk "/$1/$(printf "&&/%s/" "${@:2}")"'{ print FILENAME ":" $0 }' *; }

####### Alternative for basename using grep to extract file name eg: fileName /path/to/file.ext
function fileName()  { echo "$1"  | grep -o "[^/]*$"; }

####### Extract extention of a file	
function filext() { echo ${1##*.}; }

###### Pick the first program found from a list of alternatives -> used to set environmental variables from list of alternatives depending on what's installed (uses bash setting 'export BROWSER' above) it returns the first program found in the list -> Usage:	export BROWSER=$(find_alternatives chromium-browser google-chrome opera firefox firefox-bin iceweasel konqueror w3m lynx)
function find_alternatives() { for i;do which "$i" >/dev/null && { echo "$i"; return 0;};done;return 1; }

######  Find out the pid of a specified process -> note that the command name can be specified via a regex -> E.g. findPid '/d$/' finds pids of all processes with names ending in 'd' - Without the 'sudo' it will only find processes of the current user
function findPid() { sudo /usr/sbin/lsof -t -c "$@" ; }

######## Search for a word in the Unix word list
function findword() { /usr/bin/grep ^"$@"$ /usr/share/dict/words ; }

####### Recursively fix dir/file permissions on agiven directory
function fix() {
	if [ -d $1 ]; then
	find $1 -type d -exec chmod 755 {} \;
	find $1 -type f -exec chmod 644 {} \;
	else
	echo "$1 is not a directory."
	fi
}

####### Edit files in place to ensure Unix linendings
function fixlines() { /usr/bin/perl -pi~ -e 's/\r\n?/\n/g' "$@" ; }

###### Fix eclipse mistakes with tabs - Sources files should never use TABs for indenting because they may looks different in different editors. For example there popular Eclipse IDE use a the non default tab size 4
function fix-tabs() { expand -t 4 "$1" > "$1.expanded"; mv -f "$1.expanded" "$1"; }

###### Inserts a flag with the specified content - Usage: flag "comment" - If no comment, inserts the date.
function flag() {
    if [ "$1" == "" ];
    then
        echo -e  "\e[0;31m[====== " `date +"%A %e %B %Y"`, `date +"%H"`h`date +"%M"` " ======]\e[0m"
    else
        echo -e  "\e[0;31m[====== " $@ " ======]\e[0m"
    fi
}

###### Inserts a flag and executes the command - Example: flagcommand ls
function flagcommand() {
    if [ "$1" == "" ];
    then
        return
    else
        flag $@
        $@
    fi
}

###### Flight status - track flights from the command line (requires html2text: sudo apt-get install html2text)
function flight_status() { if [[ $# -eq 3 ]];then offset=$3; else offset=0; fi; curl "http://mobile.flightview.com/TrackByRoute.aspx?view=detail&al="$1"&fn="$2"&dpdat=$(date +%Y%m%d -d ${offset}day)" 2>/dev/null |html2text |grep ":"; }

###### Autofocus window after executing some command example: focus make all from: http://noisy-coder.blogspot.com/2010/10/autofocus-window.html
function focus() { winID=`xprop -root |awk '/_NET_ACTIVE_WINDOW/ {print $5; exit;}'`; $@; wmctrl -i -a $winID; }

###### Weather and stuff - 10-day forcast - USAGE:	forecast 50315
function forecast() {
	_ZIP=$1

	if   [ $# = 1 ];then
		printf "$_ZIP\n" | egrep '^[0-9][0-9][0-9][0-9][0-9]$' >>/dev/null
		if   [ $? = 0 ];then
			printf "Your 10 Day Weather Forecast as follows:\n";
			lynx -dump "http://www.weather.com/weather/print/$_ZIP" | sed -n '/%$/s/\[.*\]//p';
			printf "\n"
		elif [ $? = 1 ];then
			printf "Bad ZIP code!\n"
		fi
	elif [ $# != 1 ];then
		printf "You need to supply a ZIP code!\n"
	fi
}

###### get sunrise and sunset times
function suntimes()
{
l=12765843;curl -s http://weather.yahooapis.com/forecastrss?w=$l|grep astronomy| awk -F\" '{print $2 "\n" $4;}'
}

###### weather-util - requires "weather-util" and "weather-util-data" - sudo apt-get install weather-util weather-util-data - Usage = weather 'zip'/'location'/'code' weather search without extended forecast
alias weather='weather-util'

####### weather search with extended forecast
alias weatherf='weather-util --forecast'

###### weather by US zip code - Can be called two ways	# weather 50315	# weather "Des Moines"
function weather_()
{
	declare -a WEATHERARRAY
	WEATHERARRAY=( `lynx -dump http://google.com/search?q=weather+$1 | grep -A 5 '^ *Weather for' | grep -v 'Add to'`)
	echo ${WEATHERARRAY[@]}
}

###### weather search with function "forecast"
function zipweather()
{
	search=$1
	weather-util $search
	forecast $search
}

####### Easily run a program in the background without losing output
function fork() { tf=$(tempfile -d /tmp -p $1.);echo -n "$tf "; $@ &>$tf& }

####### Get FreeMusicCharts of the current month
function freemusiccharts()
{
	wget -O - "http://www.darkerradio.com/news/free-music-charts-$(date "+%B-%Y")/" 2> /dev/null | grep -o "http://[^ \"']*\.mp3" |grep "freemusiccharts.songs" | sort | uniq | xargs -n1 wget -c
}

####### Find all bash functions in a file
#------------------------------------------////

###### finds all functions defined in any shell script secified, including .bashrc
function functions() { read -p "File name> "; sort -d $REPLY | grep "() {" | sed -e 's/() {//g' | less; }

####### ISO-maker from disc
function geniso() {
    
    if [[ $CD_WRITER ]]; then
	dd $DD_OPTS if=$CD_WRITER of="$1"
    else	dd $DD_OPTS if=/dev/dvdrw of="$1"
    fi
}

####### Extract a particular column of spaceseparated output e.g.: lsof | getcolumn 0 | sort | uniq
function getcolumn() { perl -ne '@cols = split; print "$cols['$1']\n"' ; }

####### Get duration of an audio file in seconds.
function get_duration() { durline=$(sox "$1" -n stat 2>&1|grep "Length (seconds):");echo ${durline#*\: }; }

###### Get/verify info on stuff (useful in other functions) usage: getExtension <filename>
function getExtension(){ echo "${1##*.}"; }

###### getFileName
function getFileName()
# Author: Josh Bailey
# Email: jbsnake <at> <no spam> usalug.org
# further tweaked by: jsz
# usage: getFileName <filename>
{
    local filename=${1##*/}
    echo "${filename%.*}"
}

###### getPath
function getPath()
# Author: Josh Bailey
# Email: jbsnake <at> <no spam> usalug.org
# further tweaked by: jsz
# usage: getPath <filename>
{ echo "${1%/*}"; }

###### inStr
function inStr()
# Author: Josh Bailey
# Email: jbsnake <at> <no spam> usalug.org
# further tweaked by: jsz
# usage: inStr <char> <string>
{
    local i

    for ((i = 0; i < ${#2}; i++)); do
        if [[ ${2:i:1} = $1 ]]; then
            echo "$i"
        fi
    done
}

###### notADot
function notADot()
# Author: Josh Bailey
# Email: jbsnake <at> <no spam> usalug.org
{
   if [[ ${1} != '.' ]]
   then
      return 0
   else
      return 1
   fi
}

###### notAForwardSlash
function notAForwardSlash()
{
   if [[ ${1} != '/' ]]
        then
      return 0
        else
           return 1
        fi
}

####### Download the latest kernel
function get_kernel() {
    
    if [[ $1 == "-s" ]]; then
	wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-${2}.tar.bz2
    elif [[ $1 == "-t" ]]; then
	wget http://www.kernel.org/pub/linux/kernel/v2.6/testing/linux-${2}.tar.bz2
    elif [[ $1 == "-sg" ]]; then
	git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-${2}.y.git
    elif [[ $1 == "-tg" ]]; then
	git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git
    elif [[ $1 == "-z" ]]; then
	wget http://downloads.zen-kernel.org/${2}/${2}-zen${3}.patch.lzma
    fi
}

# Git stuff					 #
#------------------------------------------////

###### git_action
function git_action() {
    if [[ -d .git ]]; then
	if [[ -f .git/dotest/rebasing ]]; then
	    ACTION="rebase"
	elif [[ -f .git/dotest/applying ]]; then
	    ACTION="apply"
	elif [[ -f .git/dotest-merge/interactive ]]; then
	    ACTION="rebase -i"
	elif [[ -d .git/dotest-merge ]]; then
	    ACTION="rebase -m"
	elif [[ -f .git/MERGE_HEAD ]]; then
	    ACTION="merge"
	elif [[ -f .git/index.lock ]]; then
	    ACTION="locked"
	elif [[ -f .git/BISECT_LOG ]]; then
	    ACTION="bisect"
	else	ACTION="nothing"
	fi
	echo $ACTION
    else	echo --
    fi
}

###### git_branch
function git_branch() {
    if [[ -d .git ]]; then
	BRANCH=$(git symbolic-ref HEAD 2>/dev/null)
	echo ${BRANCH#refs/heads/}
    else	echo --
    fi
}

###### git_bzip
function git_bzip() {
    git archive master | bzip2 -9 >"$PWD".tar.bz2
}

###### git_e
function git_e() {
    if [[ "$SVN_USER_ENLIGTENMENT" && $1 == "-m" ]]; then
	svn co svn+ssh://"$SVN_USER_ENLIGTENMENT"@svn.enlightenment.org/var/svn/$2
    else
	svn co http://svn.enlightenment.org/svn/$2
    fi
}

###### git_export
function git_export() {
    if [[ "$1" != "" ]]; then
	git checkout-index --prefix="$1"/ -a
    fi
}

###### git_gnome
function git_gnome() {
    if [[ $GIT_USER_GNOME ]]; then
	if [[ $1 == "-m" ]]; then
	    git clone git+ssh://$GIT_USER_GNOME@git.gnome.org/git/$2
	elif [[ $1 == "-mb" ]]; then
	    git clone -b $3 git+ssh://$GIT_USER_GNOME@git.gnome.org/git/$2
	fi
    fi
    if [[ $1 == "-b" ]]; then
	git clone -b $3 git://git.gnome.org/$2
    else 	git clone git://git.gnome.org/$1
    fi
}

###### git_kde
function git_kde() {
    if [[ "$SVN_USER_KDE" ]]; then
	if [[ $1 == "-m" ]]; then
	    svn co --user-name="$SVN_USER_KDE" svn+ssh://svn.kde.org/home/kde/trunk/KDE/$2
	elif [[ $1 == "-mb" ]]; then
	    svn co --user-name="$SVN_USER_KDE" svn+ssh://svn.kde.org/home/kde/branches/KDE/$2
	fi
    fi
    if [[ $1 == "-b" ]]; then
	svn co svn://svn.kde.org/home/kde/branches/KDE/$2
    else	svn co svn://svn.kde.org/home/kde/trunk/KDE/$2
    fi
}

###### git_revision
function git_revision() {
    if [[ -d .git ]]; then
	REVISION=$(git rev-parse HEAD 2>/dev/null)
	REVISION=${REVISION/HEAD/}
	echo ${REVISION:0:6}
    else	echo --
    fi
}

###### git_xfce
function git_xfce() {
    if [[ $GIT_USER_XFCE ]]; then
	if [[ $1 == "-m" ]]; then
	    git clone ssh://$GIT_USER_XFCE@git.xfce.org/git/$2
	elif [[ $1 == "-mb" ]]; then
	    git clone -b $3 ssh://$GIT_USER_XFCE@git.xfce.org/git/$2
	fi
    fi
    if [[ $1 == "-b" ]]; then
	git clone -b $3 git://git.xfce.org/$2
    else	git clone git://git.xfce.org/$1
    fi
}

###### git_xz
function git_xz() {
    git archive master | xz -9 > "$PWD".tar.xz
}

###### gup
function gup() {
  git fetch && git rebase origin/$(git branch | grep '^\*' | cut -d\  -f2)
}

###### edit the svn log at  the given revision
function svnlogedit() {
    svn propedit svn:log --revprop -r$1 --editor-cmd gedit
}

###### svn recursive directory/file adder this will recursively add files/directories in SVN
function svnradd() { for i in $1/*;do if [ -e "$i" ];then if [ -d "$i" ];then svn add $i;svnradd $i;else svn add $i;fi; fi;done }

###### bash function for convenient 'find' in subversion working directories
function svn_find() { local a=$1; shift; find $a -not \( -name .svn -prune \) $*; }

###### display the revision number of the current repository
function svn_rev() {
    svn info $@ | awk '/^Revision:/ {print $2}'
}

###### do a svn update and show the log messages since the last update
function svn_uplog() {
    local old_revision=`svn_rev $@`
    local first_update=$((${old_revision} + 1))

    svn up -q $@
    if [ $(svn_rev $@) -gt ${old_revision} ]
    then
	svn log -v -rHEAD:${first_update} $@
    else
	echo "No Changes."
    fi
}

# Speed up builds and scripts, remove duplicate  entries in $PATH. Users scripts are often bad: PATH=/apath:$PATH type of thing cause duplicate#
#------------------------------------------////

function glu() { (local IFS="$1"; shift && echo "$*") }

function repath() { ( _E=`echo "${PATH//:/$'\n'}" | awk '!x[$0]++'`; glu ":" $_E ) ; }
PATH=`repath`
export PATH

# Pipe stdout to image and mail
#------------------------------------------////

function gotxt2imgmail() { if [ $# != 1 ]; then echo 'gotxt2imgmail < email >'; return; fi; e="$1"; f=$RANDOM.png; convert label:@- $f; echo "" | mailx -s $f -a $f $e ; }

# Twitter, Twitter, Twitter
#------------------------------------------////

###### view someone's twitter stream from terminal
function grabtweets() { curl -s "twitter.com/$1" | sed -ne '/entry-content/{s/<[^>]*>//g;s/^[ \t]*//;p}'; }

###### update twitter via curl as function
function tweet() { curl -u "$1" -d status="$2" "http://twitter.com/statuses/update.xml"; }

###### Hide-Unhide-In-Nautilus.sh - Usage: hideme filename	(hideme whatever.txt) - Hide/Unhide file(s)/folder(s) in Nautilus
function hideme()
{
	# Creator: Inameiname
	# Date: 21 June 2011
	# Version: 1.0
	#
	#
	# This is a simple nautilus script to automatically add file(s)/folder(s)
	# to a ".hidden" file so Nautilus will hide them, just like ".*" files
	# Instructions:
	# - decide what file(s)/folder(s) you want to hide inside a particular folder,
	# - highlight them, and right click and select the script
	# - it will automatically add the filenames to a created ".hidden" file inside the directory
	# - if ".hidden" isn't there, it will add it
	# - if you decide to unhide things, simply highlight and select the script again,
	# - and it will automatically remove the filenames from the ".hidden" file
	# - if ".hidden" contains no filenames, it will remove it
	#
	#
	# Optionals:
	# - Add the option to change the owner and group for whatever is selected to hide/unhide
	# - Add the option to add the permissions for whatever is selected to hide/unhide
	# - Add the option to make executable whatever is selected to hide/unhide
	#
	#
	# Remember this only works inside the current directory/opened folder and files/folders inside that folder.
	# Just comment out or uncomment whatever desired.
	# Currently, only the ability to hide/unhide stuff is uncommented,
	# but you can always just comment it out, and uncomment one of the "Make Executable" commands,
	# and/or one of the "Change the owner and/or group of each file" commands,
	# and/or one of the "Add permissions" commands, or mix and match whatever you want.
	#
	#
	# For the changes to take effect to the file(s)/folder(s) you hid/unhid, you may have to refresh the folder, or even Nautilus
	# Set IFS so that it won't consider spaces as entry separators.
	# Without this, spaces in file/folder names can make the loop go wacky.
	IFS=$'\n'
	# See if the Nautilus environment variable is empty
	if [ -z $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ]; then
	    # If it's blank, set it equal to $1
	    NAUTILUS_SCRIPT_SELECTED_FILE_PATHS=$1
	fi
	# Loop through the list (from either Nautilus or the command line)
	for ARCHIVE_FULLPATH in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
	    NEWDIRNAME=${ARCHIVE_FULLPATH%.*}
	    FILENAME=${ARCHIVE_FULLPATH##*/}
	    NAME=${ARCHIVE_FULLPATH##*/.*}
	    # Hide/Unhide file(s)/folder(s) using ".hidden" file within the current folder
		 # Copies all selected files/folders filenames to ".hidden"
		   echo $FILENAME >> .hidden
		 # Sorts and Checks ".hidden" for any duplicates
		   sort .hidden | uniq -u > .hidden_temp
		   rm .hidden
		   mv .hidden_temp .hidden
		 # Checks ".hidden" to see if there is anything there; if not, it removes it
		   for file in .hidden
		   do
			if [ `wc -l < $file` -eq 0 ]; then
			   # file is empty
			   rm $file
			fi
		   done
	    # Change the owner and/or group of each FILE to OWNER and/or GROUP, if desired
		 # chown -R $USER:$USER $ARCHIVE_FULLPATH # set owner:group to current user
		 # gnome-terminal -x sudo chown -R root:root $ARCHIVE_FULLPATH # set owner:group to root
		 # gnome-terminal -x sudo chown -R $USER:$USER $ARCHIVE_FULLPATH # set owner:group to current user
	    # Add permissions, if desired
		 # chmod 444 $ARCHIVE_FULLPATH # read-only permissions for all
		 # chmod 600 $ARCHIVE_FULLPATH # read/write for you, no permissions for rest
		 # chmod 644 $ARCHIVE_FULLPATH # read/write for you, read-only permissions for rest (default)
		 # sudo chmod 444 $ARCHIVE_FULLPATH # read-only permissions for all
		 # sudo chmod 600 $ARCHIVE_FULLPATH # read/write for you, no permissions for rest
		 # sudo chmod 644 $ARCHIVE_FULLPATH # read/write for you, read-only permissions for rest (default)
	    # Make executable, if desired
		 # chmod +x $ARCHIVE_FULLPATH
		 # gnome-terminal -x sudo chmod +x $ARCHIVE_FULLPATH

	done
	# Add a notification when finished, if desired
	    echo -n ''
	    echo -n 'Job Finished
	'
}
alias unhideme='hideme'

####### Cool History Summerizer
function historyawk() { history|awk '{a[$2]++}END{for(i in a){printf"%5d\t%s\n",a[i],i}}'|sort -nr|head; }

# Progress visuals				 #
#------------------------------------------////

###### display animated hourglass in the shell to indicate ongoing processing
function hourglass() { s=$(($SECONDS +${1:-10}));(tput civis;while [[ $SECONDS -lt $s ]];do for f in '|' ' ' '\-' /;do echo -n $f&&sleep .2s&&tput cub1;done;done);tput cnorm; }

###### pretty progressbar
function progressbar()
{
    SP_COLOUR="\e[37;44m"
    SP_WIDTH=5.5
    SP_DELAY=0.2
    SP_STRING=${2:-"'|/=\'"}
    while [ -d /proc/$1 ]
    do
	printf "$SP_COLOUR\e7  %${SP_WIDTH}s  \e8\e[01;37m" "$SP_STRING"
	sleep ${SP_DELAY:-.2}
	SP_STRING=${SP_STRING#"${SP_STRING%?}"}${SP_STRING%?}
    done
    tput sgr0
}

###### please wait...
function spanner() {
    PROC=$1;COUNT=0
    echo -n "Please wait "
    while [ -d /proc/$PROC ];do
	while [ "$COUNT" -lt 10 ];do
	    echo -ne '\x08  ' ; sleep 0.1
	    ((COUNT++))
	done
	until [ "$COUNT" -eq 0 ];do
	    echo -ne '\x08\x08 ' ; sleep 0.1
	    ((COUNT -= 1))
	done
    done
}

###### spin
function spin() {  
        echo -n "|/     |"
        while [ -d /proc/$1 ]
        do
        # moving right
        echo -ne "\b\b\b\b\b\b\b-     |"
        sleep .05
        echo -ne "\b\b\b\b\b\b\b\\     |"
        sleep .05
        echo -ne "\b\b\b\b\b\b\b|     |"
        sleep .05
        echo -ne "\b\b\b\b\b\b\b /    |"
        sleep .05
        echo -ne "\b\b\b\b\b\b-    |"
        sleep .05
        echo -ne "\b\b\b\b\b\b\\    |"
        sleep .05
        echo -ne "\b\b\b\b\b\b|    |"
        sleep .05
        echo -ne "\b\b\b\b\b\b /   |"
        sleep .05
        echo -ne "\b\b\b\b\b-   |"
        sleep .05
        echo -ne "\b\b\b\b\b\\   |"
        sleep .05
        echo -ne "\b\b\b\b\b|   |"
        sleep .05
        echo -ne "\b\b\b\b\b /  |"
        sleep .05
        echo -ne "\b\b\b\b-  |"
        sleep .05
        echo -ne "\b\b\b\b\\  |"
        sleep .05
        echo -ne "\b\b\b\b|  |"
        sleep .05
        echo -ne "\b\b\b\b / |"
        sleep .05
        echo -ne "\b\b\b- |"
        sleep .05
        echo -ne "\b\b\b\\ |"
        sleep .05
        echo -ne "\b\b\b| |"
        sleep .05
        echo -ne "\b\b\b /|"
        sleep .05
        echo -ne "\b\b-|"
        sleep .05
        echo -ne "\b\b\\|"
        sleep .05
        echo -ne "\b\b||"
        sleep .05
        echo -ne "\b\b/|"
        sleep .05
        # moving left
        echo -ne "\b\b||"
        sleep .05
        echo -ne "\b\b\\|"
        sleep .05
        echo -ne "\b\b-|"
        sleep .05
        echo -ne "\b\b\b/ |"
        sleep .05
        echo -ne "\b\b\b| |"
        sleep .05
        echo -ne "\b\b\b\\ |"
        sleep .05
        echo -ne "\b\b\b- |"
        sleep .05
        echo -ne "\b\b\b\b/  |"
        sleep .05
        echo -ne "\b\b\b\b|  |"
        sleep .05
        echo -ne "\b\b\b\b\\  |"
        sleep .05
        echo -ne "\b\b\b\b-  |"
        sleep .05
        echo -ne "\b\b\b\b\b/   |"
        sleep .05
        echo -ne "\b\b\b\b\b|   |"
        sleep .05
        echo -ne "\b\b\b\b\b\\   |"
        sleep .05
        echo -ne "\b\b\b\b\b-   |"
        sleep .05
        echo -ne "\b\b\b\b\b\b/    |"
        sleep .05
        echo -ne "\b\b\b\b\b\b|    |"
        sleep .05
        echo -ne "\b\b\b\b\b\b\\    |"
        sleep .05
        echo -ne "\b\b\b\b\b\b-    |"
        sleep .05
        echo -ne "\b\b\b\b\b\b\b/     |"
        sleep .05
        done
    echo -e "\b\b\b\b\b\b\b\b\b|=======| done!"
}

###### spinner
function spinner()
{
    PROC=$1
    while [ -d /proc/$PROC ];do
	echo -ne '\e[01;32m/\x08' ; sleep 0.05
	echo -ne '\e[01;32m-\x08' ; sleep 0.05
	echo -ne '\e[01;32m\\\x08' ; sleep 0.05
	echo -ne '\e[01;32m|\x08' ; sleep 0.05
    done
}

###### Display a progress process
# To start the spinner2 function, you have to send the function into the background. To stop the spinner2 function, you have to define the argument "stop".
# EXAMPLE:
#    echo -n "Starting some daemon "; spinner2 &
#    if sleep 10; then
#       spinner2 "stop"; echo -e "\t[ OK ]"
#    else
#       spinner2 "stop"; echo -e "\t[ FAILED ]"
#    fi
function spinner2() {
      local action=${1:-"start"}
      declare -a sign=( "-" "/" "|" "\\\\" )
      # define singnal file...
      [ "$action" = "start" ] && echo 1 > /tmp/signal
      [ "$action" = "stop" ] && echo 0 > /tmp/signal
      while [ "$( cat /tmp/signal 2>/dev/null )" == "1" ] ; do
          for (( i=0; i<${#sign[@]}; i++ )); do
              echo -en "${sign[$i]}\b"
              # with this command you can use millisecond as sleep time - perl rules ;-)
              perl -e 'select( undef, undef, undef, 0.1 );'
          done
      done
      # clear the last ${sign[$i]} sign at finish...
      [ "$action" = "stop" ] && echo -ne " \b"
}

###### working
function working()
{
   while [ -d /proc/$1 ]
   do
    echo -ne "w      \b\b\b\b\b\b\b";sleep .08;
    echo -ne "wo     \b\b\b\b\b\b\b";sleep .08;
    echo -ne "wor    \b\b\b\b\b\b\b";sleep .08;
    echo -ne "work   \b\b\b\b\b\b\b";sleep .08;
    echo -ne "worki  \b\b\b\b\b\b\b";sleep .08;
    echo -ne "workin \b\b\b\b\b\b\b";sleep .08;
    echo -ne "working\b\b\b\b\b\b\b";sleep .08;
    echo -ne " orking\b\b\b\b\b\b\b";sleep .08;
    echo -ne "  rking\b\b\b\b\b\b\b";sleep .08;
    echo -ne "   king\b\b\b\b\b\b\b";sleep .08;
    echo -ne "    ing\b\b\b\b\b\b\b";sleep .08;
    echo -ne "     ng\b\b\b\b\b\b\b";sleep .08;
    echo -ne "      g\b\b\b\b\b\b\b";sleep .08;
   done
}

####### Get just the HTTP headers from a web page(and its redirects)
function http_headers() { /usr/bin/curl -I -L $@ ; }

####### Convert number of bytes to human readable filesize
function human_filesize() { awk -v sum="$1" ' BEGIN {hum[1024^3]="Gb"; hum[1024^2]="Mb"; hum[1024]="Kb"; for (x=1024^3; x>=1024; x/=1024) { if (sum>=x) { printf "%.2f %s\n",sum/x,hum[x]; break; } } if (sum<1024) print "1kb"; } ' ; }

####### :h gets you to the vim help menu or directly to :help wordname
function :h() {  vim --cmd ":silent help $@" --cmd "only"; }

###### machine details - Show computer information of all sorts (requires 'gawk': sudo apt-get install gawk)
function ii()
{
    echo -e "\n${RED}You are logged onto:$NC " ; hostname
    echo -e "\n${RED}Additionnal information:$NC " ; uname -a
    echo -e "\n${RED}Users logged on:$NC " ; w -h
    echo -e "\n${RED}Current date:$NC " ; date
    echo -e "\n${RED}Machine stat:$NC " ; uptime
    echo -e "\n${RED}Disk space:$NC " ; df -h
    echo -e "\n${RED}Memory stats (in MB):$NC " ;
    if [ "$OS" = "Linux" ]; then
        free -m
    elif [ "$OS" = "Darwin" ]; then
        vm_stat
    fi
    echo -e "\n${RED}IPs:$NC " ; ips
}

###### paste hardware list (hwls) in html format into pastehtml.com directly from console and return URI
function listhw() { curl -s -S --data-urlencode "txt=$(sudo lshw -html)" "http://pastehtml.com/upload/create?input_type=html&result=address";echo; }

###### full memcache client in under 255 chars (uses dd, sed and nc)
# usage: mem memcache-command [arguments]
function mem() { { case $1 in st*|[gid]*) printf "%s " "$@";; *) dd if=$3 2>&1|sed '$!d;/^0/d;s/ .*//;s/^/'"$1"' '"$2"' 1 0 /; r '"$3"'' 2>/dev/null;;esac;printf "\r\nquit\r\n";}|nc -n 127.0.0.1 11211; }

###### notify on Battery power - works on laptops, desktop having communication b/w UPS & CPU
function NotifyOnBATTERY() { while :; do on_ac_power||notify-send "Running on BATTERY"; sleep 1m; done ; }

###### colored status of running services
function services() { printf "$(service --status-all 2>&1|sed -e 's/\[ + \]/\\E\[42m\[ + \]\\E\[0m/g' -e 's/\[ - \]/\\E\[41m\[ - \]\\E\[0m/g' -e 's/\[ ? \]/\\E\[43m\[ ? \]\\E\[0m/g')\n"; }

###### show_battery_load
function show_battery_load()
{
    case $1 in
	*acpi )
	    check_opt acpi show_battery_load::acpi
	    if [[ $? != "1" ]]; then
		load=$(acpi -b | sed -e "s/.* \([1-9][0-9]*\)%.*/\1/")
		out="$(acpi -b)"
		state="$(echo "${out}" | awk '{print $3}')"
		case ${state} in
		    charging,)
			statesign="^"
		    ;;
		    discharging,)
			statesign="v"
		    ;;
		    charged,)
			statesign="°"
		    ;;
		esac
		battery="${statesign}${load}"
		echo $battery
	    fi
	;;
	*apm )
	    check_opt apm show_battery_load::apm
	    if [[ $? != "1" ]]; then
		result="$(apm)"
		case ${result} in
		    *'AC on'*)
			state="^"
		    ;;
		    *'AC off'*)
			state="v"
		    ;;
		esac
		load="${temp##* }"
		battery="${state}${load}"
		echo $battery
	    fi
	;;
	* )
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}show_battery_load${ewhite} |${egreen} --acpi${eiceblue} [show batteryload using acpi]\
	    \n${eorange}show_battery_load${ewhite} |${egreen} --apm${eiceblue} [show batteryload using apm]" | column -t
	    echo ""
	    tput sgr0
	;;
    esac
}

###### show_cpu_load
function show_cpu_load()
{
    case $1 in
	*help )
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}show_cpu_load${ewhite} |${egreen} ! no options !\n"
	    tput sgr0
	;;
	* )
	    NICE_IGNORE=20
	    t="0"
	    while read cpu ni; do
		if [[ $ni == *-* || $ni -le $NICE_IGNORE ]]; then
		    t="$t + $cpu"
		fi
		if [[ ${cpu%%.*} -eq 0 ]]; then
		    break
		fi
	    done < <(ps -Ao "%cpu= ni="| sort -r)
	    cpu=$(echo "$t" | bc)
	    if [[ ! "${cpu#.}x" = "${cpu}x" ]]; then
		cpu="0${cpu}"
	    fi
	    cpu=${cpu%%.*}
	    if [[ $cpu -gt 100 ]]; then
		cpu=100
	    fi
	    if [[ $cpu -lt 16 ]]; then
		color=${eiceblue}
	    elif [[ $cpu -lt 26 ]]; then
		color=${eturqoise}
	    elif [[ $cpu -lt 41 ]]; then
		color=${esmoothgreen}
	    elif [[ $cpu -lt 61 ]]; then
		color=${egreen}
	    elif [[ $cpu -lt 81 ]]; then
		color=${eyellow}
	    else	color=${ered}
	    fi
	    if [[ $cpu -lt 10 ]]; then
		prepend=00
	    elif [[ $cpu -lt 100 ]]; then
		prepend=0
	    fi
	    if [[ $enabcol == true ]]; then
		echo -e "$color$prepend$cpu"
	    else	echo $prepend$cpu
	    fi
	;;
    esac
}

###### show_mem
function show_mem() {  
    case $1 in
	*used )
	    used=$(free -m | grep 'buffers/cache' | awk '{print $3}')
	    if [[ $used -lt 1000 ]]; then
		echo 0$used
	    elif [[ $used -lt 100 ]]; then
		echo 00$used
	    else	echo $used
	    fi
	;;
	*free )
	    free=$(free -m | grep 'buffers/cache' | awk '{print $4}')
	    if [[ $free -lt 1000 ]]; then
		echo 0$free
	    elif [[ $free -lt 100 ]]; then
		echo 00$ree
	    else	echo $free
	    fi
	;;
	*used-percent )
	    free | {
		read
		read m t u f s b c;
		f=$[$f + $b + $c]
		f=$[100-100*$f/$t]
		if [ $f -gt 100 ]; then
		    f=100
		fi
		echo ${f}%
	}
	;;
	*free-percent )
	    free | {
		read
		read m t u f s b c;
		f=$[$f + $b + $c]
		f=$[100-100*$f/$t]
		if [ $f -gt 100 ]; then
		    f=100
		fi
		echo $((100-${f}))%
		}
	;;
	* )
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "\n${eorange}show_mem ${ewhite}|${egreen} --used ${eiceblue}[display used memory in mb]\
	    \n${eorange}show_mem ${ewhite}|${egreen} --free ${eiceblue}[display free memory in mb]\
	    \n${eorange}show_mem ${ewhite}|${egreen} --percent-used ${eiceblue}[display used memory in %]\
	    \n${eorange}show_mem ${ewhite}|${egreen} --percent-free ${eiceblue}[display free memory in %]" | column -t
	    echo ""
	    tput sgr0
	;;
    esac
}

###### show_size
function show_size()
{
    case $1 in
	*help )
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}show_size ${ewhite}|${egreen} ! no options !\n"
	    tput sgr0
	;;
	* )
	    let TotalBytes=0
	    for Bytes in $(ls -lA -1 | grep "^-" | awk '{ print $5 }'); do
		let TotalBytes=$TotalBytes+$Bytes
	    done
	    if [ $TotalBytes -lt 1024 ]; then
		TotalSize=$(echo -e "scale=1 \n$TotalBytes \nquit" | bc)
		suffix="B"
	    elif [ $TotalBytes -lt 1048576 ]; then
		TotalSize=$(echo -e "scale=1 \n$TotalBytes/1024 \nquit" | bc)
		suffix="KB"
	    elif [ $TotalBytes -lt 1073741824 ]; then
		TotalSize=$(echo -e "scale=1 \n$TotalBytes/1048576 \nquit" | bc)
		suffix="MB"
	    else
		TotalSize=$(echo -e "scale=1 \n$TotalBytes/1073741824 \nquit" | bc)
		suffix="GB"
	    fi
	    echo "${TotalSize} ${suffix}"
	;;
    esac
}

###### show_space
function show_space()
{
    case $1 in
	*used-percent )
	    echo $(df | grep -w $2 | gawk '{print $5}')
	;;
	*free-percent )
	    echo $((100-$(df | grep -w $2 | gawk '{print $5}' | sed -e 's/\%//g')))%
	;;
	*used )
	    echo $(df -h | grep -w $2 | gawk '{print $3}')B
	;;
	*free )
	    echo $(df -h | grep -w $2 | gawk '{print $4}')B
	;;
	*total )
	    echo $(df -h | grep -w $2 | gawk '{print $2}')B
	;;
	* )
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}show_space ${ewhite}|${egreen} --used ${eiceblue}[display used space in mb/gb]\
	    \n${eorange}show_space ${ewhite}|${egreen} --free ${eiceblue}[display free space in mb/gb]\
	    \n${eorange}show_space ${ewhite}|${egreen} --percent-used ${eiceblue}[display used space in %]\
	    \n${eorange}show_space ${ewhite}|${egreen} --percent-free ${eiceblue}[display free space in %]" | column -t
	    echo ""
	    tput sgr0
	;;
    esac
}

###### show_system_load
function show_system_load() {  
    case $1 in
	1 )
	    load=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\1/" -e "s/ //g")
	;;
	10 )
	    load=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\2/" -e "s/ //g")
	;;
	15 )
	    load=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\3/" -e "s/ //g")
	;;
	*help | "")
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}show_system_load${ewhite} | ${egreen}1 ${eiceblue}[load average for 1 minute]\
	    \n${eorange}show_system_load${ewhite} | ${egreen}10 ${eiceblue}[load average for 10 minutes]\
	    \n${eorange}show_system_load${ewhite} | ${egreen}15 ${eiceblue}[load average for 15 minutes]\n" | column -t
	    tput sgr0
	;;
    esac
    if [[ $load != "" ]]; then
    tmp=$(echo $load*100 | bc)
    load100=${tmp%.*}
    if [[ $enabcol == true ]]; then
	if [[ ${load100} -lt 35 ]]; then
	    loadcolor=${eblue}
	elif [[ ${load100} -ge 35 ]] && [[ ${load100} -lt 120 ]]; then
	    loadcolor=${eiceblue}
	elif [[ ${load100} -ge 120 ]] && [[ ${load100} -lt 200 ]]; then
	    loadcolor=${egreen}
	elif [[ ${load100} -ge 200 ]] && [[ ${load100} -lt 300 ]]; then
	    loadcolor=${eyellow}
	else	loadcolor=${ered}
	fi
    fi
    echo -e $loadcolor$load
    fi
}

###### show_tty
function show_tty()
{
    case $1 in
	*help )
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}show_tty${ewhite}|${egreen} ! no options !\n"
	    tput sgr0
	;;
	* )
	    TTY=$(tty)
	    echo ${TTY:5} | sed -e 's/\//\:/g'
	;;
    esac
}

###### show_uptime
function show_uptime() {
    case $1 in
	*help )
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}show_uptime${ewhite} |${egreen} ! no options !\n"
	    tput sgr0
	;;
	* )
	    uptime=$(</proc/uptime)
	    timeused=${uptime%%.*}
	    if (( timeused > 86400 )); then
	    ((
		daysused=timeused/86400,
		hoursused=timeused/3600-daysused*24,
		minutesused=timeused/60-hoursused*60-daysused*60*24,
		secondsused=timeused-minutesused*60-hoursused*3600-daysused*3600*24
	    ))
		if (( hoursused < 10 )); then
		    hoursused=0${hoursused}
		fi
		if (( minutesused < 10 )); then
		    minutesused=0${minutesused}
		fi
		if (( secondsused < 10 )); then
		    secondsused=0${secondsused}
		fi
		output="${daysused}d ${hoursused}h:${minutesused}m:${secondsused}s"
	    elif (( timeused < 10 )); then
		output="0d 00h:00m:0$(timeused)s"
	    elif (( timeused < 60 )); then
		output="0d 00h:00m:${timeused}s"
	    elif (( timeused < 3600 )); then
	    ((
		minutesused=timeused/60,
		secondsused=timeused-minutesused*60
	    ))
		if (( minutesused < 10 )); then
		    minutesused=0${minutesused}
		fi
		if (( secondsused < 10 )); then
		    secondsused=0${secondsused}
		fi
		output="0d 00h:${minutesused}m:${secondsused}s"
	    elif (( timeused < 86400 )); then
	    ((
		hoursused=timeused/3600,
		minutesused=timeused/60-hoursused*60,
		secondsused=timeused-minutesused*60-hoursused*3600
	    ))
		if (( hoursused < 10 )); then
		    hoursused=0${hoursused}
		fi
		if (( minutesused < 10 )); then
		    minutesused=0${minutesused}
		fi
		if (( secondsused < 10 )); then
		    secondsused=0${secondsused}
		fi
		output="0d ${hoursused}h:${minutesused}m:${secondsused}s"
	    fi
	    echo "$output"
	;;
    esac
}

###### STAT Function showing ALL info, stat options, and descriptions
function statt() { C=c;stat --h|sed '/Th/,/NO/!d;/%/!d'|while read l;do p=${l/% */};[ $p == %Z ]&&C=fc&&echo ^FS:^;echo "`stat -$C $p \"$1\"` ^$p^${l#%* }";done|column -ts^; }

###### system_infos
function system_infos()
{
    case $1 in
	*cpu)
	    echo -e "${ewhite}CPU:\n"
	    echo -e "${eorange}Model:${eiceblue} $(grep "model name" /proc/cpuinfo | sed -e 's/.*: //g')"
	    echo -e "${eorange}MHz  :${eiceblue} $(grep "cpu MHz" /proc/cpuinfo | sed -e 's/.*: //g')\n"
	;;
	*kernel)
	    echo -e "${ewhite}Kernel:\n"
	    echo -e "${eorange}Release:${eiceblue} $(uname -r)"
	    echo -e "${eorange}Version:${eiceblue} $(uname -v)"
	    echo -e "${eorange}Machine:${eiceblue} $(uname -m)\n"
	;;
	*mem | *ram)
	    echo -e "${ewhite}RAM:\n"
	    echo -e "${eorange}Total:${eiceblue} $(((`showmem --free`) + (`showmem --used`))) MB"
	    echo -e "${eorange}Free :${eiceblue} $(showmem --free) MB"
	    echo -e "${eorange}Used :${eiceblue} $(showmem --used) MB\n"
	;;
	*partitions)
	    echo -e "${ewhite}Partitions:${eorange}\n"
	    echo -e "major minor blocks device-node ${eiceblue}\
	    \n$(cat /proc/partitions | sed -e '1,2d')" | column -t
	    echo ""
	;;
	*pci)
	    check_opt lspci systeminfos::pci
	    if [[ $? != "1" ]]; then
		echo -e "${ewhite}PCI Devices:\n${eiceblue}"
		lspci -vkmm
		echo ""
	    fi
	;;
	*usb)
	    check_opt lsusb systeminfos::usb
	    if [[ $? != "1" ]]; then
		echo -e "${ewhite}USB Devices:\n${eiceblue}"
		lsusb -v
		echo ""
	    fi
	;;
	*mounts)
	    echo -e "${ewhite}Mounts:\n${eorange}\
	    \ndevice-node on mount-point type filesystem options\n" ${eiceblue} "\n\n$(mount)" | column -t
	    echo ""
	;;
	*bios)
	    check_opt dmidecode systeminfos::bios
	    if [[ $? != "1" && $EUID == 0 ]]; then
		echo -e "${ewhite}SMBIOS/DMI Infos:${eiceblue}\n"
		dmidecode -q
	    fi
	;;
	*all)
	    system_infos_cpu
	    system_infos_kernel
	    system_infos_memory
	    system_infos_partitions
	    # system_infos_pci
	    # system_infos_usb
	    system_infos_mounts
	    # system_infos_bios
	;;
	*)
	    echo -e "\n${ewhite}Usage:\n"
	    echo -e "${eorange}system_infos ${ewhite}|${egreen} --cpu\t\t${eiceblue}[Display CPU Model and Freq]\
	    \n${eorange}system_infos ${ewhite}|${egreen} --kernel\t${eiceblue} 	[Display Kernel Version, Release and Machine]\
	    \n${eorange}system_infos ${ewhite}|${egreen} --memory\t${eiceblue} 	[Display Total, Free and Used RAM]\
	    \n${eorange}system_infos ${ewhite}|${egreen} --partitions\t${eiceblue}[Display Major, Minor, Blocks and Node for all Paritions]\
	    \n${eorange}system_infos ${ewhite}|${egreen} --pci\t\t${eiceblue}[Display Infos about all PCI Devices (and their kernel-module)]\
	    \n${eorange}system_infos ${ewhite}|${egreen} --usb\t\t${eiceblue}[Display Infos about all USB Devices (and their kernel-module)]\
	    \n${eorange}system_infos ${ewhite}|${egreen} --bios\t${eiceblue} 	[Display SMBIOS DMI Infos]\
	    \n${eorange}system_infos ${ewhite}|${egreen} --mounts\t${eiceblue} 	[Display all mounted devices]\n"
	    tput sgr0
	;;
    esac
}

###### shows various info on running activities
function treeps() {
    ps f -u $USER -o command,pid,%cpu,%mem,time,etime,tty | \
	awk 'NR <= 1 {print;next} !/awk/ && $0~var' var=${1:-".*"}
}

###### uptime in minutes
function uptime_min()
{
	awk  '{print $0/60;}' /proc/uptime
}

###### info about current open windows
function wininfo() {
    xprop | grep -w "WM_NAME\|WM_CLASS\|WM_WINDOW_ROLE\|_NET_WM_STATE"
}

# Resizing an image				 #
#------------------------------------------////

# USAGE: image_resize "percentage of image resize" "input image" "output image"
function image_resize()
{
convert -sample "$1"%x"$1"% "$2" "$3"
}

####### Search IMDB.COM
function imdb()
{
firefox "http://www.imdb.com/find?s=all&q="${@}"&x=0&y=0" &
}

####### Using PIPEs, Execute a command, convert output to .png file, upload file to imgur.com, then returning the address of the .png.
function imgur() { convert label:@- png:-|curl -F "image=@-" -F "key=1913b4ac473c692372d108209958fd15" http://api.imgur.com/2/upload.xml|grep -E -o "<original>(.)*</original>" | grep -E -o "http://i.imgur.com/[^<]*" ; }

####### INC
function inc() {
    let OPS=$OPS+1
    echo "* pcur $OPS"
}

####### Displays metadata for specified media file $1 = media file name
function info() {
    EXT=`echo "${1##*.}" | sed 's/\(.*\)/\L\1/'`
    if [ "$EXT" == "mp3" ]; then
        id3v2 -l "$1"
        echo
        mp3gain -s c "$1"
    elif [ "$EXT" == "flac" ]; then
        metaflac --list --block-type=STREAMINFO,VORBIS_COMMENT "$1"
    else
        echo "ERROR: Not a supported file type."
    fi
}

# Sample introduction
#------------------------------------------////

function intro() {
less <<INTRO
Hi, welcome to your bytesized shell :)
We've added a few shell aliases (commands) for common
things, to make your life easier, here's a quick list of
things you might want to do:
command - what it does
For more advances users:
press "q" to exit this screen
This screen will not be displayed to you in the future, if you want to see it again, type "intro"
INTRO
}

# Check variable has been set
#------------------------------------------////

###### works in all shells - does not require a test - handles like an assertion
function isdef() { eval test -n \"\${$1+1}\"; }

# Jump to any directory...
#------------------------------------------////

###### ..below the current one - usage: jd dir (requires globstar. To set globstar use: shopt -s globstar)
function jd() { cd **/"$@"; }

###### ..above the current one
function jda() { cd $(pwd | sed "s/\(\/$@\/\).*/\1/g"); }

###### usage: upto directory
function upto() { cd "${PWD/\/$@\/*//$@}"; }

# Kill a process by name
#------------------------------------------////

###### example: killps firefox-bin
function killps()
{
    local pid pname sig="-TERM" # default signal
    if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
        echo "Usage: killps [-SIGNAL] pattern"
        return;
    fi
    if [ $# = 2 ]; then sig=$1 ; fi
    for pid in $(myps | nawk '!/nawk/ && $0~pat { print $2 }' pat=${!#}) ; do
        pname=$(myps | nawk '$2~var { print $6 }' var=$pid )
        if ask "Kill process $pid <$pname> with signal $sig ? "
            then kill $sig $pid
        fi
    done
}

###### example: pskill firefox-bin
function psgrep() {
    if [[ $1 == "-u" ]]; then
	ps aux | grep -v grep | grep $2 | awk '{ print $2 " : " $11}' | tee .temp
	CMDS=$(cat .temp)
    elif [[ $1 != "" ]]; then
	ps aux | grep -v grep | grep "$1" | awk '{ print $11 " : " $2 " : " $1 }' | tee .temp
	CMDS=$(cat .temp)
    fi
    if [[ $CMDS == "" ]]; then
	echo "no matching process"
    fi
    rm -f .temp
}

###### pskill
function pskill() {
    if [[ $1 ]]; then
	psgrep $1
	shift
	if [[ $CMDS != "" ]]; then
	    echo -e "\nenter process number to kill:\n"
	    read ID
	    if [[ ! $ID == 0 || ! $ID == "" ]]; then
		kill $@ $ID
	    fi
	fi
    fi
}

# Kindle connection/disconnection
#------------------------------------------////

###### be sure to press on unattached Kindle beforehand: "[SHIFT][SHIFT][N]", to start /test/bin/usbnetwork - and then connect via usb the Kindle
function kindle_connect()
{
	modprobe usbnet
	modprobe cdc_ether
	sudo ifconfig usb0 192.168.2.1
	ssh [email protected]
}

###### be sure to press on unattached Kindle afterwards: "[SHIFT][SHIFT][N]", to end /test/bin/usbnetwork
function kindle_disconnect()
{
	sudo ifconfig usb0 down
}

# Led set and reset
#------------------------------------------////

function kitt() {
    
    setleds -L -num;
    setleds -L -caps;
    setleds -L -scroll;
    while :; do
	setleds -L +num;
	sleep 0.2;
	setleds -L -num;
	setleds -L +caps;
	sleep 0.2;
	setleds -L -caps;
	setleds -L +scroll;
	sleep 0.2;
	setleds -L -scroll;
	setleds -L +caps;
	sleep 0.2;
	setleds -L -caps;
    done
    resetleds
}
###### resetleds
function resetleds()

{
    setleds -L < /dev/tty1
}

####### Concatenate stuff
function kitty() {
    
    cat -n "$@"
}

# Advanced ls functions
#------------------------------------------////

###### la
function la() {
    
    ls -A --group-directories-first "$@"
}

###### lg
function lg() {
    
    if [[ "$@" == "" ]]; then
	$@="*"
    fi
    ls -l --group-directories-first "$@" | gawk '{print $9, "belongs to Group ->", $4}' | column -t
}

###### ll
function ll() {
    
    ls -l --group-directories-first "$@"
}

###### Counts files, subdirectories and directory size and displays details about files depending on the available space
function lls() {
    # count files
    echo -n "<`find . -maxdepth 1 -mindepth 1 -type f | wc -l | tr -d '[:space:]'` files>"
    # count sub-directories
    echo -n " <`find . -maxdepth 1 -mindepth 1 -type d | wc -l | tr -d '[:space:]'` dirs/>"
    # count links
    echo -n " <`find . -maxdepth 1 -mindepth 1 -type l | wc -l | tr -d '[:space:]'` links@>"
    # total disk space used by this directory and all subdirectories
    echo " <~`du -sh . 2> /dev/null | cut -f1`>"
    ROWS=`stty size | cut -d' ' -f1`
    FILES=`find . -maxdepth 1 -mindepth 1 |
    wc -l | tr -d '[:space:]'`
    # if the terminal has enough lines, do a long listing
    if [ `expr "${ROWS}" - 6` -lt "${FILES}" ]; then
	ls
    else
	ls -hlAF --full-time
    fi
}

###### lo
function lo() {
    
    if [[ "$@" == "" ]]; then
	$@="*"
    fi
    ls -l --group-directories-first "$@" | gawk '{print $9, "belongs to User ->", $3}' | sed -e '1d' | column -t
}

###### l1
function l1() {
    
    ls -1 --group-directories-first "$@"
}

###### lm
function lm() {
    
    if [[ ! "$@" == "" ]]; then
	for file in "$@"; do
	    stat -c "%A %a %n" "$file" | gawk '{print "Permissions of:", $3, "->", $1, "("$2")"}'
	done | column -t
    fi
}

###### inspired by http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x279.html -> but I made it a single awk instead of an awk, forloop and a bc asumes we have awk available.  but really, who doesnt have awk? - let's get the size of the files in this dir
function lsbytes() {
    echo -n $(ls -l | awk '/^-/{total += $5} END{printf "%.2f", total/1048576}')
}

function lscd() {
    builtin cd "${@}" &>/dev/null
    . $BSNG_RC_DIR/dirinfo/display
    dirinfo_display
    echo -e "${epink}content:"
    ls $LSCD_OPTS
    echo "$PWD" > $HOME/.lastpwd
}

###### display long list of files with the given extension - example: lsext txt
function lsext()
{
	find . -type f -iname '*.'${1}'' -exec ls -l {} \; ;
}

###### another way to call for a list of files/folders
function lsr() { /bin/ls -l "$@"/..namedfork/rsrc ; }

###### sorted, recursive long file listing
function lsr_() { find "${@:-.}" -print0 |sort -z |xargs -0 ls $LS_OPTIONS -dla; }

####### Show the single most recently modified file in a directory
function lastfile() { find ${1:-.} -maxdepth 1 -type f -printf "%T+ %p\n" | sort -n | tail -n1 | sed 's/[^[:space:]]\+ //'; }

# Uppercase, lowercase, & cleanup strings & names
#------------------------------------------////

###### lowercase all files in the current directory
function lcfiles() {
    print -n 'Really lowercase all files? (y/n) '
    if read -q ; then
	for i in * ; do
	    mv $i $i:l
    done
    fi
}

###### Convert the first letter into lowercase letters
function lcfirst() {
      if [ -n "$1" ]; then
          perl -e 'print lcfirst('$1')'
      else
          cat - | perl -ne 'print lcfirst($_)'
      fi
}

###### usage: lower [STRING]...
function lower() { echo ${@,,}; }

###### usage: echo hELLO wORLD | lower - convert stdin to lower case
function lower_() { tr [A-Z] [a-z]; }

###### move filenames to lowercase
function lowercase()
{
    for file ; do
        filename=${file##*/}
        case "$filename" in
        */*) dirname==${file%/*} ;;
        *) dirname=.;;
        esac
        nf=$(echo $filename | tr A-Z a-z)
        newname="${dirname}/${nf}"
        if [ "$nf" != "$filename" ]; then
            mv "$file" "$newname"
            echo "lowercase: $file --> $newname"
        else
            echo "lowercase: $file not changed."
        fi
    done
}

###### Remove whitespace at the beginning of a string
#  @param string $1 string (optional, can also handle STDIN)
#  @return string
#  @example:    echo " That is a sentinece " | trim
function ltrim() {
      if [ -n "$1" ]; then
              echo $1 | sed 's/^[[:space:]]*//g'
      else
              cat - | sed 's/^[[:space:]]*//g'
      fi
}

###### Space removal and lowercases folders in current dir.
function rmspaces() {
    ls | while read -r FILE
        do
        mv -v "$FILE" `echo $FILE | tr ' ' '_' | tr -d '[{}(),\!]' | tr -d "\'" | tr '[A-Z]' '[a-z]' | sed 's/_-_/_/g'`
        done
}

###### Remove whitespace at the end of a string
#  @param string $1 string (optional, can also handle STDIN)
#  @return string
#  @example:    echo "That is a sentinece " | rtrim
function rtrim() {
      if [ -n "$1" ]; then
              echo $1 | sed 's/[[:space:]]*$//g'
      else
              cat - | sed 's/[[:space:]]*$//g'
      fi
}

###### Cut a string after X chars and append three points - Usage: string strim( string string [, int length ] )
function strim() {
      local string="$1"
      local length=${2:-30}
      [ "${#string}" -gt ${length} ] && string="${string:0:${length}}..."
      echo $string
}

###### Convert all alphabetic characters to lowercase
#  @param string $1|STDIN string
#  @return string
function strtolower() {
      if [ -n "$1" ]; then
        echo $1 | tr '[:upper:]' '[:lower:]'
      else
        cat - | tr '[:upper:]' '[:lower:]'
      fi
}

###### Convert all alphabetic characters converted to uppercase
#  @param string $1|STDIN string
#  @return string
function strtoupper() {
      if [ -n "$1" ]; then
        echo $1 | tr '[:lower:]' '[:upper:]'
      else
        cat - | tr '[:lower:]' '[:upper:]'
      fi
}

###### Remove whitespace at the beginning and end of a string
#  @param string $1 string (optional, can also handle STDIN)
#  @return string
#  @example:    echo " That is a sentinece " | trim
function trim() {
      if [ -n "$1" ]; then
              echo $1 | sed 's/^[[:space:]]*//g' | sed 's/[[:space:]]*$//g'
      else
              cat - | sed 's/^[[:space:]]*//g' | sed 's/[[:space:]]*$//g'
      fi
}

###### Convert the first letter into uppercase letters
function ucfirst() {
      if [ -n "$1" ]; then
          perl -e 'print ucfirst('$1')'
      else
          cat - | perl -ne 'print ucfirst($_)'
      fi
}

###### Converts first letter of each word within a string into an uppercase, all other to lowercase - Usage: string ucwords( string string )
function ucwords() {
      local string="$*"
      for word in $string; do
          # Get the first character with cut and convert them into uppercase.
          local first="$( echo $word | cut -c1 | tr '[:lower:]' '[:upper:]' )"
          # Convert the rest of the word into lowercase and append them to the first character.
          word="$first$( echo $word | cut -c2-${#word} | tr '[:upper:]' '[:lower:]' )"
          # Put together the sentence.
          local phrase="$phrase $word"
      done
      echo "$phrase"
}

###### usage: upper [STRING]...
function upper() { echo ${@^^}; }

###### usage: echo hELLO wORLD | upper - convert stdin to upper case
function upper_() { tr [a-z] [A-Z]; }

####### Corporate ldapsearch for users		 #
function ldapfind() {
        ldapsearch -x -h ldap.foo.bar.com -b dc=bar,dc=com uid=$1
}

# Organize a text file				 #
#------------------------------------------////

###### sort lines in a text file
function linesort()
{
	sort -u "$1" > "$1".new
}

###### remove duplicate lines in a file (without resorting)
function removeduplines()
{
	awk '!x[$0]++' "$1" > "$1".new
}

###### Livehttpheaders (firefox addon) replacement -  usage: liveh [-i interface] [output-file] && firefox &
function liveh() { tcpdump -lnnAs512 ${1-} tcp |sed ' s/.*GET /GET /;s/.*Host: /Host: /;s/.*POST /POST /;/[GPH][EOo][TSs]/!d;w '"${2-liveh.txt}"' ' >/dev/null ; }

####### Search for music in the specified location
function locatemusic()
{
	slocate -i "${1}" | grep "$HOME/Music/";
}

####### Use a logger
function log() {
    echo "$1" 1>&2
    logger -ist "$(basename -- "$0")" "$1"
}

####### List your MACs address
function lsmac() { ifconfig -a | awk '/HWaddr/ {print $5}' ; }

# MPD music stuff
#------------------------------------------////

###### Add music files in MPD
function madd()
{
    # while [ $# -gt 0 ]; do
        # case "$1" in
            # a)
            # args[i++]=artist;;
            # b)
            # args[i++]=album;;
            # t)
            # args[i++]=title;;
            # *)
            # args[i++]=$1;;
        # esac; shift;
    # done
    # mpc search "${args[@]}" |
    mpc search "$@" |
    mpc add
}

###### Clear, add and play: MPD
function mcap()
{
    mpc clear
    # while [ $# -gt 0 ]; do
        # case "$1" in
            # a)
            # args[i++]=artist;;
            # b)
            # args[i++]=album;;
            # t)
            # args[i++]=title;;
            # *)
            # args[i++]=$1;;
        # esac; shift; done
    # mpc search "${args[@]}" |
    mpc search "$@" |
    mpc add
    mpc play
}

####### Email yourself a quick message		 #
function mailme()
{
    echo "$@" | mail -s "$1" $SERVERMAIL
}

###### Usage: mailme message : mailme "process X completed"
function mailme_() { mailx -s "$@" $USER <<< "$@"; }

####### .. And function				 
function man_()
{
    for i ; do
        xtitle The $(basename $1|tr -d .[:digit:]) manual
        command man -F -a "$i"
    done
}

###### Extended man command -  requires: sudo apt-get install w3m
function man_ext()
{
	/usr/bin/man $* || w3m -dump http://google.com/search?q="$*"\&btnI | less
}

###### Manpage to ... document - example:	man2pdf wipe	=	wipe.pdf
function man2pdf()
{
    case $1 in
	*help | "" )
	    echo -e "\nUsage:"
	    echo -e	"\nman2pdf | <manualpage> [generate a pdf from <manualpage>]\n"
	    tput sgr0
	;;
	* )
	    check_opt ps2pdf man2pdf
	    if [[ $? != "1"  && $1 ]]; then
		man -t $1 | ps2pdf - >$1.pdf
	    else	echo "No manpage given."
	    fi
	;;
    esac
}

###### example:	man2text wipe	=	wipe.txt
function man2text()
{
	man "$1" | col -b > ~/man_"$1".txt
}

####### What is the use of this switch?		 #
function manswitch() { man $1 | less -p "^ +$2"; }

####### Map a command over a list of files - map-files /lib *.so ls -la				 #
function map-files() { find $1 -name $2 -exec ${@:3} {} \ ; }

####### Meta-Backup - backup your software selection and repositories in a deb meta package
function meta-backup()
{
	## Written by Arjan van Lent aka socialdefect ## VERSION: 2.1 ## Modified by Inameiname
	DIALOG1="Did you enable extra repositories or PPAs on this system?. If you have no idea what this is just enter no"
	DIALOG2="Your backup has been created succesfully"
	DIALOG3="Something went wrong. Type bash -x meta-backup in a terminal to debug"
	DIALOG4="Would you like to use the backup for a distribution upgrade?"
	DIALOG5="Enter the codename of the distribution you'd like to upgrade to. eg. sid or maverick"
	DIALOG6="Where woud you like to save your backup files? Enter full path. eg /home/username/backups"
	mkdir -p /tmp/meta-backup/my-meta-backup/DEBIAN						## creating build directories
	  dialog --title "Meta-backup" --yesno "$DIALOG1" 8 40					## repository dialog ## question add repo's
	  dialog --title "Meta-backup" --infobox "..." 8 40
	if [ $? = 0 ] ; then
	  mkdir -p /tmp/meta-backup/my-repo-backup/etc/apt/sources.list.d
	  mkdir /tmp/meta-backup/my-repo-backup/DEBIAN
	  cp -R /etc/apt/sources.list.d/* /tmp/meta-backup/my-repo-backup/etc/apt/sources.list.d/
	  cp -R /etc/apt/sources.list /tmp/meta-backup/my-repo-backup/etc/apt/
	fi
						    ## create the control file for the repo-backup
	echo 'Section: misc
	Priority: optional
	Package: my-repo-backup
	Version: 2.1
	Maintainer: meta-backup
	Depends:
	Architecture: all
	Description: Repository/PPA backup created by meta-backup.
	 Repository/PPA backup created by meta-backup. This package can be used to install all repositories and PPAs that are installed on the computer where the backup is made.' >> /tmp/meta-backup/my-repo-backup/DEBIAN/control
						    ## create the preinst file for the repo-backup
	echo '#!/bin/sh
	set -e
	# Backup repo config
	mv /etc/apt/sources.list /etc/apt/sources.list.old
	mv /etc/apt/sources.list.d /etc/apt/sources.list.d.old' >> /tmp/meta-backup/my-repo-backup/DEBIAN/preinst
	chmod +x /tmp/meta-backup/my-repo-backup/DEBIAN/preinst
						    ## create the postinst file for the repo-backup
	echo '#!/bin/sh
	set -e
	# Pubkeys (to generate this large key, which is all of them in one: sudo apt-key exportall > /tmp/repokeys.key)
	if [ -f /tmp/repokeys.key ];then
	    rm /tmp/repokeys.key
	fi
	sudo cat > "/tmp/repokeys.key" <<"End-of-message"' >> /tmp/meta-backup/my-repo-backup/DEBIAN/postinst
	  ## get the repository keys
	apt-key exportall >> /tmp/meta-backup/my-repo-backup/DEBIAN/postinst
	echo 'End-of-message
	if which sudo apt-key >> /dev/null; then
	    if sudo apt-key add "/tmp/repokeys.key"; then
		echo "OK - repokeys key was installed"
	    else
		echo "ERROR: there was a problem installing the repokeys-key"
	    fi
	fi
	sudo rm -fv "/tmp/repokeys.key"' >> /tmp/meta-backup/my-repo-backup/DEBIAN/postinst
	chmod +x /tmp/meta-backup/my-repo-backup/DEBIAN/postinst
						    ## create the postrm file for the repo-backup
	echo '#!/bin/sh
	set -e
	# Restore repo config
	mv /etc/apt/sources.list.old /etc/apt/sources.list
	mv /etc/apt/sources.list.d.old /etc/apt/sources.list.d' >> /tmp/meta-backup/my-repo-backup/DEBIAN/postrm
	chmod +x /tmp/meta-backup/my-repo-backup/DEBIAN/postrm
	dialog --title "Meta-backup" --yesno "$DIALOG4" 8 40					## Distupgrade feature
	  dialog --title "Meta-backup" --infobox "..." 8 40
	if [ $? = 0 ] ; then
	    dialog --title "Meta-backup" --inputbox "$DIALOG5" 8 40 2> /tmp/meta-backup/upgrade
	    UPGRADE=`cat /tmp/meta-backup/upgrade`
	    dialog --title "Meta-backup" --infobox "..." 8 40
	fi
	if [ $UPGRADE = 0 ] ; then
	  MYDIST=`lsb_release -cs`
	  sed 's/$MYDIST/$UPGRADE/' /tmp/meta-backup/myrepo-backup/etc/apt/sources.list
	  sed 's/$MYDIST/$UPGRADE/' /tmp/meta-backup/myrepo-backup/etc/apt/sources.list.d/*
	fi											## end dist upgrade feature
	  DEPS=`aptitude search -F %p ~i --disable-columns | sed 's/$/,/' | tr '\n\r' ' ' | sed 's/, $//'`	## get list of inst. packages to fill DEPS variable
						    ## create the control file for the meta-backup
	echo "Section: misc
	Priority: optional
	Package: my-meta-backup
	Version: 2.1
	Maintainer: meta-backup
	Depends: $DEPS
	Architecture: all
	Description: Personal system backup created by meta-backup
	 Personal system backup created by meta-backup. This package can be used to install all applications that are installed on the computer where the backup is made. Can be used on all systems using the same base system version as used on the backup machine." >> /tmp/meta-backup/my-meta-backup/DEBIAN/control
	cd /tmp/meta-backup && dpkg --build my-meta-backup					## build and save the package(s)
	if [ $? = 0 ] ; then
	    cd /tmp/meta-backup && dpkg --build my-repo-backup
	fi
	ls /tmp/meta-backup/my-meta-backup.deb							## finish backup
	  if [ $? = 0 ] ; then
	    ERROR=no
	    else ERROR=yes
	  fi
	ls /tmp/meta-backup/my-repo-backup.deb
	  if [ $? = 0 ] ; then
	    ERROR=no
	  else ERROR=yes
	  fi
	dialog --title "Meta-backup" --inputbox "$DIALOG6" 8 40 2> /tmp/meta-backup/save	## move the debs to selected location
	    SAVE=`cat /tmp/meta-backup/save`
	    dialog --title "Meta-backup" --infobox "..." 8 40
	    ls $SAVE
	  if [ $? = 0 ] ; then
	    mv /tmp/meta-backup/*.deb $SAVE
	    chmod 777 $SAVE/my-*-backup.deb
	  else
	    mkdir -p $SAVE
	    mv /tmp/meta-backup/*.deb $SAVE
	    chmod -R 777 $SAVE
	  fi
	if [ $ERROR = no ] ; then								## Display exit message
	  dialog --title "Meta-backup" --infobox "$DIALOG2" 8 40
	 else
	  dialog --title "Meta-backup" --infobox "$DIALOG3" 8 40
	fi
	rm -rf /tmp/meta-backup									## cleaning up
}

###### Automatically inputs aliases here in'.bashrc' - Usage: mkalias <name> "<command>" Example: mkalias rm "rm -i"
function mkalias()
{
        if [[ $1 && $2 ]]
        then
        echo -e "alias $1=\"$2\"" >> ~/.bashrc
        alias $1=$2
        fi
}

# Makes directory then moves into it		 #
#------------------------------------------////

####### mkcdr
#function mkcdr() { mkdir -p -v $1 cd $1; }

####### mkdircd
function mkdircd()	{ mkdir -p "$@" && eval cd "\"\$$#\""; }

####### mktar - Creates an archive from directory
function mktar() { tar cvf  "${1%%/}.tar"     "${1%%/}/"; }

####### mktbz - Creates an archive from directory
function mktbz() { tar cvjf "${1%%/}.tar.bz2" "${1%%/}/"; }

####### mktgz - Creates an archive from directory
function mktgz() { tar cvzf "${1%%/}.tar.gz"  "${1%%/}/"; }

####### Reminder / to do list	
function mnote()
{
    echo -e "- $* \n" >> ~/todo
    echo -e "- $* \n" >> ~/todo.perm
    ~/motd.pl
}

###### Morse code encoding and decoding - this is a short Morse code decoder written as a shellscript using sed the Morse coded text should be written with spaces between the letters only good to convert from Morse code to text
function morse2text()
{
	echo $1\  | tr . 0 | sed -e {s/0----\ /1/g} -e {s/00---\ /2/g} -e {s/000--\ /3/g} -e {s/000-\ /4/g} -e {s/00000\ /5/g} -e {s/-0000\ /6/g} -e {s/--000\ /7/g} -e {s/---00\ /8/g} -e {s/----0\ /9/g} -e {s/-----\ /0/g} \
	    | sed -e {s/-0-0\ /c/g} -e {s/-000\ /b/g} -e {s/00-0\ /f/g} -e {s/0000\ /h/g} -e {s/0---\ /j/g} -e {s/0-00\ /l/g} -e {s/0--0\ /p/g} -e {s/--0-\ /q/g} -e {s/000-\ /v/g} -e {s/-00-\ /x/g} -e {s/-0--\ /y/g} -e {s/--00\ /z/g} \
	    | sed -e {s/0--\ /w/g} -e {s/-00\ /d/g} -e {s/--0\ /g/g} -e {s/-0-\ /k/g} -e {s/---\ /o/g} -e {s/0-0\ /r/g} -e {s/000\ /s/g} -e {s/00-\ /u/g} \
	    | sed -e {s/0-\ /a/g} -e {s/00\ /i/g} -e {s/--\ /m/g} -e {s/-0\ /n/g} \
	    | sed -e {s/0\ /e/g} -e {s/-\ /t/g}
}

function text2morse()
{
cat > "/tmp/text2morse.py" <<"End-of-message"
#!/usr/bin/python
# short mark, dot or 'dit' (.) = .
# longer mark, dash or 'dah' (-) = -
# intra-character gap (between the dots and dashes within a character) = no space
# short gap (between letters) = single space
# medium gap (between words) = double space
import sys
__author__="Aanand Natarajan"
# morse code dictionary
codes = {'1':".----",'2':"..---",'3':"...--",'4':"....-",'5':".....",'6':"-....",'7':"--...",'8':"---..",
'9':"----.",'0':"-----",'A':".-",'B':"-...",'C':"-.-.",'D':"-..",'E':".",'F':"..-.",'G':"--.",
'H':"....",'I':"..",'J':".---",'K':"-.-",'L':".-..",'M':"--",'N':"-.",'O':"---",'P':".--.",
'Q':"--.-",'R':".-.",'S':"...",'T':"-",'U':"..-",'V':"...-",'W':".--",'X':"-..-",'Y':"-.--",
'Z':"--..",
# punctuations
',':"--..--",'.':".-.-.-",'?':"..--..",';':"-.-.-",':':"---...",'/':"-..-.",
'-':"-....-","'":".----.",'(':"-.--.",')':"-.--.-",'!':"-.-.--",'&':".-...",
'=':"-...-",'+':".-.-.",'_':"..--.-",'"':".-..-.",'$':"...-..-",'@':".--.-.",
# space
' ':"|"}
binary = {'.':'.','-':'-',',':' ','|':'  '}
def encode(value):
    """ encodes the value into morse code """
    morse_value=""
    value.replace('*', 'X')
    value.replace('^', 'XX')
    for c in value:
       try :
               morse_value += codes[c.upper()]+','
       except :
         print "Unintended character " + c + " omitted"
    return _get_binary(morse_value)
def decode(morse_code_value):
    """ decodes the morse bytes """
    decoded_value = _decode_binary(morse_code_value)
    ascii_value=""
    for v in decoded_value.split(","):
        ascii_value += _get_key(v)
    return ascii_value
def _get_binary(value):
     binary_value = ""
     for c in value:
         binary_value += binary[c]
     return binary_value
def _get_key(value):
     """ returns the key for the given value """
     for k,v in codes.items():
         if v == value:
            return k
     return ''
def _decode_binary(binary):
    dah_replaced = binary.replace('-', '-')
    dit_replaced = dah_replaced.replace('.', '.')
    comma_replaced = dit_replaced.replace(' ', ',')
    zero_replaced = comma_replaced.replace('', '|,')
    return zero_replaced
def _do_decode(value):
    print "Decoded : "+decode(value)
def _do_encode(value):
    print "Encoded : "+encode(value)
if __name__ == "__main__":
   if len(sys.argv) > 2:
      if sys.argv[1] == 'd' :
         print "decoding"
         _do_decode(sys.argv[2])
      else:
         print "encoding"
         _do_encode(sys.argv[2])
   elif len(sys.argv) > 1:
        print "encoding"
        _do_encode(sys.argv[1])
   else:
        print "Usage : "+sys.argv[0]+" [d (decode) |e (encode)] [input string]"
End-of-message
chmod +x "/tmp/text2morse.py"
"/tmp/text2morse.py" "$1"
rm "/tmp/text2morse.py"
}

####### Computes most frequent used words of text file usage:	most_frequent "file.txt"
function most_frequent()
{
	cat "$1" | tr -cs "[:alnum:]" "\n"| tr "[:lower:]" "[:upper:]" | awk '{h[$1]++}END{for (i in h){print h[i]" "i}}'|sort -nr | cat -n | head -n 30
}

####### Mount Fat					 #
function mount_fat()
{
    local _DEF_PATH="/media/tmp1"
    if [ -n "$2" ];then
        sudo mount -t vfat -o rw,users,flush,umask=0000 "$1" "$2"
    else
        sudo mount -t vfat -o rw,users,flush,umask=0000 "$1" $_DEF_PATH
    fi
}

# Flash Video Cache Finder/Saver		 #
#------------------------------------------////

###### flash video cache finder - Find cached video while watching and without needing downloader extensions Type moz at a prompt to find the vid. Tested with Firefox (Icecat), Chromium, Midori, Uzbl, Konqueror, and Arora
function moz()
{
	# Make sure we have lsof
	if  [ -x /usr/sbin/lsof ]; then
	    LSOF=/usr/sbin/lsof
	elif [ -x /usr/bin/lsof ]; then
	    LSOF=/usr/bin/lsof
	elif [ -x /usr/local/bin/lsof ]; then
	    LSOF=/usr/local/bin/lsof
	else
	    echo "lsof was not found... exiting"
	    return 1
	fi
	# Find a process ID and go there
	PROCDIR=$( $LSOF -X | grep Flash | tail -n1 | awk '{ print $2 }' )
	# Not found? exit gracefully
	if [ "$PROCDIR" == "" ]; then
	    echo "No running instance found"
	    return 1
	fi
	cd /proc/$PROCDIR/fd
	# Stat through the file descriptors looking for video
	MQ=$( for i in *; do stat $i | head -n1 | grep "tmp/Flash" | awk '{ print $2 }'; done )
	# Another exit point
	if [ "$MQ" == "" ]; then
	    echo "No video found"
	    return 1
	fi
	#Finally, print them all out
	for i in $MQ; do
	    j=${i#?}
	    echo "Video at "${j%?}
	done
}

###### flash video cache saver - Find cached flash video and copy to user's home directory - Usage: mozz [filename] (where filename is the name you want to save as)
function mozz()
{
	# Check for given filename
	if [ $# -ne 1 ]; then
	    echo "Usage: mozz [filename]"
	    exit 65
	fi
	# Make sure we have lsof
	if  [ -x /usr/sbin/lsof ]; then
	    LSOF=/usr/sbin/lsof
	elif [ -x /usr/bin/lsof ]; then
	    LSOF=/usr/bin/lsof
	elif [ -x /usr/local/bin/lsof ]; then
	    LSOF=/usr/local/bin/lsof
	else
	    echo "lsof was not found... exiting"
	    exit 1
	fi
	# Look for flvs in user's home - if not, create one
	if [ ! -d $HOME/flvs ]; then
	    echo -e "\033[0;31mCreating " $HOME"/flvs"
	    mkdir -v $HOME"/flvs"
	fi
	# Find a process ID and go there
	PROCDIR=$( $LSOF -X | grep Flash | tail -n1 | awk '{ print $2 }' )
	# Not found? exit gracefully
	if [ "$PROCDIR" == "" ]; then
	    echo "No running instance found"
	    exit 1
	fi
	# To warn us if nothing happens
	flvflag=0
	# Stat through FDs and copy the first
	for i in /proc/$PROCDIR/fd/*; do
	    j=$( stat $i | head -n1 | grep "tmp/Flash")

	    if [ ${#j} -gt 0 ]; then
		k=$( echo $j | awk '{ print $2 }' )
		l=${k#?}
		m=$( cp -v ${l%?} $HOME"/flvs/"$1".flv" )
		echo -e "\033[0;32m$m"
		echo -e "\033[0;34mCurrent filesize: \033[0;35m"$( stat --format=%s $HOME"/flvs/"$1".flv" )
		flvflag=1
		break
	    fi
	done
	# Echo the warning
	if [ $flvflag -eq 0 ]; then
	    echo "Warning: no video was copied"
	fi
}

####### Messagebox maker	- msg "Title of Message Box" or msg "Title of Message Box" $height $width
function msg()
{
   # function for making a messagebox
   # if it has less than two arguments
   if [[ $# < 2 ]]
   then
      # use auto-size for the messagebox
      dialog --msgbox "$1" 0 0
   else
      # use specified height and width
      dialog --msgbox "$1" $2 $3
   fi
   clear
}

# Youtube stuff					 #
#------------------------------------------////

###### stream YouTube videos directly to your media player
function mtube() {
  video_id=$(curl -s $1 | sed -n "/watch_fullscreen/s;.*\(video_id.\+\)&title.*;\1;p");
  mplayer -fs $(echo "http://youtube.com/get_video.php?$video_id");
}

alias mtube_='mplayer -fs $(echo "http://youtube.com/get_video.php?$(curl -s "$1" | sed -n "/watch_fullscreen/s;.*\(video_id.\+\)&title.*;\1;p")")'

###### mps-youtube - requires "python-pip" and mps-youtube - sudo apt-get install python-pip - sudo pip install mps-youtube - sudo pip install mps-youtube --upgrade 
# alias youtube='mpsyt'

###### Youtube-dl - requires "youtube-dl" sudo apt-get install youtube-dl
# alias yt='youtube-dl -t'

###### YouTube convert and download all user's videos to MP3s on the fly
function yt2mp3() { for j in `seq 1 301`;do i=`curl -s gdata.youtube.com/feeds/api/users/$1/uploads\?start-index=$j\&max-results=1|grep -o "watch[^&]*"`;ffmpeg -i `wget youtube.com/$i -qO-|grep -o 'url_map"[^,]*'|sed -n '1{s_.*|__;s_\\\__g;p}'` -vn -ab 128k "`youtube-dl -e ${i#*=}`.mp3";done;}

function yt2mp3-chanrip() { for count in 1 51 101 151 201 251 301; do for i in $(curl -s http://gdata.youtube.com/feeds/api/users/"$1"/uploads\?start-index="$count"\&max-results=50 | grep -Eo "watch\?v=[^[:space:]\"\'\\]{11}" | uniq); do ffmpeg -i $(wget http://youtube.com/"$i" -qO- | sed -n "/fmt_url_map/{s/[\'\"\|]/\n/g;p}" | sed -n '/^fmt_url_map/,/videoplayback/p' | sed -e :a -e '$q;N;5,$D;ba' | tr -d '\n' | sed -e 's/\(.*\),\(.\)\{1,3\}/\1/') -vn -ab 128k "$(youtube-dl -e http://youtube.com/"$i").mp3"; done; done; unset count i; }

###### convert to ogg
function yt2ogg() {
    
    ffmpeg -i "$1" -vn "$1".ogg
}

###### play YouTube's first match directly
function ytplay() { args="$*";mplayer -fs $(youtube-dl -g "http://www.youtube.com$(lynx --source "http://www.youtube.com/results?search_query=${args// /+}&aq=f"|grep -m1 '<a id=.*watch?v=.*title'|cut -d\" -f4)"); }

###### download entire YouTube channel - all of a user's videos					 #
function yt-chanrip() { for i in $(curl -s http://gdata.youtube.com/feeds/api/users/"$1"/uploads | grep -Eo "watch\?v=[^[:space:]\"\'\\]{11}" | uniq); do youtube-dl --title --no-overwrites http://youtube.com/"$i"; done }

###### download YouTube music playlist and convert it to mp3 files
function yt-pl2mp3() { umph -m 50 $1 | cclive -f mp4_720p; IFS=$(echo -en "\n\b"); for track in $(ls | grep mp4 | awk '{print $0}' | sed -e 's/\.mp4//'); do (ffmpeg -i $track.mp4 -vn -ar 44100 -ac 2 -ab 320 -f mp3 $track.mp3); done; rm -f *.mp4 ; }

####### Find artist and title of music cd, UPC code given
function musiccdinfo()
{
	wget http://www.discogs.com/search?q=724349691704 -O foobar &> /dev/null ; grep \/release\/ foobar | head -2 | tail -1 | sed -e 's/^<div>.*>\(.*\)<\/a><\/div>/\1/' ; rm foobar
}

####### Query Wikipedia via console over DNS		 #
function mwiki() { blah=`echo $@ | sed -e 's/ /_/g'`; dig +short txt $blah.wp.dg.cx; }

# function mwiki() { dig +short txt `echo $*|sed 's| *|_|g'`.wp.dg.cx; }
function mwiki_() { local IFS=_; dig +short txt "${*^}".wp.dg.cx; }

####### User friendly ps
function my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,bsdtime,command ; }

function pp() { my_ps f | awk '!/awk/ && $0~var' var=${1:-".*"} ; }

function psaux() {
    [ $# == 1 ] && ps aux | grep $1
}

# 'Readlink' equivalent using shell commands, and following all links	
#------------------------------------------////

###### this is equivalent to the GNU ' readlink' tool, but it supports following all links, even in different directories
# myreadlink() { [ ! -h "$1" ] && echo "$1" || (local link="$(expr "$(command ls -ld -- "$1")" : '.*-> \(.*\)$')"; cd $(dirname $1); myreadlink "$link"; }

# Editor startup, should be transparent for different versions
#------------------------------------------////
# function ned()
# {   if [[ -n `which neditc` ]] ; then
#         neditc $@
#     elif [[ -n `which nedit` ]] ; then
#         nedit $@ >&/dev/null &
#     else
#         echo NEdit does not appear to be on this computer.
#     fi
# }

####### For newbies with Linux			 #
function newbies()
	{
	read -sn 1 -p "1/10. Welcome to Ubuntu. Relax. Take a breath. Just because it's not Windows doesn't mean it will be difficult to figure out. Especially with me at the wheel. ;)

	"
	read -sn 1 -p "ﻲ/10. Ubuntu is an operating system, just like Windows (ie. XP, Vista, 7). It is a Linux distro, meaning it uses the Linux kernel, which is essentially the brains of the operating system. Ubuntu is highly customizable, and I have tweaked it to look similar to Windows, but it can look, feel, and run any way you'd like. Unlike Windows, Ubuntu is free, as well as nearly all of it's applications. Less than 1% of the world uses Linux; about half of that use Ubuntu (#1 ranked Linux distro)). And due to this, and the fact that it's structure is different than Windows, it is pretty much virus-free. Also, no Windows viruses can ever harm a Linux/Ubuntu computer. So download away.

	"
	read -sn 1 -p "3/10. Your computer's username is 'Me'. Your computer's password is 'password'. The password can easily be changed.

	"
	read -sn 1 -p "ﻴ/10. To change the password, you must change both the User and the Default Keyring passwords. First, change the user password, by going to Menu (bottom left button) -> System -> Preferences -> About Me and click 'Change Password...'. Second, change the Default Keyring password by going to Menu (bottom left button) -> Accessories -> Passwords and Encryption Keys and find 'Passwords: default', click it with the right mouse button, and select 'Change Password'.

	"
	read -sn 1 -p "5/10. Ubuntu updates and upgrades are currently set up to install important security updates as well as to pop up a box prompting you to click install when anything else requires an upgrade. Very easy. Just need password. One thing about updates on Ubuntu is it updates everything, both the operating system and the installed applications through the repositories (official and unofficial servers that house a large number of various applications and games).

	"
	read -sn 1 -p "6/10. Your home folder (similar to a 'My Documents' folder in Windows) is 'me', and can be opened either by going to Menu (bottom left button) -> Places -> Home Folder, OR double-clicking the left mouse button on 'me's Home' on the Desktop. The 'Temp' folder inside is what is set for all downloads and is my ideal for using as the working folder for whatever you want. In the 'Pictures' folder, there is a 'Backgrounds' folder that includes all of your desktop backgrounds and is where you can add or remove backgrounds.

	"
	read -sn 1 -p "7/10. There are some application subsitutes to mention: [OpenOffice -> Microsoft Office], [(Totem) Movie Player -> Windows Media Player], [Evolution Mail -> Microsoft Outlook or Outlook Express], [Nautilus File Manager -> Windows Explorer].

	"
	read -sn 1 -p "8/10. If you'd like to add/remove software, Ubuntu has a very easy way to do so. Just go to the Ubuntu Software Center, by going to Menu (bottom left button) -> Ubuntu Software Center. It lists all the software found in the repositories.

	"
	read -sn 1 -p "9/10. If you wish to open this extremely helpful text again, it's as easy as: single-clicking the right mouse button anywhere on the Desktop (or in Nautilus File Manager) -> Scripts -> My_Scripts -> For-Newbies -> For-Newbies.sh.

	"
	read -sn 1 -p "10/10. To get rid of this damn script at startup because you are sick of seeing it every time you log into your computer, go to Menu (bottom left button) -> Other -> Startup Applications and uncheck 'For Newbies'.

	"
}

####### Download all data from Google Ngram Viewer
function ngramviewerdl()
{
	wget -qO - http://ngrams.googlelabs.com/datasets | grep -E href='(.+\.zip)' | sed -r "s/.*href='(.+\.zip)'.*/\1/" | uniq | while read line; do `wget $line`; done
}

######## Run command detached from terminal and without output - Usage: nh
function nh() {
    nohup "$@" &>/dev/null &
}

####### Stupid simple note taker			 #
function note()
{
        # if file doesn't exist, create it
        [ -f $HOME/.notes ] || touch $HOME/.notes
        # no arguments, print file
        if [ $# = 0 ]
        then
                cat $HOME/.notes
        # clear file
        elif [ $1 = -c ]
        then
                > $HOME/.notes
        # add all arguments to file
        else
                echo "$@" >> $HOME/.notes
        fi
}

####### Open a new terminal tab in the same directory as the current	- SOURCE => http://pastie.caboo.se/188640 AND => http://justinfrench.com/index.php?id=231
function nth() {
  osascript -e "
  Tell application \"Terminal\"
    activate
    tell application \"System Events\" to tell process \"Terminal\" to keystroke \"t\" using command down
    do script with command \"cd '$(pwd)'; clear\" in selected tab of the front window
  end tell"
}

####### Remove apps with style: nuke it from orbit
#------------------------------------------////

###### You can't stand programs x, y, and z. Remove all trace of their existence by adding this function to your config. It will remove the cruft, the settings, #and such and such. This function doesn't even give a damn about you trying to remove programs that don't exist: it'll just for loop to the next one on #your hit list.
function nuke() { if [ $(whoami) != "root" ] ; then for x in $@; do sudo apt-get autoremove --purge $x; done; else for x in $@; do apt-get autoremove --purge $x; done; fi }

####### Echo the lines of a file preceded by line	number
function numberLines() { perl -pe 's/^/$. /' "$@" ; }

####### How many pages will my text files print on?
function numpages() { echo $(($(wc -l $* | sed -n 's/ total$//p')/60)); }

####### Open a GUI app from CLI
function open() {
  $1 >/dev/null 2>&1 &
}

####### Display file contents either with less or cat
# based on number of lines			 #
#------------------------------------------////

function out() { tmp=$(mktemp); awk '{print $0}' > $tmp; if [ $(wc -l $tmp | awk '{print $1}') -gt $(tput lines) ]; then less $tmp; else cat $tmp; fi; rm -fr $tmp; }

####### Convert a single-page PDF to a hi-res PNG, at 300dpi - If you skip this part: -density 300x300, you'll get a very lo-res image
function pdf2png()
{
	convert -density 300x300 $1 $2
}

####### ThePirateBay.org torrent search	
function piratebay()
{
	lynx -dump http://thepiratebay.org/search/$@|awk '/TPB.torrent$/ {print $2}'
}

####### Optimize PNG files
function pngoptim()
{
		  NAME_="pngoptim"
		  HTML_="optimize png files"
	    PURPOSE_="reduce the size of a PNG file if possible"
	   SYNOPSIS_="$NAME_ [-hl] <file> [file...]"
	   REQUIRES_="standard GNU commands, pngcrush"
	    VERSION_="1.0"
		  DATE_="2004-06-29; last update: 2004-12-30"
		AUTHOR_="Dawid Michalczyk <[email protected]>"
		   URL_="www.comp.eonworks.com"
	   CATEGORY_="gfx"
	   PLATFORM_="Linux"
		 SHELL_="bash"
	 DISTRIBUTE_="yes"
	# This program is distributed under the terms of the GNU General Public License
	usage() {
	echo >&2 "$NAME_ $VERSION_ - $PURPOSE_
	Usage: $SYNOPSIS_
	Requires: $REQUIRES_
	Options:
		-h, usage and options (this help)
		-l, see this script"
	exit 1
	}
	# tmp file set up
	tmp_1=/tmp/tmp.${RANDOM}$$
	# signal trapping and tmp file removal
	trap 'rm -f $tmp_1 >/dev/null 2>&1' 0
	trap "exit 1" 1 2 3 15
	# var init
	old_total=0
	new_total=0
	# arg handling and main execution
	case "$1" in
	    -h) usage ;;
	    -l) more $0; exit 1 ;;
		*.*) # main execution
		   # check if required command is in $PATH variable
		   which pngcrush &> /dev/null
		   [[ $? != 0 ]] && { echo >&2 required \"pngcrush\" command is not in your PATH; exit 1; }
		   for a in "$@";do
			  if [ -f $a ] && [[ ${a##*.} == [pP][nN][gG] ]]; then
				 old_size=$(ls -l $a | { read b c d e f g; echo $f ;} )
				 echo -n "${NAME_}: $a $old_size -> "
				 pngcrush -q $a $tmp_1
				 rm -f -- $a
				 mv -- $tmp_1 $a
				 new_size=$(ls -l $a | { read b c d e f g; echo $f ;} )
				 echo $new_size bytes
				 (( old_total += old_size ))
				 (( new_total += new_size ))
			  else
				 echo ${NAME_}: file $a either does not exist or is not a png file
			  fi
		   done ;;
	    *) echo ${NAME_}: skipping $1 ; continue ;;
	esac
	percentage=$(echo "scale = 2; ($new_total*100)/$old_total" | bc)
	reduction=$(echo $(( old_total - new_total )) \
	| sed '{ s/$/@/; : loop; s/\(...\)@/@.\1/; t loop; s/@//; s/^\.//; }')
	echo "${NAME_}: total size reduction: $reduction bytes (total size reduced to ${percentage}%)"
}

####### Display text of ODF document in terminal   $1 = ODF file
function o3() { unzip -p "$1" content.xml | o3totxt | utf8tolatin1; }

####### Random data overwriting			 #
#------------------------------------------////
function overwriter()
{
	# The author of this script, Elias Amaral,
	# claims no copyright over it.
	# http://iamstealingideas.wordpress.com/2010/05/20/writing-random-data-to-a-hard-drive-again
	msg() {
	  printf "\n - $1\n\n" $2
	}
	mbs=4 # 4mb
	blocksize=$(($mbs * 1024 * 1024))
	dev=$1
	if [[ -z $dev ]]; then
	  msg "usage: $0 <device>"; exit
	elif [[ ! -b $dev ]]; then
	  msg "$dev: not a block device"; exit
	elif [[ ! -w $dev ]]; then
	  msg "$dev: no write permission"; exit
	elif grep -q $dev /etc/mtab; then
	  msg "$dev: mounted filesystem on device, omgomg!"; exit
	fi
cat <<end
This program writes random data to a hard disk.
It is intended to be used before storing encrypted data.
It may contain bugs (but seems to work for me).
It seems you have chosen to wipe data from the disk $dev.
Here is the partition table of this disk:
end
	fdisk -l $dev
	echo
	echo 'Are you sure you want to proceed?'
	msg 'WARNING: IT WILL DESTROY ALL DATA ON THE DISK'
	read -p 'Type uppercase yes if you want to proceed: ' q
	if [[ $q != YES  ]]; then
	  exit
	fi
	while
	  echo $i > step.new
	  mv step.new step
	  msg 'Writing at offset %s' $(($mbs * $i))M
	  openssl rand \
			-rand /dev/urandom \
			$blocksize | \
	  dd of=$dev \
		bs=$blocksize \
		seek=$i
	do
	  let i++
	done
	msg Finished.
}
alias overwriter_='sudo dd if=/dev/zero bs=1M | openssl bf-cbc -pass pass:`cat /dev/urandom | tr -dc [:graph:] | head -c56` | sudo dd of=$dev bs=1M'

####### Ownership Changes { own file user }
function own() { chown -R "$2":"$2" ${1:-.}; }

####### packagehold Hold packages
function packagehold()
{
	echo -n "Please enter the package you wish to put a hold on:
	"
	read progID
	echo "$progID hold" |sudo dpkg --set-selections
}

###### packageunhold  Unhold packages
function packageunhold()
{
	echo -n "Please enter the package you wish to remove the hold on:
	"
	read progID
	echo "$progID install" |sudo dpkg --set-selections
}

####### Download all installed deb packages from official repos currently on system		 #
function packagelistdl()
{
	sudo dpkg --get-selections | awk '{ print $1};' | while read package; do apt-cache show "$package"| wget -c 'http://ae.archive.ubuntu.com/ubuntu/'`sed -ne '/^Filename/s/^Filename: //p'`; done
}

####### Pacman Search
function pacsearch() {
       echo -e "$(pacman -Ss $@ | sed \
       -e 's#core/.*#\\033[1;31m&\\033[0;37m#g' \
       -e 's#extra/.*#\\033[0;32m&\\033[0;37m#g' \
       -e 's#community/.*#\\033[1;35m&\\033[0;37m#g' \
       -e 's#^.*/.* [0-9].*#\\033[0;36m&\\033[0;37m#g' )"
}

####### Paste command output to www.pastehtml.com in txt format					 #
function paste() { curl -s -S --data-urlencode "txt=$($*)" "http://pastehtml.com/upload/create?input_type=txt&result=address";echo; }

####### Removes duplicate pathsNOTE: symlinks aren't dereferenced (e.g., using `readlink`) as they may exist for compatibility reasons
function pathremove() {
    local IFS=':'
    local newpath
    local i

    for i in ${!2}; do
        if [ "$i" != "$1" ]; then
            newpath=${newpath:+$newpath:}$i
        fi
    done
    export $2="$newpath"
}

####### Print character classes			 #
function pcharc() { perl -e 'for (0..255) {$_ = chr($_); print if /['$1']/}' | cat -v; echo; }

####### Quick plot of numbers on stdin (can also pass - plot paramaters) - requires gnuplot: sudo apt-get install gnuplot example: seq 1000 | sed 's/.*/s(&)/' | bc -l | plot linecolor 2
function plot() { { echo 'plot "-"' "$@"; cat; } | gnuplot -persist; }

####### Scans a port, returns what's on it.
function port() {
	lsof -i :"$1"
}

####### Portscan in one line
function portscan()
{
	$HOST=127.0.0.1;for((port=1;port<=65535;++port));do echo -en "$port ";if echo -en "open $HOST $port\nlogout\quit" | telnet 2>/dev/null | grep 'Connected to' > /dev/null;then echo -en "\n\nport $port/tcp is open\n\n";fi;done
}

####### Use Perl like grep
function prep() { perl -nle 'print if '"$1"';' $2 ; }

####### Find the printer driver (ppd) type being used
function printdriver() {
        lpoptions -d $1 | grep -oe "printer-make-and-model='.*'" | cut -f2 -d "=" | sed -r s/\'//g
}

######## Print a row of characters across the terminal - Default character is "=", default color is white
function println()
{
	echo -n -e "\e[038;05;${2:-255}m";printf "%$(tput cols)s"|sed "s/ /${1:-=}/g"
}

# Pronounce an English word - usage:	pronounce "word1" "word2" "word3" "..."
function pronounce() { for a in $@; do wget -qO- $(wget -qO- "http://www.m-w.com/dictionary/$a" | grep 'return au' | sed -r "s|.*return au\('([^']*)', '([^'])[^']*'\).*|http://cougar.eb.com/soundc11/\2/\1|") | aplay -q; done }

###### usage:	pronounce_ "word1" "word2" "word3" "..." requires 'mpg123' - sudo apt-get install mp321, but better dictionary
function pronounce_() { wget -qO- $(wget -qO- "http://dictionary.reference.com/browse/$@" | grep 'soundUrl' | head -n 1 | sed 's|.*soundUrl=\([^&]*\)&.*|\1|' | sed 's/%3A/:/g;s/%2F/\//g') | mpg123 -; }

####### Pull a single file out of a .tar.gz
function pullout() {
  if [ $# -ne 2 ]; then
    echo "need proper arguments:"
    echo "pullout [file] [archive.tar.gz]"
    return 1
  fi
  case $2 in
    *.tar.gz|*.tgz)
    gunzip < $2 | tar -xf - $1
    ;;
    *)
    echo $2 is not a valid archive
    return 1
    ;;
  esac
  return 0
}

####### Create QR codes from a URL
function qrurl() { curl -sS "http://chart.apis.google.com/chart?chs=200x200&cht=qr&chld=H|0&chl=$1" -o - | display -filter point -resize 600x600 png:-; }

####### Email yourself a short note			 #
#------------------------------------------////

function quickemail() { echo "$*" | mail -s "$*" [email protected]; }

####### Suppress output of loud commands you don't want to hear from					 #
function quietly() { "$@" |&:; }

function Quietly() { "$@" > /dev/null 2>&1; }

function quietly_() { $* 2> /dev/null > /dev/null; }

####### Turning on and off Internet radio
function radio() { if [ "$(pidof mpg123)" ] ; then killall mpg123; else mpg123 -q -@ http://173.236.29.51:8200 & fi }

####### Scroll file one line at a time (w/only UNIX base tools) - usage:	rd < file ; or ... | rd
function rd_() { IFS='<ctrl-m>';$@;for i in `sed 's.\\\.\\\134.g;s.%.\\\045.g'`;do printf "$i$IFS";sleep 1;done ; }

####### TTS
function readfile() { curl -sGA Mozilla -d "language=en&format=audio/mp3&options=MaxQuality&appid=To6RoRW0R9Pt9emvqxsqEImBiS_ElZ19Dxpu9j6WURkg*&text=`python3 -c 'from urllib.parse import quote_plus; from sys import stdin; print(quote_plus(stdin.read()))' <${1:?file name is empty}`" 'http://api.microsofttranslator.com/V2/Http.svc/Speak' | mpg321 -q -; }

####### Copy Relinux backups to '~/Backups' folder (only after Relinux has backed-up stuff)
function relinux-copy()
# requires: relinux (not yet available in PPA/repo)
{
    notify-send -t 3000 -i /usr/share/icons/gnome/32x32/status/info.png "Relinux ISO Copy Started"
    DISTRIB_ID=`cat /etc/lsb-release | grep DISTRIB_ID | cut -d '=' -f 2`
    DISTRIB_CODENAME=`lsb_release -cs | sed "s/^./\u&/"`
    if [ ! -d "$HOME/Backups" ]; then
    mkdir "$HOME/Backups"
    fi
    if [ ! -d "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`" ]; then
    mkdir "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
    cd "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
    echo 'Password:		password' >> Password.txt
    cp /home/relinux/custom.iso "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
    cd ..
    cd ..
    notify-send -t 3000 -i /usr/share/icons/gnome/32x32/status/info.png "Relinux ISO Copy Finished"
    else
    mkdir "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y_%H%M`"
    cd "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y_%H%M`"
    echo 'Password:		password' >> Password.txt
    cp /home/relinux/custom.iso "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y_%H%M`"
    cd ..
    cd ..
    notify-send -t 3000 -i /usr/share/icons/gnome/32x32/status/info.png "Relinux ISO Copy Finished"
    fi ;
}

####### Copy Remastersys backups to '~/Backups' folder (only after Remastersys has backed-up stuff)
#function remastersys-copy()
# requires: sudo apt-get install remastersys (Packet ist veraltet)
#{
#    notify-send -t 3000 -i /usr/share/icons/gnome/32x32/status/info.png "Remastersys ISO Copy Started"
#    DISTRIB_ID=`cat /etc/lsb-release | grep DISTRIB_ID | cut -d '=' -f 2`
#    DISTRIB_CODENAME=`lsb_release -cs | sed "s/^./\u&/"`
#    if [ ! -d "$HOME/Backups" ]; then
#    mkdir "$HOME/Backups"
#    fi
#    if [ ! -d "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`" ]; then
#    mkdir "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
#    cd "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
#    echo 'Password:		password' >> Password.txt
#    cp /home/remastersys/remastersys/custom-backup.iso "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
#    cd ..
#    cd ..
#    notify-send -t 3000 -i /usr/share/icons/gnome/32x32/status/info.png "Remastersys ISO Copy Finished"
#    else
#    mkdir "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y_%H%M`"
#    cd "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y_%H%M`"
#    echo 'Password:		password' >> Password.txt
#    cp /home/remastersys/remastersys/custom-backup.iso "$HOME/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y_%H%M`"
#    cd ..
#    cd ..
#    notify-send -t 3000 -i /usr/share/icons/gnome/32x32/status/info.png "Remastersys ISO Copy Finished"
#    fi ;
#}

####### Reminder for whatever whenever
function remindme()
{
	sleep $1 && zenity --info --text "$2" &
}

####### Remount a device
function remount() {
    
    DEVICE=$1
    shift
    mount -oremount,$@ $DEVICE
}

###### Repeats a command every x seconds - Usage: repeat PERIOD COMMAND
function repeat() {
    local period
    period=$1; shift;
    while (true); do
        eval "$@";
    sleep $period;
    done
}

####### Add repo
function repoadd() {
    
    reprepro -Vb "$REPO_HOME" include "$REPO_DIST" *.changes
    cd "$REPO_HOME"/dists/"$REPO_DIST"
    gpg -abs -o Release.gpg Release
}

####### Repository update check
function repository-update-check() {
cat > "/tmp/repository-update-check.sh" <<"End-of-message"
#!/bin/bash
# created by unknown
# updated and tweaked by Inameiname (11 October 2011)
#Dependency check
    DEPENDENCIES="zenity curl"
    for dep in $DEPENDENCIES
    do
	which $dep &> /dev/null
	if [ $? -ne '0' ]
	then
	    echo "[ERR]: $dep Not Found in your path."
	    exit
	fi
    done
#Cleans last usage
    OLD_FILES="repositories"
    for old in $OLD_FILES
    do
	if [ -f /tmp/$old ];
	then
	    rm -fv -R /tmp/$old
	fi
    done
#Lists release, repos
    myrelease=$(grep 'DISTRIB_CODENAME' /etc/lsb-release | sed 's/DISTRIB_CODENAME=//' | head -1)
    #myrelease="saucy"
    repo_clean=$(ls /etc/apt/sources.list.d/ | grep -v .save)
    repo_list=$(cd /etc/apt/sources.list.d && cat $repo_clean /etc/apt/sources.list | grep deb\ http.* | sed -e 's/.*help\.ubuntu\.com.*//' -e 's/^#.*//' -e 's/deb\ //' -e 's/deb-src\ //' -e '/^$/d' | sort -u | awk '{print $1"|"$2}' | sed -e 's/\/|/|/' -e 's/-[a-z]*$//' | uniq && cd)
    #repo_list=$(cat dummy.sources.list | grep deb\ http.* | sed -e 's/.*help\.ubuntu\.com.*//' -e 's/^#.*//' -e 's/deb\ //' -e 's/deb-src\ //' -e '/^$/d' | sort -u | awk '{print $1"|"$2}' | sed -e 's/\/|/|/' -e 's/-[a-z]*$//' | uniq && cd)
    count_repos=$(echo $repo_list | wc -w)
    check_progress=$count_repos
    release_14="trusty"
    release_13="saucy"
    release_12="raring"
    release_11="quantal"
    release_10="precise"
    release_9="oneiric"
    release_8="natty"
    release_7="maverick"
    release_6="lucid"
    release_5="karmic"
    release_4="jaunty"
    release_3="intrepid"
    release_2="hardy"
    release_1="gutsy"
#Checks
    {
    for repo_0 in $repo_list
            do
	repo="$(echo $repo_0 | sed 's/|.*//')"
	rir="$(echo $repo_0 | sed 's/.*|//')"
            rir_list=$(curl --silent $repo/dists/ | grep -oi href\=\"[^\/].*/\" | sed -e 's/href\=\"//i' -e 's/\/\"//' -e 's/-.*//' -e 's/\ NAME.*//i' | sort -u | uniq)
	if [ '$rir_list' = '' ]
	then
	    rir_list=$(curl --silent $repo/ | grep -oi href\=\"[^\/].*\" | sed -e 's/href\=\"//i' -e 's/\/\"//' -e 's/-.*//' -e 's/\ NAME.*//i' -e 's/\/index\.html\"//' -e 's/.*".*//' -e 's/http.*//' | sort -u | uniq)
	fi
	#(I guess one will find something more elegant here)
	if [ $(echo "$rir_list" | grep -o $myrelease) ]
            then
                    echo "$myrelease " >> /tmp/repositories
            fi
	if [ '$rir_list' = '' ]
	then
	    echo "$myrelease " >> /tmp/repositories
	fi
            if [ $(echo "$rir_list" | grep -oi $release_14) ]
            then
                    r14="yes"
                    else
                    r14="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_13) ]
            then
                    r13="yes"
                    else
                    r13="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_12) ]
            then
                    r12="yes"
                    else
                    r12="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_11) ]
            then
                    r11="yes"
                    else
                    r11="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_10) ]
            then
                    r10="yes"
                    else
                    r10="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_9) ]
            then
                    r9="yes"
                    else
                    r9="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_8) ]
            then
                    r8="yes"
                    else
                    r8="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_7) ]
            then
                    r7="yes"
                    else
                    r7="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_6) ]
            then
                    r6="yes"
                    else
                    r6="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_5) ]
	then
                    r5="yes"
        	else
                    r5="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_4) ]
	then
                    r4="yes"
        	else
                    r4="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_3) ]
	then
                    r3="yes"
        	else
                    r3="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_2) ]
	then
                    r2="yes"
        	else
                    r2="no"
            fi
            if [ $(echo "$rir_list" | grep -oi $release_1) ]
	then
                    r1="yes"
        	else
                    r1="no"
            fi
	#results
	if [ "$rir" = "$release_14" ]
	then
	    results="$repo [$r14] $r13 $r12 $r11 $r10 $r9 $r8 $r7 $r6 $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_13" ]
	then
	    results="$repo $r14 [$r13] $r12 $r11 $r10 $r9 $r8 $r7 $r6 $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_12" ]
	then
	    results="$repo $r14 $r13 [$r12] $r11 $r10 $r9 $r8 $r7 $r6 $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_11" ]
	then
	    results="$repo $r14 $r13 $r12 [$r11] $r10 $r9 $r8 $r7 $r6 $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_10" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 [$r10] $r9 $r8 $r7 $r6 $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_9" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 [$r9] $r8 $r7 $r6 $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_8" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 $r9 [$r8] $r7 $r6 $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_7" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 $r9 $r8 [$r7] $r6 $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_6" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 $r9 $r8 $r7 [$r6] $r5 $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_5" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 $r9 $r8 $r7 $r6 [$r5] $r4 $r3 $r2 $r1"
	elif [ "$rir" = "$release_4" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 $r9 $r8 $r7 $r6 $r5 [$r4] $r3 $r2 $r1"
	elif [ "$rir" = "$release_3" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 $r9 $r8 $r7 $r6 $r5 $r4 [$r3] $r2 $r1"
	elif [ "$rir" = "$release_2" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 $r9 $r8 $r7 $r6 $r5 $r4 $r3 [$r2] $r1"
	elif [ "$rir" = "$release_1" ]
	then
	    results="$repo $r14 $r13 $r12 $r11 $r10 $r9 $r8 $r7 $r6 $r5 $r4 $r3 $r2 [$r1]"
	else
	    echo "$myrelease " >> /tmp/repositories
	    results="$repo [yes] [yes] [yes] [yes] [yes] [yes] [yes] [yes] [yes] [yes] [yes] [yes] [yes] [yes]"

	fi
	#finds status and stores results
	if [ $(echo "$results" | grep -o "\[no\]" | uniq) ]
            then
                    status="Error"
	fi
            if [ $(echo "$results" | grep -o "\[yes\]" | uniq) ]
	then
                    status="Ok"
	fi
#		if [ $(echo "$results" | grep -o "\[yes\]" | uniq) ] && [ "$rir" \< "$myrelease" ] && [ -n $(echo "$results" | grep -o "\[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]" | uniq) ] && [ echo "rir_list" | $(awk '{print $14 $13 $12 $11 $10 $9 $8 $7 $6 $5 $4 $3 $2 $1}' | grep $myrelease) ]
#		then
#			status="Upgradeable"
#		fi
#		if [ $(echo "$results" | grep -o "\[yes\]" | uniq) ] && [ "$rir" \> "$myrelease" ] && [ -n $(echo "$results" | grep -o "\[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]\ \[yes\]" | uniq) ] && [ echo "rir_list" | $(awk '{print $14 $13 $12 $11 $10 $9 $8 $7 $6 $5 $4 $3 $2 $1}' | grep $myrelease) ]
#		then
#			status="Downgradeable"
#	        fi
	#TODO should be $status $repo $r14 $r13 $r12 $r11 $r10 $r9 $r8 $r7 $r6 $r5 $r4 $r3 $r2 $r1
	echo "$status $results" >> /tmp/repositories
	#Zenity progressbar
    	percent=$((100-$check_progress*100/$count_repos))
    	check_progress=$(($check_progress-1))
    	echo $percent
	done
    } | zenity --progress --percentage=0 --title="Repositories" --text="Scanning repositories..." --auto-close
#Displays nicely
    if [ "$(cat /tmp/repositories | grep -c $myrelease)" = "$count_repos" ]
    then
	zeni_text="All the repositories you use support the $myrelease release."
    elif [ "$(cat /tmp/repositories | grep -c $myrelease)" = "1" ]
    then
	zeni_text="Only $(cat /tmp/repositories | grep -c $myrelease) of your $count_repos activated repositories supports the $myrelease release."
    else
	zeni_text="$(($count_repos - $(cat /tmp/repositories | grep -c $myrelease))) of your $count_repos activated repositories don't support the $myrelease release."
    fi
    if [ "$((100+$count_repos*25))" -gt "600" ]
    then
	window_height="600"
    else
	window_height="$((100+$count_repos*22))"
    fi
    zenity --title "Repositories" --text "$zeni_text" --width 800 --height $window_height --list --column "Status" --column "Repository" --column "$release_14" --column "$release_13" --column "$release_12" --column "$release_11" --column "$release_10" --column "$release_9" --column "$release_8" --column "$release_7" --column "$release_6" --column "$release_5" --column "$release_4" --column "$release_3" --column "$release_2" --column "$release_1" $(cat /tmp/repositories | sed s/$myrelease//)
End-of-message
chmod +x "/tmp/repository-update-check.sh"
"/tmp/repository-update-check.sh"
rm -fv -R "/tmp/repositories"
rm -fv -R "/tmp/repository-update-check.sh"
}

####### Set permissions to "standard" values (644/755), recursive - Usage: resetp
function resetp() {
    chmod -R u=rwX,go=rX "$@"
}

####### X DISPLAY functions
function reset_display()
{
    if [ "$SHLVL" -eq 1 ]; then
        echo $DISPLAY > $HOME/.display
    else
        if [ -e $HOME/.display ]; then
            export DISPLAY=$(cat $HOME/.display)
        fi
    fi
}

######
function set_xtitle()
{
    if [ $TERM == "xterm" ]; then
        echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"
    fi
}
# if [ "$UID" -ne 0 ]; then
#     reset_display
# fi

####### Resize images
function resizeimg()
{
		  NAME_="resizeimg"
		  HTML_="batch resize image"
	    PURPOSE_="resize bitmap image"
	    PURPOSE_="resize bitmap image"
	   SYNOPSIS_="$NAME_ [-hlv] -w <n> <file> [file...]"
	   REQUIRES_="standard GNU commands, ImageMagick"
	    VERSION_="1.2"
		  DATE_="2001-04-22; last update: 2004-10-02"
		AUTHOR_="Dawid Michalczyk <[email protected]>"
		   URL_="www.comp.eonworks.com"
	   CATEGORY_="gfx"
	   PLATFORM_="Linux"
		 SHELL_="bash"
	 DISTRIBUTE_="yes"
	# This program is distributed under the terms of the GNU General Public License
	usage () {
		echo >&2 "$NAME_ $VERSION_ - $PURPOSE_
		Usage: $SYNOPSIS_
		Requires: $REQUIRES_
		Options:
			-w <n>, an integer referring to width in pixels; aspect ratio will be preserved
			-v, verbose
			-h, usage and options (this help)
			-l, see this script"
		    exit 1
	}
	gfx_resizeImage() {
	    # arg check
	    [[ $1 == *[!0-9]* ]] && { echo >&2 $1 must be an integer; exit 1; }
	    [ ! -f $2 ] && { echo >&2 file $2 not found; continue ;}
	    # scaling down to value in width
	    mogrify -geometry $1 $2
	}
	# args check
	[ $# -eq 0 ] && { echo >&2 missing argument, type $NAME_ -h for help; exit 1; }
	# var init
	verbose=
	width=
	# option and arg handling
	while getopts vhlw: options; do
	    case $options in
		   v) verbose=on ;;
		   w) width=$OPTARG ;;
		   h) usage ;;
		   l) more $0; exit 1 ;;
		  \?) echo invalid argument, type $NAME_ -h for help; exit 1 ;;
	    esac
	done
	shift $(( $OPTIND - 1 ))
	# check if required command is in $PATH variable
	which mogrify &> /dev/null
	[[ $? != 0 ]] && { echo >&2 the required ImageMagick \"mogrify\" command \
	is not in your PATH variable; exit 1; }
	for a in "$@";do
	    gfx_resizeImage $width $a
	    [[ $verbose ]] && echo ${NAME_}: $a
	done
}

####### Daemon management				 #
function restart() { sudo /etc/rc.d/$1 restart; }
function start() { sudo /etc/rc.d/$1 start; }
function stop() { sudo /etc/rc.d/$1 stop; }

####### Restart the windows, only once		 #
#------------------------------------------////
function restowin() { sudo grub-set-default 3 && sudo reboot; }

####### Use binary notation to chmod a file		 #
#------------------------------------------////
function right() { bc <<< "obase=8;ibase=2;$1"; }; # touch foo; chmod $(right 111111011) foo; ls -l foo

####### Rip a file with handbrake and good options
function rip() {
	handbrake -i /dev/dvd -o ${HOME}/${1}.mp4 -L -U -F -f mp4 -e x264 -b 4000 -B 192
 }

####### Log rm commands
function rm() {         
	workingdir=$( pwdx $$ | awk '{print $2}' )         /bin/rm $*         echo "rm $* issued at $(date) by the user $(who am i| awk '{print $1} ') in the directory ${workingdir}"  >> /tmp/rm.out ; 
}

# Using associative array to remove all files and directories under PWD except
function rmall_but() { declare -A keep;for arg;do keep[$arg]=1;done;for file in *;do [[ ${keep[$file]} ]] || rm -rf "$file";done; }

####### Remove an inode via inode number
function rminode() {
        find . -inum $1 -exec rm -i {} \;
}

####### Roll - archive wrapper - usage: roll <foo.tar.gz> ./foo ./bar
function roll()
{
  FILE=$1
  case $FILE in
    *.tar.bz2) shift && tar cjf $FILE $* ;;
    *.tar.gz) shift && tar czf $FILE $* ;;
    *.tgz) shift && tar czf $FILE $* ;;
    *.zip) shift && zip $FILE $* ;;
    *.rar) shift && rar $FILE $* ;;
  esac
}

####### Removing all extended attributes from a directory tree
function rr()
{
    for i in $(ls -Rl@ | grep '^    ' | awk '{print $1}' | sort -u); \
       do echo Removing $i ... >&2;  \
       find . | xargs xattr -d $i 2>/dev/null ; done
}

####### Make a backup before editing a file
function safeedit() {
	cp $1 ${1}.backup && vim $1
}

####### Sanitize - set file/directory owner and permissions to normal values (644/755) - usage: sanitize <file>
function sanitize()
{
  chmod -R u=rwX,go=rX "$@"
  chown -R ${USER}:users "$@"
}

####### Save a specified directory
function save() { /usr/bin/sed "/$@/d" ~/.dirs > ~/.dirs1; \mv ~/.dirs1 ~/.dirs; echo "$@"=\"`pwd`\" >> ~/.dirs; source ~/.dirs ; }

####### Save a file to ~/Temp	
function saveit() {
	cp $1 ${HOME}/Temp/${1}.saved
}

####### Screencasting with mplayer webcam window
function screencastw()
{
	mplayer -cache 128 -tv driver=v4l2:width=176:height=177 -vo xv tv:// -noborder -geometry "95%:93%" -ontop | ffmpeg -y -f alsa -ac 2 -i pulse -f x11grab -r 30 -s `xdpyinfo | grep 'dimensions:'|awk '{print $2}'` -i :0.0 -acodec pcm_s16le output.wav -an -vcodec libx264 -vpre lossless_ultrafast -threads 0 output.mp4
}

#Search package database			 #
#------------------------------------------////

###### search Gentoo package database (portage) using eix $1 = search term (package name)
# Search all available w/ desc.; show summary
function sd() { eix -FsSc "$1"; }  

# Search exact available; show details
function se() { eix -F "^$1\$"; }  

# Search installed; show summary
function si() { eix -FIc "$1"; }   

# Search all available; show summary
function sp() { eix -Fc "$1"; }     

###### search Arch package database using pacman - $1 = search term (package name
function sp() {
    echo -e "$(pacman -Ss "$@" | sed \
        -e 's#^core/.*#\\033[1;31m&\\033[0;37m#g' \
        -e 's#^extra/.*#\\033[0;32m&\\033[0;37m#g' \
        -e 's#^community/.*#\\033[1;35m&\\033[0;37m#g' \
        -e 's#^.*/.* [0-9].*#\\033[0;36m&\\033[0;37m#g' ) \
        \033[0m"
}

###### search Debian (or Ubuntu) package database (apt) using dpkg - $1 = search term (package name)
function sp() { apt-cache search "$1" | grep -i "$1"; }  # search all available

####### Sed /pat/!d without using sed (no RE; limited to shell patterns aka globbing) - usage: se pattern # use in place of sed /pat/!d where RE are overkill
function se_() { while read a;do [ "$a" != "${a#*$@*}" ]&&echo $a;done ; }

####### Search and replace words/phrases from text file usage:	searchnreplace "whatever oldtext" "whatever newtext" "file(s) to act on"
function searchnreplace()
{
	# Store old text and new text in variables
	old=$1;
	new=$2;
	# Shift positional parameters to places to left (get rid of old and
	# new from command line)
	shift;
	shift;
	# Store list of files as a variable
	files=$@;
	a='';
	for a in $files
	 do
	  temp=$(echo "/tmp/$LOGNAME-$a");
	# echo "$temp";
	  echo -n ".";
	  sed -e "s/$old/$new/g" $a > $temp;
	  mv $temp $a;
	 done
	echo;
	echo -e "Searched $# files for '$old' and replaced with '$new'";
}

####### Sed edit-in-place using -a option instead of -i option (no tmp file created)	
function sedi() { case $# in [01])echo usage: sedi cmds file;;2)sed -an ''"$1"';H;$!d;g;w '"$2"'' $2;;esac; }

####### Auto send an attachment from CLI
function send() {
	echo "File auto-sent from linux." | mutt -s "See Attached File" -a $1 $2
}

####### Manage services
function service() {
  if [ $# -lt 2 ]; then
    echo "Missing service name or command"
    return 1
  fi
  sudo /etc/init.d/$1 $2 && return 0
}

###### service() { /etc/rc.d/$1 $2; }
function service_() {
        if [ -n "$2"  ]
        then
                /etc/rc.d/$1 $2
        else
                echo    "All daemons"
                ls --ignore=functions* /etc/rc.d/
                echo    "Running daemons"
                ls /var/run/daemons
        fi
}

####### Create a new script, automatically populating the shebang line, editing the script, and making it executable.				 #
function shebang() { if i=$(which $1); then printf '#!%s\n\n' $i >  $2 && vim + $2 && chmod 755 $2; else echo "'which' could not find $1, is it in your \$PATH?"; fi; }

####### Shot - takes a screenshot of your current	 window					 #
function shot()
{
	import -frame -strip -quality 75 "$HOME/$(date +%s).png"
}

####### Create an easy to pronounce shortened URL from CLI
function shout() { curl -s "http://shoutkey.com/new?url=$1" | sed -n 's/\<h1\>/\&/p' | sed 's/<[^>]*>//g;/</N;//b' ;}

####### To remind yourself of an alias (given some part of it)
function showa() { /usr/bin/grep -i -a1 $@ ~/.aliases.bash | grep -v '^\s*$' ; }

####### Colored word-by-word diff of two files - ex.: showdiff oldversion.txt newversion.txt
function showdiff()
{
	wdiff -n -w $'\033[30;41m' -x $'\033[0m' -y $'\033[30;42m' -z $'\033[0m' $1 $2
}

####### Show the contents of a file, including additional useful info	
function showfile()
{
	width=72
	for input
	do
	  lines="$(wc -l < $input | sed 's/ //g')"
	  chars="$(wc -c < $input | sed 's/ //g')"
	  owner="$(ls -ld $input | awk '{print $3}')"
	  echo "-----------------------------------------------------------------"
	  echo "File $input ($lines lines, $chars characters, owned by $owner):"
	  echo "-----------------------------------------------------------------"
	  while read line
	    do
		 if [ ${#line} -gt $width ] ; then
		   echo "$line" | fmt | sed -e '1s/^/  /' -e '2,$s/^/+ /'
		 else
		   echo "  $line"
		 fi
	    done < $input
	  echo "-----------------------------------------------------------------"
	done | more
}

####### ShowTimes: show the modification, metadatachange, and access times of a file	
function showTimes() { stat -f "%N:   %m %c %a" "$@" ; }

# Used by file		
#------------------------------------------////

###### sh_coloroff
function sh_coloroff()
{
	echo -en "$reset_color"
}

###### sh_colormsg
function sh_colormsg()
{
	[ -n "$1" ] && echo -en "${fg_bold}${@}${reset_color}"
}

###### sh_error
function sh_error()
{
	echo -e "${fg_bold}[ e ]${reset_color} $@"
}

###### sh_info
function sh_info()
{
	echo -e "${fg_bold}[ i ]${reset_color} $@"
}

###### sh_success
function sh_success()
{
	echo -e "${fg_bold}[ k ]${reset_color} $@"
}

###### sh_mesg
function sh_mesg()
{
	echo -e "${fg_bold}[ m ]${reset_color} $@"
}

###### use with   svn diff -r `sh_svnprev`
function sh_svnprev(){ 
	echo $(( `svnversion . | sed 's/[^0-9].*//'` - 1))
}

###### sh_fcore - $1 - path
function sh_fcore()
{
  p="."
  [ -n "$1" ] && p="$1"
  find $p -name "core\.*[[:digit:]]*" -type f 2>& /dev/null
  return 0
}

####### Edit the Apache configuration
function apacheconfig ()
{
	if [ -f /etc/httpd/conf/httpd.conf ]; then
		sedit /etc/httpd/conf/httpd.conf
	elif [ -f /etc/apache2/apache2.conf ]; then
		sedit /etc/apache2/apache2.conf
	else
		echo "Error: Apache config file could not be found."
		echo "Searching for possible locations:"
		sudo updatedb && locate httpd.conf && locate apache2.conf
	fi
}

####### Edit the PHP configuration file
function phpconfig ()
{
	if [ -f /etc/php.ini ]; then
		sedit /etc/php.ini
	elif [ -f /etc/php/php.ini ]; then
		sedit /etc/php/php.ini
	elif [ -f /etc/php5/php.ini ]; then
		sedit /etc/php5/php.ini
	elif [ -f /usr/bin/php5/bin/php.ini ]; then
		sedit /usr/bin/php5/bin/php.ini
	elif [ -f /etc/php5/apache2/php.ini ]; then
		sedit /etc/php5/apache2/php.ini
	else
		echo "Error: php.ini file could not be found."
		echo "Searching for possible locations:"
		sudo updatedb && locate php.ini
	fi
}

####### Edit the MySQL configuration file
function mysqlconfig ()
{
	if [ -f /etc/my.cnf ]; then
		sedit /etc/my.cnf
	elif [ -f /etc/mysql/my.cnf ]; then
		sedit /etc/mysql/my.cnf
	elif [ -f /usr/local/etc/my.cnf ]; then
		sedit /usr/local/etc/my.cnf
	elif [ -f /usr/bin/mysql/my.cnf ]; then
		sedit /usr/bin/mysql/my.cnf
	elif [ -f ~/my.cnf ]; then
		sedit ~/my.cnf
	elif [ -f ~/.my.cnf ]; then
		sedit ~/.my.cnf
	else
		echo "Error: my.cnf file could not be found."
		echo "Searching for possible locations:"
		sudo updatedb && locate my.cnf
	fi
}

####### Ssh functions					 #
#------------------------------------------////

function slak()
{
    if [ $# -lt 2 ]; then
        echo "add public key to securelink server"
        echo "usage: skak [accountname] [sl port]"
    else
        cat /Volumes/Library/ssh/id_rsa-$1.pub | ssh -q lila@localhost -p $2 "if [ ! -d ~/.ssh/ ] ; then mkdir ~/.ssh ; fi ; chmod 700 ~/.ssh/ ; cat - >> ~/.ssh/authorized_keys ; chmod 600 ~/.ssh/authorized_keys"
    fi
}

###### slssh
function slssh()
{
    if [ $# -lt 1 ]; then
        echo "connect to securelink ssh session"
        echo "usage slssh [port#]"
        echo "ssh -p \$1 localhost"
    else
        ssh -p $1 localhost
    fi
}

###### slpg
function slpg()
{
    if [ $# -lt 1 ]; then
        echo "create securelink ssh tunnel for postgres"
        echo "usage: slpg [port#]"
        echo "ssh -N localhost -L 2345/localhost/5432 -p \$1"
    else
        ssh -N localhost -L 2345/localhost/5432 -p $1
    fi
}

###### sshmysql
function sshmysql()
{
# bind MySQL hostport to forward remote MySQL connection to localhost
ssh -L 13306:127.0.0.1:3306 -N $* &
}

###### sshpg
function sshpg()
{
    if [ $# -lt 1 ]; then
        echo "create ssh tunnel for postgres"
        echo "usage: sshpg username@server"
        echo "ssh -N \$1 -L 2345/localhost/5432"
    else
        ssh -N $1 -L 2345/localhost/5432
    fi
}

###### sshpg2
function sshpg2()
{
    if [ $# -lt 1 ]; then
        echo "create ssh tunnel for postgres"
        echo "usage: sshpg username@server"
        echo "ssh -N \$1 -L \$2/localhost/5432"
    else
        ssh -N $1 -L $2/localhost/5432
    fi
}

####### Function that outputs dots every second until command completes
function sleeper() { while `ps -p $1 &>/dev/null`; do echo -n "${2:-.}"; sleep ${3:-1}; done; }; export -f sleeper

####### Slow down CPU and IO for process and its offsprings
#------------------------------------------////

###### requires gawk: sudo apt-get install gawk
function slow2() { ionice -c3 renice -n 20 $(pstree `pidof $1` -p -a -u -A|gawk 'BEGIN{FS=","}{print $2}'|cut -f1 -d " ") ; }

####### Sort a list of comma-separated list of numbers 
function sort_csn() { echo "${1}" | sed -e "s/,/\n/g"| sort -nu | awk '{printf("%s,",$0)} END {printf("\n")}' | sed -e "s/,$//"; }

####### Get function's source
function source_print() { set | sed -n "/^$1/,/^}$/p"; }

# Spellchecking
#------------------------------------------////

###### I-Spell @ work: ENGLISH - requires ispell: sudo apt-get install ispell
function spell()
{
    local CHATTO
    if [ $# -ne 1 ]; then
        echo -e "\033[1;32mUSAGE: \033[33mis word_to_check\033[0m"
    else
        CHATTO=$( echo $* | awk '{print $1}' )
        shift
        echo -e "----------------------------------------------------->\n"
        echo $CHATTO | ispell -a -m -B |grep -v "@"
        echo -e "----------------------------------------------------->"
    fi
}

###### Google spell checker
function spellcheck() { typeset y=$@;curl -sd "<spellrequest><text>$y</text></spellrequest>" https://www.google.com/tbproxy/spell|sed -n '/s="[0-9]"/{s/<[^>]*>/ /g;s/\t/ /g;s/ *\(.*\)/Suggestions: \1\n/g;p}'|tee >(grep -Eq '.*'||echo -e "OK");}

###### spell checks either a Web page URL or a file - requires ispell: sudo apt-get install ispell
function webspell()
{
	okaywords="$HOME/.okaywords"
	tempout="/tmp/webspell.$$"
	trap "/bin/rm -f $tempout" 0
	if [ $# -eq 0 ] ; then
	  echo "Usage: webspell file|URL" >&2;
	fi
	for filename
	do
	  if [ ! -f "$filename" -a "$(echo $filename|cut -c1-7)" != "http://" ] ; then
		continue;      # picked up directory in '*' listing
	  fi
	  lynx -dump $filename | tr ' ' '\n' | sort -u | \
	    grep -vE "(^[^a-z]|')" | \
	    # adjust the following line to produce just a list of misspelled words
	    ispell -a | awk '/^\&/ { print $2 }' | \
	    sort -u > $tempout
	  if [ -r $okaywords ] ; then
	    # if you have an okaywords file, screen okay words out
	    grep -vif $okaywords < $tempout > ${tempout}.2
	    mv ${tempout}.2 $tempout
	  fi
	  if [ -s $tempout ] ; then
	    echo "Probable spelling errors: ${filename}"
	    echo '-------' ; cat $tempout ; echo '========='
	    cat $tempout | paste - - - -  | sed 's/^/  /'
	  fi
	done
}

####### Cut a part of a video # ("$1" for original file, "$2" for new file, "$3" is start time, & "$4" is length of video desired)
function splitvideo()
{
	ffmpeg -vcodec copy -acodec copy -i "$1" -ss "$3" -t "$4" "$2"
}

####### Posts a file to sprunge.us and copies the related  url to the clipboard (command line pastebin)	     #
function sprunge() { curl -s -F "sprunge=@$1" http://sprunge.us | xclip -selection clipboard && xclip -selection clipboard -o; }

####### Stock prices - can be called two ways: stock novl  (this shows stock pricing): stock "novell"  (this way shows stock symbol for novell)					 #
function stock()
{
	stockname=`lynx -dump http://finance.yahoo.com/q?s=${1} | grep -i ":${1})" | sed -e 's/Delayed.*$//'`
	stockadvise="${stockname} - delayed quote."
	declare -a STOCKINFO
	STOCKINFO=(` lynx -dump http://finance.yahoo.com/q?s=${1} | egrep -i "Last Trade:|Change:|52wk Range:"`)
	stockdata=`echo ${STOCKINFO[@]}`
	   if [[ ${#stockname} != 0 ]] ;then
		 echo "${stockadvise}"
		 echo "${stockdata}"
		    else
		    stockname2=${1}
		    lookupsymbol=`lynx -dump -nolist http://finance.yahoo.com/lookup?s="${1}" | grep -A 1 -m 1 "Portfolio" | grep -v "Portfolio" | sed 's/\(.*\)Add/\1 /'`
			  if [[ ${#lookupsymbol} != 0 ]] ;then
			  echo "${lookupsymbol}"
				else
				echo "Sorry $USER, I can not find ${1}."
			  fi
	   fi
}

###### command line way to get the stock quote via Yahoo
function stock_()
{
	curl -s 'http://download.finance.yahoo.com/d/quotes.csv?s=csco&f=l1'
}

####### Stopwatch and Countdown Timer			 #
function stopwatch() {
	BEGIN=$(date +%s)
	while true; do
	    NOW=$(date +%s)
	    DIFF=$(($NOW - $BEGIN))
	    MINS=$(($DIFF / 60))
	    SECS=$(($DIFF % 60))
	    echo -ne "Time elapsed: $MINS:`printf %02d $SECS`\r"
	    sleep .1
	done
}

###### stopwatch with log
function stop_watch()
{
	START=$( date +%s ); while true; do CURRENT=$( date +%s ) ; echo $(( CURRENT-START )) ; sleep 1 ; echo -n ^[[A ; done
}

###### countdown clock
function countdown() { case "$1" in -s) shift;; *) set $(($1 * 60));; esac; local S=" "; for i in $(seq "$1" -1 1); do echo -ne "$S\r $i\r"; sleep 1; done; echo -e "$S\rBOOM!"; }

###### countdown clock
alias countdown2='MIN=1 && for i in $(seq $(($MIN*60)) -1 1); do echo -n "$i, "; sleep 1; done; echo -e "\n\nBOOOM! Time to start."'

####### Transcodes and streams a video over http on port 6789 (vlc required)			 #
# function stream() { cvlc $1 --extraintf rc --sout
# 'transcode{vcodec=h264,vb=256,fps=12,scale=1,deinterlace,acodec=mp3,threads=3,ab=64,channels=2}:duplicate{dst=std{access=http,mux=ts,dst=0.0.0.0:6789}}';
# }

####### Print the corresponding error message
function strerror() { python -c "import os; print os.strerror($1)"; }

####### Function to split a string into an array
function string2array()
{
	read -a ARR <<<'world domination now!'; echo ${ARR[2]};
}

####### Count total number of subdirectories in current directory starting with specific name.
function subdir_find()
{
	find . -type d -name "*TestDir*" | wc -l
}

####### Check tcp-wrapping support	-  returns TRUE if the application supports tcp-wrapping or FALSE if not by reading the shared libraries used by this application.
function supportsWrap() { ldd `which ${1}` | grep "libwrap" &>/dev/null && return 0 || return 1; }

####### Swap 2 filenames around			 #
#------------------------------------------////

###### from Uzi's bashrc
function swap()
{
    local TMPFILE=tmp.$$
    [ $# -ne 2 ] && echo "swap: 2 arguments needed" && return 1
    [ ! -e $1 ] && echo "swap: $1 does not exist" && return 1
    [ ! -e $2 ] && echo "swap: $2 does not exist" && return 1
    mv "$1" $TMPFILE
    mv "$2" "$1"
    mv $TMPFILE "$2"
}

####### swap2
function swap2() { if [ -f "$1" -a -f "$2" ]; then mv "$1" "$1.$$" && mv "$2" "$1" && mv "$1.$$" "$2" && echo "Success"; else echo "Fail"; fi; }

####### Switch two files (comes in handy)
function switchfile() {
	mv $1 ${1}.tmp && $2 $1 && mv ${1}.tmp $2
}

####### Creates a dated tarball
function tarball()
{
    name=$1
    shift
    tar zcvf $name-`date +%Y%m%d`.tar.gz "$@"
}

####### Monitor progress of data through a pipeline
function tarcp() {
    if (( $# >= 2 )); then
        echo "copy ${@[1, -2]} => ${@[-1]}"
        # http://www.ivarch.com/programs/pv.shtml
        if which pv ; then
            tar -c -f - ${@[1, -2]} | pv -t -b -r | tar -x -f - -C ${@[-1]}
        else
            tar -c -v -f - ${@[1, -2]} | tar -x -f - -C ${@[-1]}
        fi
    else
        "error, not enough parameters."
        return 1
    fi
}

####### TODO: fix so -s can be sent to cp
function tcp() {
        if [ "$1" = "-s" -o "$1" = "--set-target" ]; then
                COPY_TARGET="$(realpath $2)";
        elif [ "$1" = "-h" -o "$1" = "--help" ]; then
                echo "usage: tcp [-s|--set-target <dir>] | <mv args> <files>";
        else
                cp --target-directory "$COPY_TARGET" "$@";
        fi
}

####### Keeping your $HOME directory organized - having one temp dir for dls etc can quickly become mess, so try this tip to organise by date
# export TD="$HOME/temp/`date +'%Y-%m-%d'`"
# function td() {
#    td=$TD
#    if [ ! -z "$1" ]; then
#        td="$HOME/temp/`date -d "$1 days" +'%Y-%m-%d'`";
#    fi
#    mkdir -p $td; cd $td
#    unset td
# }

###### Make the following commands run in background automatically - wrapper around xemacs/gnuserv ...
function te()
{
    if [ "$(gnuclient -batch -eval t 2>&-)" == "t" ]; then
        gnuclient -q "$@";
    else
        ( xemacs "$@" &);
    fi
}

####### Set terminal title				 #
#------------------------------------------////

function terminal_title {
    echo -en "\033]2;$@\007"
}

# Set/Unset a proxy for the terminal using tor
#------------------------------------------////

###### For a HTTP proxy in a single terminal window, simply run the following command in a terminal:
# export http_proxy='http://YOUR_USERNAME:YOUR_PASSWORD@PROXY_IP:PROXY_PORT/'
# For a secure connection (HTTPS), use:
# export https_proxy='http://YOUR_USERNAME:YOUR_PASSWORD@PROXY_IP:PROXY_PORT/'
# Obviously, replace everything with your username, password, proxy ip and port. If the proxy does not require an username and password, skip that part
function termproxy()
{
	export http_proxy='http://localhost:8118'
	export https_proxy='http://localhost:8118'
}

###### To close the HTTP proxy in the terminal, either close the terminal, or enter this:
function termproxyX()
{
	unset http_proxy
	unset https_proxy
}

####### Terrorist threat level text

function terrorist-level()
{
	echo "Terrorist threat level: $(curl -s 'http://www.dhs.gov/dhspublic/getAdvisoryCondition' | awk -F\" 'NR==2{ print $2 }')"
}

####### Display theme info
function themeinfo() {
	  if [ `pgrep emerald` ]; then
	    echo "  Emerald:    `cat $HOME/.emerald/theme/theme.ini | grep description | awk -F= '{print $2}'`"
	  else
	    echo "  Metacity:   `gconftool-2 -g /apps/metacity/general/theme`"
	  fi
	  echo "  GTK:        `gconftool-2 -g /desktop/gnome/interface/gtk_theme`"
	  echo "  Icons:      `gconftool-2 -g /desktop/gnome/interface/icon_theme`"
	  echo "  Cursor:     `gconftool-2 -g /desktop/gnome/peripherals/mouse/cursor_theme`"
	  echo "  Font:       `gconftool-2 -g /desktop/gnome/interface/font_name`"
	  echo "  Wallpaper:  `gconftool-2 -g /desktop/gnome/background/picture_filename | xargs basename | cut -d. -f 1`"
	  echo
}

####### Thesaurus requires dict: sudo apt-get install dict
function ths() {
    dict -d moby-thes $@
}

####### A function to find the fastest free DNS server - requires: sudo apt-get install moreutils
function timeDNS() { { for x in "${local_DNS}" "208.67.222.222" "208.67.220.220" "198.153.192.1" "198.153.194.1" "156.154.70.1" "156.154.71.1" "8.8.8.8" "8.8.4.4"; do ({ echo -n "$x "; dig @"$x" "$*"|grep Query ; }|sponge &) done ; } | sort -n -k5 ; }

####### Timer function - Elapsed time.  Usage:
#   t=$(timer)
#   ... # do something
#   printf 'Elapsed time: %s\n' $(timer $t)
#      ===> Elapsed time: 0:01:12
# If called with no arguments a new timer is returned.
# If called with arguments the first is used as a timer
# value and the elapsed time is returned in the form HH:MM:SS.
function timer()
{
    if [[ $# -eq 0 ]]; then
        echo $(date '+%s')
    else
        local  stime=$1
        etime=$(date '+%s')
        if [[ -z "$stime" ]]; then stime=$etime; fi
        dt=$((etime - stime))
        ds=$((dt % 60))
        dm=$(((dt / 60) % 60))
        dh=$((dt / 3600))
        printf '%d:%02d:%02d' $dh $dm $ds
    fi
}

####### Return a title-cased version of the string[str.title() in python]

function title() { sed 's/\<\w*/\u&/g' <<<$@; }
# function title() { string=( $@ ); echo ${string[@]^} ; }

####### To examine lots of files and potentially move them to a common directory
# ex:	tmv -s /mnt/disk/5k
# ex:	make a playlist
# ex:	tmv eye-of-the-tiger.mp3 #  <-> mv eye-of-the-tiger.mp3 /mnt/disk/5k
function tmv() {
        if [ "$1" = "-s" -o "$1" = "--set-target" ]; then
                MOVE_TARGET="$(realpath $2)";
        elif [ "$1" = "-h" -o "$1" = "--help" ]; then
                echo "usage: tmv [-s|--set-target <dir>] | <mv args> <files>";
        else
                mv --target-directory "$MOVE_TARGET" "$@";
        fi
}

####### Top-ten commands
function top10() {
    
    history | awk '{a[$2]++ } END{for(i in a){print a[i] " " i}}' | sort -rn | head
}

####### Switch tor on and off (requires privoxy)
function torswitch() {
    
    if [[ $EUID == 0 ]]; then
	case $1 in
	    *on )
		if [[ $(grep forward-socks4a /etc/privoxy/config) == "" ]]; then
		    echo "forward-socks4a / 127.0.0.1:9050 ." >> /etc/privoxy/config
		else
		    sed -e 's/\# forward-socks4a/forward-socks4a/g' -i /etc/privoxy/config
		    /etc/init.d/tor restart
		    /etc/init.d/privoxy restart
		fi
	    ;;
	    *off )
		sed -e 's/forward-socks4a/\# forward-socks4a/g' -i /etc/privoxy/config
		/etc/init.d/tor restart
		/etc/init.d/privoxy restart
	    ;;
	esac
    fi
}

####### Get the total length of all video / audio in the current dir in H:m:s
alias total_audio_length="mplayer -endpos 0.1 -vo null -ao null -identify *.avi 2>&1 |grep ID_LENGTH |cut -d = -f 2|awk '{SUM += $1} END { printf "%d:%d:%d\n",SUM/3600,SUM%3600/60,SUM%60}'"

alias total_video_length='total_audio_length'

###### ####### Touchpad stuff	- to get information on touchpad
alias touchpad_id='xinput list | grep -i touchpad'

###### ####### Touchpad stuff	 - to disable touchpad- using 'touchpad_id', set the number for your touchpad (default is 12)
function touchpad_off()
{
	touchpad=12
	xinput set-prop $touchpad "Device Enabled" 0
}

###### ####### Touchpad stuff	- to enable touchpad- using 'touchpad_id', set the number for your touchpad (default is 12)
function touchpad_on()
{
	touchpad=12
	xinput set-prop $touchpad "Device Enabled" 1
}

####### Transmission with blocklists
function transmissionbl()
{
	# Automatically downloads and 'installs' my choice of I-Blocklist lists prior to running Transmission (currently, there are 82 separate lists to choose from)
	# Homepage:	http://www.iblocklist.com/lists.php
	notify-send -t 20000 -i /usr/share/icons/gnome/32x32/status/info.png "Please wait while blocklists for Transmission BitTorrent Client are downloading..."
	BLOCKLISTDIR="$HOME/.config/transmission/blocklists"
	BASEURL="http://list.iblocklist.com/?list="
	ENDURL="&fileformat=p2p&archiveformat=gz"
	FILES=( bt_level1 bt_level2 bt_level3 us bt_dshield jcjfaxgyyshvdbceroxf ijfqtofzixtwayqovmxn bt_templist dufcxgnbjsdwmwctgfuj )
	if [ ! -d $BLOCKLISTDIR ];then
	    mkdir -p $BLOCKLISTDIR
	else
	    /bin/rm -fv -R $BLOCKLISTDIR
	    mkdir -p $BLOCKLISTDIR
	fi
	for i in "${FILES[@]}"
	  do
	    # wget -c $BASEURL"$i"$ENDURL -O $BLOCKLISTDIR/$i.gz
	    curl -L --retry 10 $BASEURL"$i"$ENDURL -o $BLOCKLISTDIR/$i.gz 	# seems to generate less download failures than wget
	    gunzip -f $BLOCKLISTDIR/$i.gz
	    mv $BLOCKLISTDIR/$i $BLOCKLISTDIR/$i.txt
	done
	if [ ! $(find "$BLOCKLISTDIR" -type f -name "*.gz") ];then
	    notify-send -t 10000 -i /usr/share/icons/gnome/32x32/status/info.png "The blocklists have finished downloading. Transmission will open momentarily..."
	    transmission-gtk
	    /bin/rm -fv -R $BLOCKLISTDIR/*.txt
	    exit
	else
	    notify-send -t 10000 -i /usr/share/icons/gnome/32x32/status/info.png "The blocklists have failed to completely download. Please try again." & /bin/rm -fv -R $BLOCKLISTDIR
	    exit
	fi
}

####### Moves specified files to ~/.Trash -  will not overwrite files that have the same name
function trashit()
{   local trash_dir=$HOME/.Trash
    for file in "$@" ; do
        if [[ -d $file ]] ; then
            local already_trashed=$trash_dir/`basename $file`
            if [[ -n `/bin/ls -d $already_trashed*` ]] ; then
                local count=`/bin/ls -d $already_trashed* | /usr/bin/wc -l`
                count=$((++count))
                /bin/mv --verbose "$file" "$trash_dir/$file$count"
                continue
            fi
        fi
        /bin/mv --verbose --backup=numbered "$file" $HOME/.Trash
    done
}

####### Tree stuff	-  shows directory tree (requires 'tree': sudo apt-get install tree)
function treecd() {
    builtin cd "${@}" &>/dev/null
    . $BSNG_RC_DIR/dirinfo/display
    dirinfo_display
    echo -e "${epink}content:"
    tree -L 1 $TREE_OPTS
    echo "$PWD" > $HOME/.lastpwd
}

####### Tree stuff	-  displays a tree of the arborescence
function treefind() {
    find "$@" | sed 's/[^/]*\//|   /g;s/| *\([^| ]\)/+--- \1/'
}

####### Search for a show at TV.COM			 #
#------------------------------------------////
function tvcom() {
	firefox "http://www.tv.com/search.php?type=11&stype=all&tag=search%3Bfrontdoor&qs="${@}"&stype=program" &
}

####### TV/Monitor switch on/off (good for wanting to watch video from computer through S-Video out) - use the command: "xrandr" to discover what the proper connected video outputs there are attached such as VGA-0 (monitor), LVDS1 (Laptop screen), S-video, VGA1 (VGA-to-TV Converter Box), etc.
function tv-monitor-switch-end() {
	mode="$(xrandr -q|grep -A1 "LVDS1 connected"| tail -1 |awk '{ print $1 }')"
	if [ -n "$mode" ]; then
	  mode1="$(xrandr -q|grep -A1 "VGA1 connected"| tail -1 |awk '{ print $1 }')"
	  if [ -n "$mode1" ]; then
	    xrandr --output LVDS1 --mode 1280x800 --output VGA1 --off
	  else
	    echo "No VGA1 monitor is connected so nothing to do."
	  fi
	else
	  mode2="$(xrandr -q|grep -A1 "VGA-0 connected"| tail -1 |awk '{ print $1 }')"
	  if [ -n "$mode2" ]; then
	    mode3="$(xrandr -q|grep -A1 "S-video connected"| tail -1 |awk '{ print $1 }')"
	    if [ -n "$mode3" ]; then
		 xrandr --output VGA-0 --mode 1024x768 --output S-video --off
	    else
		 echo "No S-video monitor is connected so nothing to do."
	    fi
	  else
	    echo "No other monitor is connected so nothing to do."
	  fi
	fi
}

###### tv-monitor-switch-start
function tv-monitor-switch-start() {
	mode="$(xrandr -q|grep -A1 "LVDS1 connected"| tail -1 |awk '{ print $1 }')"
	if [ -n "$mode" ]; then
	  mode1="$(xrandr -q|grep -A1 "VGA1 connected"| tail -1 |awk '{ print $1 }')"
	  if [ -n "$mode1" ]; then
	    xrandr --addmode VGA1 1024x768
	    xrandr --output LVDS1 --mode 1024x768 --output VGA1 --mode 1024x768 --same-as LVDS1
	  else
	    echo "No VGA1 monitor is connected so nothing to do."
	  fi
	else
	  mode2="$(xrandr -q|grep -A1 "VGA-0 connected"| tail -1 |awk '{ print $1 }')"
	  if [ -n "$mode2" ]; then
	    mode3="$(xrandr -q|grep -A1 "S-video connected"| tail -1 |awk '{ print $1 }')"
	    if [ -n "$mode3" ]; then
		 xrandr --addmode S-video 800x600
		 xrandr --output VGA-0 --mode 800x600 --output S-video --mode 800x600 --same-as VGA-0
	    else
		 echo "No S-video monitor is connected so nothing to do."
	    fi
	  else
	    echo "No other monitor is connected so nothing to do."
	  fi
	fi
}

####### Convert text file to pdf - Requires:	sudo apt-get install txt2html python-pisa (Packet Veraltet)
# function txt2pdf() { xhtml2pdf -b "${1%.*}" < <(txt2html "$1"); }

####### Adds "-c" canonical option to bash "type" - builtin command to follow symbolic links	 #
function type() { if [ "$1" = "-c" ]; then shift; for f in "$@"; do ff=$(builtin type -p "$f"); readlink -f "$ff"; done; else builtin type $typeopts "$@"; fi; }

####### Changes spaces to underscores in names
function underscore()
{
    for f in * ; do
	[ "${f}" != "${f// /_}" ]
	mv -- "${f}" "${f// /_}"
    done
}

####### Decompiler for jar files using jad
function unjar() { mkdir -p /tmp/unjar/$1 ; unzip -d /tmp/unjar/$1 $1 *class 1>/dev/null && find /tmp/unjar/$1 -name *class -type f | xargs jad -ff -nl -nonlb -o -p -pi99 -space -stat ; rm -r /tmp/unjar/$1 ; }

####### Remove all files created by latex
function unlatex() {
	if [ "$1" == "" ]; then
	return
	fi
	i=${1%%.*}
	rm -f $i.aux $i.toc $i.lof $i.lot $i.los $i.?*~ $i.loa $i.log $i.bbl $i.blg $i.glo
	rm -f $i.odt $i.tns $i.fax $i.bm $i.out $i.nav $i.snm
	rm -f $i.mtc* $i.bmt
	mv -f $i.dvi .$i.dvi
	mv -f $i.ps .$i.ps
	mv -f $i.pdf .$i.pdf
	rm -f $i.dvi $i.ps $i.pdf
	unset i
}

####### Up to top directory
function up() {
[ "${1/[^0-9]/}" == "$1" ] && {
        local ups=""
        for ((i=1; i<=$1; i++))
        do
                ups=$ups"../"
        done
        cd $ups
        }
}

####### Move all files in current directory (recursively) up a level
function upalevel()
{
	find . -type f | perl -pe '(s!(\./.*/)(.*)!mv "\1\2" "\1../\2"!);' | sh
}

####### Short URLs with ur1.ca
function ur1() { curl -s --url http://ur1.ca/ -d longurl="$1" | sed -n -e '/Your ur1/!d;s/.*<a href="\(.*\)">.*$/\1/;p' ; }

####### Easily decode unix-time (function)

function utime() { perl -e "print localtime($1).\"\n\"";}

####### Echo a command, then execute it
function v_() { echo "$@"; "$@"; }

###### Checks to ensure that all environment variables are valid	- looks at SHELL, HOME, PATH, EDITOR, MAIL, and PAGER
function validator()
{
	errors=0
	function in_path()
	{
		  # given a command and the PATH, try to find the command. Returns
		  # 1 if found, 0 if not.  Note that this temporarily modifies the
		  # the IFS input field seperator, but restores it upon completion.
		  cmd=$1    path=$2    retval=0
		  oldIFS=$IFS; IFS=":"
		  for directory in $path
		  do
		    if [ -x $directory/$cmd ] ; then
			 retval=1      # if we're here, we found $cmd in $directory
		    fi
		  done
		  IFS=$oldIFS
		  return $retval
	}
	function validate()
	{
		  varname=$1    varvalue=$2
		  if [ ! -z $varvalue ] ; then
		    if [ "${varvalue%${varvalue#?}}" = "/" ] ; then
			 if [ ! -x $varvalue ] ; then
			   echo "** $varname set to $varvalue, but I cannot find executable."
			   errors=$(( $errors + 1 ))
			 fi
		    else
			 if in_path $varvalue $PATH ; then
			   echo "** $varname set to $varvalue, but I cannot find it in PATH."
			   errors=$(( $errors + 1 ))
			 fi
		    fi
		  fi
	}
	####### Beginning of actual shell script #######
	if [ ! -x ${SHELL:?"Cannot proceed without SHELL being defined."} ] ; then
	  echo "** SHELL set to $SHELL, but I cannot find that executable."
	  errors=$(( $errors + 1 ))
	fi
	if [ ! -d ${HOME:?"You need to have your HOME set to your home directory"} ]
	then
	  echo "** HOME set to $HOME, but it's not a directory."
	  errors=$(( $errors + 1 ))
	fi
	# Our first interesting test: are all the paths in PATH valid?
	oldIFS=$IFS; IFS=":"     # IFS is the field separator. We'll change to ':'
	for directory in $PATH
	do
	  if [ ! -d $directory ] ; then
		 echo "** PATH contains invalid directory $directory"
		 errors=$(( $errors + 1 ))
	  fi
	done
	IFS=$oldIFS             # restore value for rest of script
	# Following can be undefined, & also be a progname, rather than fully qualified path.
	# Add additional variables as necessary for your site and user community.
	validate "EDITOR" $EDITOR
	validate "MAILER" $MAILER
	validate "PAGER"  $PAGER
	# and, finally, a different ending depending on whether errors > 0
	if [ $errors -gt 0 ] ; then
	  echo "Errors encountered. Please notify sysadmin for help."
	else
	  echo "Your environment checks out fine."
	fi
}

######## Converts VCD/SVCD to MPEG files
function vcd2mpeg()
{
	# Made by ioccatflashdancedotcx
	# Version 1.6, Thu Aug  4 00:43:44 CEST 2005
	if [ -n "$(ls 2>/dev/null *001|grep *001)" ]; then
				 rar x *01.rar
		if [ -n "$(ls 2>/dev/null *bin)" ]; then
				for i in *bin ; do vcdxrip -p --bin-file="$i" ; done
				mv *mpg cd.mpg
				rm *cue *bin *.xml _cdi_cdi_* _extra_svcdinfo.txt &>/dev/null
		fi
	fi
	if [ -n "$(ls 2>/dev/null *01.rar|grep *01.rar)" ]; then
				 rar x *01.rar
		if [ -n "$(ls 2>/dev/null *bin)" ]; then
				for i in *bin ; do vcdxrip -p --bin-file="$i" ; done
				mv *mpg cd.mpg
				rm *cue *bin *.xml _cdi_cdi_* _extra_svcdinfo.txt &>/dev/null
		fi
	fi
	if [ -n "$(ls 2>/dev/null *.rar|grep *.rar)" ]; then
				 rar x *rar
		if [ -n "$(ls 2>/dev/null *bin)" ]; then
					for i in *bin ; do vcdxrip -p --bin-file="$i" ; done
					mv *mpg cd.mpg
				rm *cue *bin *.xml _cdi_cdi_* _extra_svcdinfo.txt &>/dev/null
		fi
	fi
	for cddir in CD1 CD2 CD3 CD4 CD5 CD6 Cd1 Cd2 Cd3 Cd4 Cd5 Cd6 cd1 cd2 cd3 cd4 cd5 cd6; do
	if cd ${cddir} &>/dev/null; then
	    if [ -n "$(ls 2>/dev/null *001|grep *001)" ]; then
		rar x *001
		if [ -n "$(ls 2>/dev/null *bin)" ]; then
		    for i in *bin ; do vcdxrip -p --bin-file="$i" ; done
			if [ -n "$(ls 2>/dev/null avseq02.mpg)" ]; then
			    rm avseq01.mpg
			fi
		    mv *mpg ../${cddir}.mpg
				rm *cue *bin *.xml _cdi_cdi_* _extra_svcdinfo.txt &>/dev/null
		    cd ..
		    for i in ${cddir}.mpg ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		elif [ -n "$(ls 2>/dev/null *mpg)" ]; then
		    mv *mpg ../${cddir}.mpg
		    cd ..
		    for i in ${cddir}.mpg ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		elif [ -n "$(ls 2>/dev/null *avi)" ]; then
			mv *avi ../${cddir}.avi
			cd ..
			for i in ${cddir}.avi ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		fi
	    else
	    if [ -n "$(ls 2>/dev/null *01.rar|grep *01.rar)" ]; then
		rar x *01.rar
		if [ -n "$(ls 2>/dev/null *bin)" ]; then
		    for i in *bin ; do vcdxrip -p --bin-file="$i" ; done
			if [ -n "$(ls 2>/dev/null avseq02.mpg)" ]; then
			    rm avseq01.mpg
			fi
		    mv *mpg ../${cddir}.mpg
				rm *cue *bin *.xml _cdi_cdi_* _extra_svcdinfo.txt &>/dev/null
		    cd ..
		    for i in ${cddir}.mpg ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		elif [ -n "$(ls 2>/dev/null *mpg)" ]; then
		    mv *mpg ../${cddir}.mpg
		    cd ..
		    for i in ${cddir}.mpg ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		elif [ -n "$(ls 2>/dev/null *avi)" ]; then
			mv *avi ../${cddir}.avi
			cd ..
			for i in ${cddir}.avi ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		fi
	    else
	    if [ -n "$(ls 2>/dev/null *.rar|grep *.rar)" ]; then
		rar x *rar
		if [ -n "$(ls 2>/dev/null *bin)" ]; then
		    for i in *bin ; do vcdxrip -p --bin-file="$i" ; done
			if [ -n "$(ls 2>/dev/null avseq02.mpg)" ]; then
			    rm avseq01.mpg
			fi
		    mv *mpg ../${cddir}.mpg
				rm *cue *bin *.xml _cdi_cdi_* _extra_svcdinfo.txt &>/dev/null
		    cd ..
		    for i in ${cddir}.mpg ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		elif [ -n "$(ls 2>/dev/null *mpg)" ]; then
			mv *mpg ../${cddir}.mpg
			cd ..
			for i in ${cddir}.mpg ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		elif [ -n "$(ls 2>/dev/null *avi)" ]; then
			mv *avi ../${cddir}.avi
			cd ..
			for i in ${cddir}.avi ; do mv -- $i `echo $i|tr A-Z a-z` ; done
		fi
	    fi
	    fi
	    fi
	fi
	done
}

####### Copy a file prefixed with a version number to a subdirectory
function vers() { ( IFS=$'\n'; suf="_versions"; mkdir -p "$1$suf"; nr=`ls "$1$suf" | wc -l`; nr=`printf "%02d" $(($nr + 1))`; cp "$1" "$1$suf/v${nr}_$1" ) ; }

####### Edit a executable script
function vie() { vi $(which $1); }

####### Run a command, redirecting output to a file, then edit the file with vim
function vimcmd() { $1 > $2 && vim $2; }

####### Text message on wallpaper			 #
function wallpaperWarn() { BG="/desktop/gnome/background/picture_filename"; convert "`gconftool-2 -g $BG`" -pointsize 70 -draw "gravity center fill red  text 0,-360 'Warn' fill white  text 0,360 'Warn'" /tmp/w.jpg; gconftool-2 --set $BG -t string "/tmp/w.jpg" ; }

####### Crawl a webpage for links			 #
function webcrawl()
{
	lynx -dump $1 | grep -A999 "^References$" | tail -n +3 | awk '{print $2 }'
}

####### Download all files of a certain type with wget - usage: wgetall mp3 http://example.com/download/
function wgetall() { wget -r -l2 -nd -Nc -A.$@ $@ ; }

####### Telling you from where your commit come from
function where()
{
	COUNT=0; while [ `where_arg $1~$COUNT | wc -w` == 0 ]; do let COUNT=COUNT+1; done; echo "$1 is ahead of "; where_arg $1~$COUNT; echo "by $COUNT commits";};function where_arg() { git log $@ --decorate -1 | head -n1 | cut -d ' ' -f3- ;
}

####### Which PATH variable should use for this script?#
function whichpath() { local -A path; local c p; for c; do p=$(type -P "$c"); p=${p%/*}; path[${p:-/}]=1; done; local IFS=:; printf '%s\n' "${!path[*]}"; }

###### Check hosts that are online - for those who DO NOT USE their /etc/hosts file for name resolution
# This can look through resolv.conf file for address of nameservers (note: THIS WILL ONLY WORK IF YOU USE LOCAL NAMESERVERS! Nameservers
# from your ISP will render this function useless). It then cuts result to show just first 3 octets of IP address and runs nmap just as original function.
if which nmap 2>&1 > /dev/null; then
  function whodat()
  {
    if [ -n "$1" ]; then
      net="$1"
    else
      net=$(cat /etc/resolv.conf | grep 'nameserver' | cut -c12-26 | awk -F '.' '{print $1"."$2"."$3".0/24"}')
    fi
    echo "testing $net for online hosts"
    nmap -sP $net | awk '/Host/ && /up/ { print $0; }'
    echo "done"
}
fi

###### Check hosts that are online - for those who USE their /etc/hosts file for name resolution
#if which nmap 2>&1 > /dev/null; then
#  function whoisonline()
#  {
#    if [ -n "$1" ]; then
#      net="$1"
#    else
#      net=$(grep `hostname` /etc/hosts | awk -F '.' '{ print $1"."$2"."$3".0/24"}')
#    fi
#    sh_info "testing $net for online boxes"
#    sudo nmap -sP $net | awk '/Host/ && /up/ { print $0; }'
#    sh_success "done"
#  }
#fi

####### Wipe command (uses 'shred', not 'wipe', which I think is better (sudo apt-get	install wipe))
function wipe_() {
    
    cryptsetup -d /dev/urandom -c aes-xts-plain create delete $1
    shred -vzn 0 /dev/mapper/delete
    sync && sleep 4
    cryptsetup remove delete
}

####### Wordcount - counts frequency of words in a file
function wordfreq()
{
	cat "$1"|tr -d '[:punct:]'|tr '[:upper:]' '[:lower:]'|tr -s ' ' '\n'|sort|uniq -c|sort -rn
}

###### word counter
function words()
{
	# words.sh
	# counts words in selection and displays result in zenity window
	# dependencies xsel, wc, zenity
	text=$(xsel)
	words=$(wc -w <<<$text)
	zenity --info --title "Word Count" --text "Words in selection:\n${words}\n\n\"${text}\""
}

####### ISO-writer
function writeiso() {
    if [[ $CD_WRITER ]]; then
	cdrecord dev=$CD_WRITER "$1"
    else	cdrecord deV=/dev/dvdrw "$1"
    fi
}

####### Xchown something
function xchown() {
    user="$1"
    shift
    for df in "$@";
	do su -c "chown -R $user:$user \"$df\"";
    done
}

####### X delete - removes files with desired name in current directory
if [[ ${BASH_VERSINFO[0]} -ge "4" ]]; then
	function xdel() {
		
		shopt -s globstar
		[[ "$@" != "" ]] &&
		    { for argv in "$@"; do
			rm -fv ./**/*"$argv"
		    done }
	    }
fi

####### This function uses xmllint to evaluate xpaths - usage: xpath /some/xpath XMLfile
function xpath() { xmllint --format --shell "$2" <<< "cat $1" | sed '/^\/ >/d' ; }

####### Adds some text in the terminal frame
function xtitle()
{
    case "$TERM" in
        *term | rxvt)
            echo -n -e "\033]0;$*\007" ;;
        *)
            ;;
    esac
}

####### copy and go to dir
function cpg (){
  if [ -d "$2" ];then
    cp $1 $2 && cd $2
  else
    cp $1 $2
  fi
}

####### move and go to dir
function mvg (){
  if [ -d "$2" ];then
    mv $1 $2 && cd $2
  else
    mv $1 $2
  fi
}

####### Meine LAN IP + LAN Bcast Adresse
function localnet ()
{
	/sbin/ifconfig | awk /'net Adresse/ {print $2}'
	echo ""
	/sbin/ifconfig | awk /'Bcast/ {print $3}'
	echo ""
}

####### Parallel XZ with progress bar
function xzv() { THREADS=`grep processor /proc/cpuinfo | wc -l`; for file in $*; do pv -s `stat -c%s $file` < $file | pxz -q -T $THREADS > $file.xz ; done; }

####### Busted... (Yaourt)
function yaourt() {
	EDITORBACKUP="$EDITOR";
	export EDITOR=cat;
	sudo yaourt "$@";
	export EDITOR="$EDITORBACKUP";
	export EDITORBACKUP=
}

####### Overwrite a file with zeros
function zero() {
        case "$1" in
                "")     echo "Usage: zero <file>"

                        return -1;
        esac
        filesize=`wc -c  "$1" | awk '{print $1}'`
        `dd if=/dev/zero of=$1 count=$filesize bs=1`
}

####### To create a ZIP archive of a file or folder
function zipf() { zip -r "$1".zip "$1" ; }

####### extract - Enpacken
function extract () {
     if [ -f $1 ] ; then
         case $1 in
             *.tar.bz2)   tar xjf $1        ;;
             *.tar.gz)    tar xzf $1     ;;
             *.bz2)       bunzip2 $1       ;;
             *.rar)       rar x $1     ;;
             *.gz)        gunzip $1     ;;
             *.tar)       tar xf $1        ;;
             *.tbz2)      tar xjf $1      ;;
             *.tgz)       tar xzf $1       ;;
             *.zip)       unzip $1     ;;
             *.Z)         uncompress $1  ;;
             *.7z)        7z x $1    ;;
             *)           echo "'$1' cannot be extracted via extract()" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}

####### Extract - extract most common compression types
#function extract() {
#  local e=0 i c
#  for i; do
#    if [[ -f $i && -r $i ]]; then
#        c=''
#        case $i in
#          *.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))               #Fehler
#                 c='bsdtar xvf' ;;
#          *.7z)  c='7z x'       ;;
#          *.Z)   c='uncompress' ;;
#          *.bz2) c='bunzip2'    ;;
#          *.exe) c='cabextract' ;;
#          *.gz)  c='gunzip'     ;;
#          *.rar) c='unrar x'    ;;
#          *.xz)  c='unxz'       ;;
#          *.zip) c='unzip'      ;;
#          *)     echo "$0: cannot extract \`$i': Unrecognized file extension" >&2; e=1 ;;
#        esac
#        [[ $c ]] && command $c "$i"
#    else
#        echo "$0: cannot extract \`$i': File is unreadable" >&2; e=2
#    fi
#  done
#  return $e
#}

# TV/DVD/Video/Audio Copying/ripping/extracting
#------------------------------------------////

############ TV ############

###### ANALOG TV to AVI
function atv2avi()
{
	# great xvid quality is "2000" (11mb/min)
	echo -n "What analog/cable tv channel would you like to convert? (1-99)?:
	"
	read achan_type
	echo -n "Please enter how long you want to record (in this format: 02:08:17):
	"
	read time_type
	echo -n "Please enter a name for the AVI file you will convert:
	"
	read file_name
	echo -n "Please enter the quality you want your recording to be (in this format: 2000):
	"
	read qual_type
	mencoder -tv driver=v4l2:device=/dev/video1:input=0:norm=ntsc:chanlist=us-cable:channel=$achan_type:alsa=1:adevice=hw.1:audiorate=48000:immediatemode=0:amode=1 tv:// -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type
}
alias atvrip='atv2avi'

function atv2avi_w()
{
	# great xvid quality is "2000" (11mb/min) (watch the recording at the same time)
	echo -n "What analog/cable tv channel would you like to convert? (1-99)?:
	"
	read achan_type
	echo -n "Please enter how long you want to record (in this format: 02:08:17):
	"
	read time_type
	echo -n "Please enter a name for the AVI file you will convert:
	"
	read file_name
	echo -n "Please enter the quality you want your recording to be (in this format: 2000):
	"
	read qual_type
	mencoder -tv driver=v4l2:device=/dev/video1:input=0:norm=ntsc:chanlist=us-cable:channel=$achan_type:alsa=1:adevice=hw.1:audiorate=48000:immediatemode=0:amode=1 tv:// -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type & (sleep 5 && mplayer $HOME/Temp/$file_name.avi)
}
alias atvrip_w='atv2avi_w'

###### WATCH ANALOG TV
function atv()
{
	echo -n "What analog/cable tv channel would you like to watch? (1-99)?:
	"
	read ANALOGSTATION
	sh -c "mplayer -tv driver=v4l2:device=/dev/video1:input=0:norm=ntsc:chanlist=us-cable:channel="$ANALOGSTATION" tv:// & sox -r 48000 -t alsa hw:1,0 -t alsa hw:0,0"
}

###### atv_
function atv_()
{
	sh -c "tvtime & sox -r 48000 -t alsa hw:1,0 -t alsa hw:0,0"
}

###### ATV
function ATV()
{
	sox -s -r 32000 -c 2 -t alsa hw:1,0 -s -r 32000 -c 2 -t alsa hw:0,0 &
	tvtime
	t=`pidof sox`;
	kill $t;
}

###### WATCH DIGITAL TV
function dtv()
{
	dtvchannels
	echo -n "What digital tv channel would you like to watch?:
	"
	read DIGITALSTATION
	mplayer dvb://"$DIGITALSTATION"
}

###### DIGITAL TV to AVI
function dtv2avi()
{
	# great xvid quality is "1600" (13mb/min)
	dtvchannels
	echo -n "What digital tv channel would you like to convert?:
	"
	read dchan_type
	echo -n "Please enter how long you want to record (in this format: 02:08:17):
	"
	read time_type
	echo -n "Please enter a name for the AVI file you will convert:
	"
	read file_name
	echo -n "Please enter the quality you want your recording to be (in this format: 1600):
	"
	read qual_type
	mencoder dvb://$dchan_type -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip,scale -zoom -xy 624 -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type
}
alias dtvrip='dtv2avi'

###### dtv2avi_w
function dtv2avi_w()
{
	# great xvid quality is "1600" (13mb/min) (watch the recording at the same time)
	dtvchannels
	echo -n "What digital tv channel would you like to convert?:
	"
	read dchan_type
	echo -n "Please enter how long you want to record (in this format: 02:08:17):
	"
	read time_type
	echo -n "Please enter a name for the AVI file you will convert:
	"
	read file_name
	echo -n "Please enter the quality you want your recording to be (in this format: 1600):
	"
	read qual_type
	mencoder dvb://$dchan_type -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip,scale -zoom -xy 624 -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type & (sleep 5 && mplayer $HOME/Temp/$file_name.avi)
}
alias dtvrip_w='dtv2avi_w'

###### DTV2AVI
function DTV2AVI()
{
	# best quality; big file size (100mb/min), but needs strong signal
	dtvchannels
	echo -n "What digital tv channel would you like to convert?:
	"
	read dchan_type
	echo -n "Please enter how long you want to record (in this format: 02:08:17):
	"
	read time_type
	echo -n "Please enter a name for the AVI file you will convert:
	"
	read file_name
	mencoder dvb://$dchan_type -ovc copy -oac copy -o $HOME/Temp/$file_name.mpg -endpos $time_type
}
alias DTVRIP='DTV2AVI'

###### DIGITAL TV to YouTube-compliant AVI
function dtv2yt()
{
	# ok quality (YouTube) (5mb/min)
	dtvchannels
	echo -n "What digital tv channel would you like to convert?:
	"
	read DIGITALSTATION
	echo -n "Please enter a name for the AVI file you will convert:
	"
	read AVINAME
	echo -n "Please enter how long you want to record (in this format: 02:08:17):
	"
	read ENDPOSITION
	mencoder dvb://"$DIGITALSTATION" -oac mp3lame -lameopts cbr=128 -ovc lavc -lavcopts vcodec=mpeg4 -ffourcc xvid -vf scale=320:-2,expand=:240:::1 -o "$AVINAME".avi -endpos "$ENDPOSITION"
}

####### list of all of the local digital tv channels
#function dtvchannels() {
#cat <<EOF
#<INSERT YOUR LOCAL DIGITAL TV STATIONS HERE>
#EOF
#}

###### TV (recording and watching (includes those tv functions above)
function tv()
{
	# Creator:		Inameiname
	# Original Creator:	Jose Catre-Vandis
	# Version: 1.0
	# Last modified: 24 September 2011
	# Requirements: mencoder & zenity
	# sudo apt-get install mencoder zenity
	#
	# THINGS YOU WILL NEED TO DO:
	# 1. A working dvb card and/or analog tv card
	# 2. If dvb, a ~/.mplayer/channels.conf
	# - can scan dvb channels and create this by:
	#	- sudo scan /usr/share/dvb/atsc/us-ATSC-
	#	- center-frequencies-8VSB > ~/.mplayer/
	#	- channels.conf
	# 3. If analog, a channel list, and tuned in!
	# - (all channels must have no spaces!)
	# - can scan analog channels and tune in by:
	# 	- tvtime-scanner
	# 4. Determine where your tv card is located, and
	# change if need be (script set on 'video1')
	# - tvtime-configure -d /dev/video0 # if tvtime
	# - otherwise, change 'video1' to 'video0' below
	######################## SOFTWARE CHECK
	############ Check for required software...
	mencoder_bin=`which mencoder | grep -c "mencoder"`
	###### check for mencoder (also requires 'zenity')
	if [ $mencoder_bin -eq "0" ]; then
		zenity --error --title="Error - Missing Software" \
		 --text="You do not have the mencoder package installed
		Please install it in order to use this script.
		Make sure that the Multiverse repositories are enabled and
		then type: 'sudo apt-get install mencoder' at a terminal."
		exit
	fi
	######################## CHOOSE TV TYPE
	############ What type of TV TYPE do you want?
	###### you can edit these entries to suit
	title="Which TV type do you want ?"
	tv_type=`zenity  --width="480" --height="300" --title="$title" --list --radiolist --column="Click Here" \
	    --column="Channel" --column="Description" \
	    FALSE "DVB_RECORD" "Records dvb tv"\
	    FALSE "ANALOG_RECORD" "Records analog tv"\
	    FALSE "DVB_TV" "Watch dvb tv through mplayer"\
	    TRUE "ANALOG_TV" "Watch analog tv through mplayer"\
	    FALSE "ANALOG_TV1" "Watch analog tv through tvtime 1"\
	    FALSE "ANALOG_TV2" "Watch analog tv through tvtime 2"\
	    | sed 's/ max//g' `
	echo "$tv_type chosen as the channel to record."
	###### user must select a target type (Check if they cancelled)
	if [ ! "$tv_type" ]; then
	    zenity --error --title="Error" --text="You must select a TV type!"
	    exit
	fi
	######################## TV TYPES
	if [ "$tv_type" = "DVB_RECORD" ]; then
	    ############ RECORD DVB TV
	    ###### Which DVB TV Channel? ######
	    ###### YOU NEED TO EDIT THIS SECTION FOR YOUR ENVIRONMENT
	    # just change the channel names to reflect your channels.conf file
	    # ensure there are no spaces in channel names here or in your channels.conf file
	    # can scan dvb channels and create this by:
	    # sudo scan /usr/share/dvb/atsc/us-ATSC-center-frequencies-8VSB > ~/.mplayer/channels.conf
	    title="Which DVB-T Channel do you want to record ?"
	    dchan_type=`zenity  --width="380" --height="500" --title="$title" --list --radiolist --column="Click Here" \
		--column="Channel" --column="Description" \
		TRUE "ABC" "" \
		FALSE "MYTV" "" \
		FALSE "NBC" "" \
		FALSE "CBS" "" \
		FALSE "CBS2" "" \
		FALSE "FOX" "" \
		FALSE "WOSU-HD" "" \
		FALSE "WOSU-D1" "" \
		FALSE "WOSU-D2" "" \
		FALSE "ADD" "" \
		FALSE "YOUR" "" \
		FALSE "OWN" "" \
		FALSE "CHANNELS" "" \
		FALSE "HERE" "" \
		FALSE "Custom" "Input your own channel: 'NBC'"\
		| sed 's/ max//g' `
	    echo "$dchan_type chosen as the channel to record."
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$dchan_type" ]; then
		zenity --error --title="Error" --text="You must select a Channel!"
		exit
	    fi
	    ###### How Long Do You Want To Record? ######
	    ###### how long?
	    title="How long do you want to record for ?"
	    time_type=`zenity  --width="380" --height="500" --title="$title" --list --radiolist --column="Click Here" \
		--column="Record Time" --column="Description" \
		TRUE "00:00:20" "20 seconds for testing" \
		FALSE "00:01:00" "1 minute" \
		FALSE "00:05:00" "5 minutes" \
		FALSE "00:10:00" "10 minutes" \
		FALSE "00:15:00" "15 minutes" \
		FALSE "00:30:00" "30 minutes" \
		FALSE "00:45:00" "45 minutes" \
		FALSE "01:00:00" "1 hour" \
		FALSE "01:15:00" "1:15 minutes" \
		FALSE "01:30:00" "1:30 minutes" \
		FALSE "01:45:00" "1:45 minutes" \
		FALSE "02:00:00" "2 hours" \
		FALSE "02:15:00" "2:15 minutes" \
		FALSE "02:30:00" "2:30 minutes" \
		FALSE "02:45:00" "2:45 minutes" \
		FALSE "03:00:00" "3 hours" \
		FALSE "03:15:00" "3:15 minutes" \
		FALSE "03:30:00" "3:30 minutes" \
		FALSE "03:45:00" "3:45 minutes" \
		FALSE "04:00:00" "4 hours" \
		FALSE "04:15:00" "4:15 minutes" \
		FALSE "04:30:00" "4:30 minutes" \
		FALSE "04:45:00" "4:45 minutes" \
		FALSE "05:00:00" "5 hours" \
		FALSE "05:15:00" "5:15 minutes" \
		FALSE "05:30:00" "5:30 minutes" \
		FALSE "05:45:00" "5:45 minutes" \
		FALSE "06:00:00" "6 hours" \
		FALSE "06:15:00" "6:15 minutes" \
		FALSE "06:30:00" "6:30 minutes" \
		FALSE "06:45:00" "6:45 minutes" \
		FALSE "07:00:00" "7 hours" \
		FALSE "07:15:00" "7:15 minutes" \
		FALSE "07:30:00" "7:30 minutes" \
		FALSE "07:45:00" "7:45 minutes" \
		FALSE "08:00:00" "8 hours" \
		FALSE "08:15:00" "8:15 minutes" \
		FALSE "08:30:00" "8:30 minutes" \
		FALSE "08:45:00" "8:45 minutes" \
		FALSE "09:00:00" "9 hours" \
		FALSE "09:15:00" "9:15 minutes" \
		FALSE "09:30:00" "9:30 minutes" \
		FALSE "09:45:00" "9:45 minutes" \
		FALSE "10:00:00" "10 hours" \
		FALSE "10:15:00" "10:15 minutes" \
		FALSE "10:30:00" "10:30 minutes" \
		FALSE "10:45:00" "10:45 minutes" \
		FALSE "11:00:00" "11 hours" \
		FALSE "11:15:00" "11:15 minutes" \
		FALSE "11:30:00" "11:30 minutes" \
		FALSE "11:45:00" "11:45 minutes" \
		FALSE "12:00:00" "12 hours" \
		FALSE "12:15:00" "12:15 minutes" \
		FALSE "12:30:00" "12:30 minutes" \
		FALSE "12:45:00" "12:45 minutes" \
		FALSE "13:00:00" "13 hours" \
		FALSE "13:15:00" "13:15 minutes" \
		FALSE "13:30:00" "13:30 minutes" \
		FALSE "13:45:00" "13:45 minutes" \
		FALSE "14:00:00" "14 hours" \
		FALSE "14:15:00" "14:15 minutes" \
		FALSE "14:30:00" "14:30 minutes" \
		FALSE "14:45:00" "14:45 minutes" \
		FALSE "15:00:00" "15 hours" \
		FALSE "15:15:00" "15:15 minutes" \
		FALSE "15:30:00" "15:30 minutes" \
		FALSE "15:45:00" "15:45 minutes" \
		FALSE "16:00:00" "16 hours" \
		FALSE "16:15:00" "16:15 minutes" \
		FALSE "16:30:00" "16:30 minutes" \
		FALSE "16:45:00" "16:45 minutes" \
		FALSE "17:00:00" "17 hours" \
		FALSE "17:15:00" "17:15 minutes" \
		FALSE "17:30:00" "17:30 minutes" \
		FALSE "17:45:00" "17:45 minutes" \
		FALSE "18:00:00" "18 hours" \
		FALSE "18:15:00" "18:15 minutes" \
		FALSE "18:30:00" "18:30 minutes" \
		FALSE "18:45:00" "18:45 minutes" \
		FALSE "19:00:00" "19 hours" \
		FALSE "19:15:00" "19:15 minutes" \
		FALSE "19:30:00" "19:30 minutes" \
		FALSE "19:45:00" "19:45 minutes" \
		FALSE "20:00:00" "20 hours" \
		FALSE "20:15:00" "20:15 minutes" \
		FALSE "20:30:00" "20:30 minutes" \
		FALSE "20:45:00" "20:45 minutes" \
		FALSE "21:00:00" "21 hours" \
		FALSE "21:15:00" "21:15 minutes" \
		FALSE "21:30:00" "21:30 minutes" \
		FALSE "21:45:00" "21:45 minutes" \
		FALSE "22:00:00" "22 hours" \
		FALSE "22:15:00" "22:15 minutes" \
		FALSE "22:30:00" "22:30 minutes" \
		FALSE "22:45:00" "22:45 minutes" \
		FALSE "23:00:00" "23 hours" \
		FALSE "23:15:00" "23:15 minutes" \
		FALSE "23:30:00" "23:30 minutes" \
		FALSE "23:45:00" "23:45 minutes" \
		FALSE "24:00:00" "24 hours" \
		| sed 's/ max//g' `
	    echo "$time_type chosen as the record time."
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$time_type" ]; then
		zenity --error --title="Error" --text="You must select a Time!"
		exit
	    fi
	    ###### Choose a Filename? ######
	    ###### user must enter a filename
	    title="Please enter a filename for your recording, no spaces"
	    file_name=`zenity  --width="480" --height="150" --title="$title" --entry`
	    echo "$file_name entered as the file name."
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$file_name" ]; then
		zenity --error --title="Error" --text="You must enter a Filename!"
		exit
	    fi
	    ###### Select the Quality of Your Recording? ######
	    ###### quality?
	    title="What quality do you want to record at ?"
	    qual_type=`zenity  --width="380" --height="380" --title="$title" --list --radiolist --column="Click Here" \
		--column="Record Quality" --column="Description" \
		FALSE "500" "Passable Quality"\
		FALSE "900" "OK Quality"\
		FALSE "1100" "VHS Quality"\
		FALSE "1300" "SVHS Quality"\
		FALSE "1500" "VCD Quality"\
		TRUE "1600" "MY Quality"\
		FALSE "1800" "SVCD Quality" \
		FALSE "2000" "Very Good Quality"\
		FALSE "2500" "High Quality" \
		FALSE "3000" "Excellent Quality"\
		FALSE "MPEG-TS" "Raw dvb in ts format"\
		| sed 's/ max//g' `
	    echo "$qual_type chosen as the encoding quality."
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$qual_type" ]; then
		zenity --error --title="Error" --text="You must select an encoding quality!"
		exit
	    fi
	    ###### Start Time, Now or a Set Time Later? ######
	    ###### date-time timer
	    # enter required time:
	    title="Please enter a start time..."
	    starttime=`zenity  --width="480" --height="150" --title="$title" --entry --entry-text="now" --text="Enter Start Time in 00:00 format
	    or click 'OK' for immediate start"`
	    echo "$starttime entered as the start time."
	    curtime=$(date --utc --date now +%s)
	    echo "$curtime entered as the current time."
	    righttime=$(date --utc --date $starttime +%s)
	    echo "$righttime entered as the start time."
	    # this bit copes with the starting time for the encode
	    # beginning after midnight the following day
	    if (($righttime<$curtime)); then
		    newtime=$(($righttime+86400))
	    else
		    newtime=$righttime
	    fi
	    waittime=$(($newtime - $curtime))
	    echo "$waittime entered as time to wait before encoding starts"
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$newtime" ]; then
		zenity --error --title="Error" --text="You must enter a Start Time!"
		exit
	    fi
	    echo Channel= $dchan_type
	    echo Filename= $file_name
	    echo Encode length= $time_type
	    echo Quality of encode= $qual_type
	    sleep $waittime
	    ###### The Actual DVB Video Encoding? ######
	    ###### video encoding DVB
	    # YOU NEED TO EDIT THIS SECTION FOR YOUR ENVIRONMENT
	    if [ "$qual_type" = "MPEG-TS" ]; then
		mencoder dvb://$dchan_type -ovc copy -oac copy -o $HOME/Temp/$file_name.mpg -endpos $time_type | zenity --progress --percentage=0 --title="DVB Recording Script" --text="Processing Video...
		$file_name"
	    elif [ "$dchan_type" = "Custom" ]; then
		# custom channel
		custom_dchannel="Please enter custom digital channel, no spaces"
		dchan_type_custom=`zenity  --width="480" --height="150" --title="$custom_dchannel" --entry`
		echo "$dchan_type_custom entered as the dvb channel."
		mencoder dvb://$dchan_type_custom -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip,scale -zoom -xy 624 -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type | zenity --progress --percentage=0 --title="DVB Recording Script" --text="Processing Video...
		$file_name"
	    else
		mencoder dvb://$dchan_type -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip,scale -zoom -xy 624 -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type | zenity --progress --percentage=0 --title="DVB Recording Script" --text="Processing Video...
		$file_name"
	    fi
	elif [ "$tv_type" = "ANALOG_RECORD" ]; then
	    ############ RECORD ANALOG TV
	    ###### Which Analog TV Channel? ######
	    ###### YOU NEED TO EDIT THIS SECTION FOR YOUR ENVIRONMENT
	    # just change the channel names to reflect your analog channels list
	    # you need to keep the "31-BBC1" style and format, if applicable.
	    # this is "channelnumber-channelname"
	    # can scan analog channels and tune in by (at least with tvtime):
	    # tvtime-scanner
	    title="Which Analog Channel do you want to record ?"
	    achan_type=`zenity  --width="380" --height="500" --title="$title" --list --radiolist --column="Click Here" \
		--column="Channel" --column="Description" \
		TRUE "Composite" "Records from Composite Input" \
		FALSE "SVIDEO" "Records from S-Video Input" \
		FALSE "1" ""\
		FALSE "2" ""\
		FALSE "3" ""\
		FALSE "4" ""\
		FALSE "5" ""\
		FALSE "6" ""\
		FALSE "7" ""\
		FALSE "8" ""\
		FALSE "9" ""\
		FALSE "10" ""\
		FALSE "11" ""\
		FALSE "12" ""\
		FALSE "13" ""\
		FALSE "14" ""\
		FALSE "15" ""\
		FALSE "16" ""\
		FALSE "17" ""\
		FALSE "18" ""\
		FALSE "19" ""\
		FALSE "20" ""\
		FALSE "21" ""\
		FALSE "22" ""\
		FALSE "23" ""\
		FALSE "24" ""\
		FALSE "25" ""\
		FALSE "26" ""\
		FALSE "27" ""\
		FALSE "28" ""\
		FALSE "29" ""\
		FALSE "30" ""\
		FALSE "31" ""\
		FALSE "32" ""\
		FALSE "33" ""\
		FALSE "34" ""\
		FALSE "35" ""\
		FALSE "36" ""\
		FALSE "37" ""\
		FALSE "38" ""\
		FALSE "39" ""\
		FALSE "40" ""\
		FALSE "41" ""\
		FALSE "42" ""\
		FALSE "43" ""\
		FALSE "44" ""\
		FALSE "45" ""\
		FALSE "46" ""\
		FALSE "47" ""\
		FALSE "48" ""\
		FALSE "49" ""\
		FALSE "50" ""\
		FALSE "51" ""\
		FALSE "52" ""\
		FALSE "53" ""\
		FALSE "54" ""\
		FALSE "55" ""\
		FALSE "56" ""\
		FALSE "57" ""\
		FALSE "58" ""\
		FALSE "59" ""\
		FALSE "60" ""\
		FALSE "61" ""\
		FALSE "62" ""\
		FALSE "63" ""\
		FALSE "64" ""\
		FALSE "65" ""\
		FALSE "66" ""\
		FALSE "67" ""\
		FALSE "68" ""\
		FALSE "69" ""\
		FALSE "70" ""\
		FALSE "71" ""\
		FALSE "72" ""\
		FALSE "73" ""\
		FALSE "74" ""\
		FALSE "75" ""\
		FALSE "76" ""\
		FALSE "77" ""\
		FALSE "78" ""\
		FALSE "79" ""\
		FALSE "80" ""\
		FALSE "81" ""\
		FALSE "82" ""\
		FALSE "83" ""\
		FALSE "84" ""\
		FALSE "85" ""\
		FALSE "86" ""\
		FALSE "87" ""\
		FALSE "88" ""\
		FALSE "89" ""\
		FALSE "90" ""\
		FALSE "91" ""\
		FALSE "92" ""\
		FALSE "93" ""\
		FALSE "94" ""\
		FALSE "95" ""\
		FALSE "96" ""\
		FALSE "97" ""\
		FALSE "98" ""\
		FALSE "99" ""\
		FALSE "100" ""\
		FALSE "101" ""\
		FALSE "102" ""\
		FALSE "103" ""\
		FALSE "104" ""\
		FALSE "105" ""\
		FALSE "106" ""\
		FALSE "107" ""\
		FALSE "108" ""\
		FALSE "109" ""\
		FALSE "110" ""\
		FALSE "111" ""\
		FALSE "112" ""\
		FALSE "113" ""\
		FALSE "114" ""\
		FALSE "115" ""\
		FALSE "116" ""\
		FALSE "117" ""\
		FALSE "118" ""\
		FALSE "119" ""\
		FALSE "120" ""\
		FALSE "121" ""\
		FALSE "122" ""\
		FALSE "123" ""\
		FALSE "124" ""\
		FALSE "125" ""\
		FALSE "Custom" "Input your own channel: '234'"\
		| sed 's/ max//g' `
	    echo "$achan_type chosen as the channel to record."
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$achan_type" ]; then
		zenity --error --title="Error" --text="You must select a Channel!"
		exit
	    fi
	    ###### How Long Do You Want To Record? ######
	    ###### how long?
	    title="How long do you want to record for ?"
	    time_type=`zenity  --width="380" --height="500" --title="$title" --list --radiolist --column="Click Here" \
		--column="Record Time" --column="Description" \
		TRUE "00:00:20" "20 seconds for testing" \
		FALSE "00:01:00" "1 minute" \
		FALSE "00:05:00" "5 minutes" \
		FALSE "00:10:00" "10 minutes" \
		FALSE "00:15:00" "15 minutes" \
		FALSE "00:30:00" "30 minutes" \
		FALSE "00:45:00" "45 minutes" \
		FALSE "01:00:00" "1 hour" \
		FALSE "01:15:00" "1:15 minutes" \
		FALSE "01:30:00" "1:30 minutes" \
		FALSE "01:45:00" "1:45 minutes" \
		FALSE "02:00:00" "2 hours" \
		FALSE "02:15:00" "2:15 minutes" \
		FALSE "02:30:00" "2:30 minutes" \
		FALSE "02:45:00" "2:45 minutes" \
		FALSE "03:00:00" "3 hours" \
		FALSE "03:15:00" "3:15 minutes" \
		FALSE "03:30:00" "3:30 minutes" \
		FALSE "03:45:00" "3:45 minutes" \
		FALSE "04:00:00" "4 hours" \
		FALSE "04:15:00" "4:15 minutes" \
		FALSE "04:30:00" "4:30 minutes" \
		FALSE "04:45:00" "4:45 minutes" \
		FALSE "05:00:00" "5 hours" \
		FALSE "05:15:00" "5:15 minutes" \
		FALSE "05:30:00" "5:30 minutes" \
		FALSE "05:45:00" "5:45 minutes" \
		FALSE "06:00:00" "6 hours" \
		FALSE "06:15:00" "6:15 minutes" \
		FALSE "06:30:00" "6:30 minutes" \
		FALSE "06:45:00" "6:45 minutes" \
		FALSE "07:00:00" "7 hours" \
		FALSE "07:15:00" "7:15 minutes" \
		FALSE "07:30:00" "7:30 minutes" \
		FALSE "07:45:00" "7:45 minutes" \
		FALSE "08:00:00" "8 hours" \
		FALSE "08:15:00" "8:15 minutes" \
		FALSE "08:30:00" "8:30 minutes" \
		FALSE "08:45:00" "8:45 minutes" \
		FALSE "09:00:00" "9 hours" \
		FALSE "09:15:00" "9:15 minutes" \
		FALSE "09:30:00" "9:30 minutes" \
		FALSE "09:45:00" "9:45 minutes" \
		FALSE "10:00:00" "10 hours" \
		FALSE "10:15:00" "10:15 minutes" \
		FALSE "10:30:00" "10:30 minutes" \
		FALSE "10:45:00" "10:45 minutes" \
		FALSE "11:00:00" "11 hours" \
		FALSE "11:15:00" "11:15 minutes" \
		FALSE "11:30:00" "11:30 minutes" \
		FALSE "11:45:00" "11:45 minutes" \
		FALSE "12:00:00" "12 hours" \
		FALSE "12:15:00" "12:15 minutes" \
		FALSE "12:30:00" "12:30 minutes" \
		FALSE "12:45:00" "12:45 minutes" \
		FALSE "13:00:00" "13 hours" \
		FALSE "13:15:00" "13:15 minutes" \
		FALSE "13:30:00" "13:30 minutes" \
		FALSE "13:45:00" "13:45 minutes" \
		FALSE "14:00:00" "14 hours" \
		FALSE "14:15:00" "14:15 minutes" \
		FALSE "14:30:00" "14:30 minutes" \
		FALSE "14:45:00" "14:45 minutes" \
		FALSE "15:00:00" "15 hours" \
		FALSE "15:15:00" "15:15 minutes" \
		FALSE "15:30:00" "15:30 minutes" \
		FALSE "15:45:00" "15:45 minutes" \
		FALSE "16:00:00" "16 hours" \
		FALSE "16:15:00" "16:15 minutes" \
		FALSE "16:30:00" "16:30 minutes" \
		FALSE "16:45:00" "16:45 minutes" \
		FALSE "17:00:00" "17 hours" \
		FALSE "17:15:00" "17:15 minutes" \
		FALSE "17:30:00" "17:30 minutes" \
		FALSE "17:45:00" "17:45 minutes" \
		FALSE "18:00:00" "18 hours" \
		FALSE "18:15:00" "18:15 minutes" \
		FALSE "18:30:00" "18:30 minutes" \
		FALSE "18:45:00" "18:45 minutes" \
		FALSE "19:00:00" "19 hours" \
		FALSE "19:15:00" "19:15 minutes" \
		FALSE "19:30:00" "19:30 minutes" \
		FALSE "19:45:00" "19:45 minutes" \
		FALSE "20:00:00" "20 hours" \
		FALSE "20:15:00" "20:15 minutes" \
		FALSE "20:30:00" "20:30 minutes" \
		FALSE "20:45:00" "20:45 minutes" \
		FALSE "21:00:00" "21 hours" \
		FALSE "21:15:00" "21:15 minutes" \
		FALSE "21:30:00" "21:30 minutes" \
		FALSE "21:45:00" "21:45 minutes" \
		FALSE "22:00:00" "22 hours" \
		FALSE "22:15:00" "22:15 minutes" \
		FALSE "22:30:00" "22:30 minutes" \
		FALSE "22:45:00" "22:45 minutes" \
		FALSE "23:00:00" "23 hours" \
		FALSE "23:15:00" "23:15 minutes" \
		FALSE "23:30:00" "23:30 minutes" \
		FALSE "23:45:00" "23:45 minutes" \
		FALSE "24:00:00" "24 hours" \
		| sed 's/ max//g' `
	    echo "$time_type chosen as the record time."
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$time_type" ]; then
		zenity --error --title="Error" --text="You must select a Time!"
		exit
	    fi
	    ###### Choose a Filename? ######
	    ###### user must enter a filename
	    title="Please enter a filename for your recording, no spaces"
	    file_name=`zenity  --width="480" --height="150" --title="$title" --entry`
	    echo "$file_name entered as the file name."
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$file_name" ]; then
		zenity --error --title="Error" --text="You must enter a Filename!"
		exit
	    fi
	    ###### Select the Quality of Your Recording? ######
	    ###### quality?
	    title="What quality do you want to record at ?"
	    qual_type=`zenity  --width="380" --height="380" --title="$title" --list --radiolist --column="Click Here" \
		--column="Record Quality" --column="Description" \
		FALSE "500" "Passable Quality"\
		FALSE "900" "OK Quality"\
		FALSE "1100" "VHS Quality"\
		FALSE "1300" "SVHS Quality"\
		FALSE "1500" "VCD Quality"\
		TRUE "1600" "MY Quality"\
		FALSE "1800" "SVCD Quality" \
		FALSE "2000" "Very Good Quality"\
		FALSE "2500" "High Quality" \
		FALSE "3000" "Excellent Quality"\
		| sed 's/ max//g' `
	    echo "$qual_type chosen as the encoding quality."
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$qual_type" ]; then
		zenity --error --title="Error" --text="You must select an encoding quality!"
		exit
	    fi
	    ###### Start Time, Now or a Set Time Later? ######
	    ###### date-time timer
	    # enter required time:
	    title="Please enter a start time..."
	    starttime=`zenity  --width="480" --height="150" --title="$title" --entry --entry-text="now" --text="Enter Start Time in 00:00 format
	    or click 'OK' for immediate start"`
	    echo "$starttime entered as the start time."
	    curtime=$(date --utc --date now +%s)
	    echo "$curtime entered as the current time."
	    newtime=$(date --utc --date $starttime +%s)
	    echo "$newtime entered as the start time."
	    waittime=$(($newtime - $curtime))
	    echo "$waittime entered as time to wait before encoding starts"
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$newtime" ]; then
		zenity --error --title="Error" --text="You must enter a Start Time!"
		exit
	    fi
	    echo Channel= $achan_type
	    echo Filename= $file_name
	    echo Encode length= $time_type
	    echo Quality of encode= $qual_type
	    sleep $waittime
	    ###### The Actual Analog Video Encoding? ######
	    ###### video encoding analog
	    # YOU NEED TO EDIT THIS SECTION FOR YOUR ENVIRONMENT
	    # In the third script (after "else") just change the
	    # chanlist value from us-cable to your chanlist region
	    # AND change device (video1) to video0 or whatever if need be
	    if [ "$achan_type" = "Composite" ]; then
		input_type=1
		mencoder -tv driver=v4l2:device=/dev/video1:input=$input_type:norm=ntsc:alsa=1:adevice=hw.1:audiorate=48000:immediatemode=0:amode=1 tv:// -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type | zenity --progress --percentage=0 --title="COMPOSITE Recording Script" --text="Processing Video...
		$file_name"
	    elif [ "$achan_type" = "SVIDEO" ]; then
		input_type=2
		mencoder -tv driver=v4l2:device=/dev/video1:input=$input_type:norm=ntsc:alsa=1:adevice=hw.1:audiorate=48000:immediatemode=0:amode=1 tv:// -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type | zenity --progress --percentage=0 --title="SVIDEO Recording Script" --text="Processing Video...
		$file_name"
	    elif [ "$achan_type" = "Custom" ]; then
		# custom channel
		custom_achannel="Please enter custom analog channel, no spaces"
		achan_type_custom=`zenity  --width="480" --height="150" --title="$custom_achannel" --entry`
		echo "$achan_type_custom entered as the analog channel."
		mencoder -tv driver=v4l2:device=/dev/video1:input=0:norm=ntsc:chanlist=us-cable:channel=$achan_type_custom:alsa=1:adevice=hw.1:audiorate=48000:immediatemode=0:amode=1 tv:// -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type | zenity --progress --percentage=0 --title="ANALOG TV Recording Script" --text="Processing Video...
		$file_name"
	    else
		mencoder -tv driver=v4l2:device=/dev/video1:input=0:norm=ntsc:chanlist=us-cable:channel=$achan_type:alsa=1:adevice=hw.1:audiorate=48000:immediatemode=0:amode=1 tv:// -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=$qual_type:vhq:v4mv:keyint=250 -vf pp=de,pullup,softskip -oac mp3lame -lameopts abr:br=128:vol=3 -ffourcc xvid -o $HOME/Temp/$file_name.avi -endpos $time_type | zenity --progress --percentage=0 --title="ANALOG TV Recording Script" --text="Processing Video...
		$file_name"
	    fi
	elif [ "$tv_type" = "DVB_TV" ]; then
	    ############ WATCH DVB TV (through MPlayer)
	    # YOU NEED TO EDIT THIS SECTION FOR YOUR ENVIRONMENT
	    # gives you list of your current dvb channels
	    dchan_type=$(zenity --entry --text="What digital tv channel would you like to watch?:

	    ATSC/NTSC local digital channel list:
	    ADD YOUR LIST OF DIGITAL CHANNELS HERE FOR EASY USE ")
	    mplayer dvb://$dchan_type
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$dchan_type" ]; then
		zenity --error --title="Error" --text="You must select a Channel!"
		exit
	    fi
	elif [ "$tv_type" = "ANALOG_TV" ]; then
	    ############ WATCH Analog TV (through MPlayer)
	    achan_type=$(zenity --entry --text="What analog/cable tv channel would you like to watch?: ")
	    sh -c "mplayer -tv driver=v4l2:device=/dev/video1:input=0:norm=ntsc:chanlist=us-cable:channel=$achan_type tv:// & sox -r 48000 -t alsa hw:1,0 -t alsa hw:0,0"
	    ###### user must select a target type (Check if they cancelled)
	    if [ ! "$achan_type" ]; then
		zenity --error --title="Error" --text="You must select a Channel!"
		exit
	    fi
	elif [ "$tv_type" = "ANALOG_TV1" ]; then
	    ############ WATCH Analog TV (through TVtime 1)
	    sox -s -r 32000 -c 2 -t alsa hw:1,0 -s -r 32000 -c 2 -t alsa hw:0,0 &
	    tvtime
	    t=`pidof sox`;
	    kill $t;
	else
	    ############ WATCH Analog TV (through TVtime 2)
	    sh -c "tvtime & sox -r 48000 -t alsa hw:1,0 -t alsa hw:0,0"
	fi
	exit
}

############ DVD ############

###### DVD to ISO
function dvd2iso()
{
	# to get desired device
	df -h -x tmpfs -x usbfs
	echo -n "Using the information in the terminal window, please enter the appropriate DVD drive:
	"
	read DVDDEVICE
	echo -n "Please enter a name for the ISO file you will create:
	"
	read XVIDNAME
	pv "$DVDDEVICE" | dd of="$XVIDNAME".iso
}
alias dvdcopy='dvd2iso'

###### DVD to MPG
function dvd2mpg()
{
	# to get desired device
	df -h -x tmpfs -x usbfs
	echo -n "Using the information in the terminal window, please enter the appropriate DVD drive:
	"
	read DVDDEVICE
	# to get desired title on dvd
	# requires lsdvd: sudo apt-get install lsdvd
	lsdvd "$DVDDEVICE"
	echo -n "Using the information in the terminal window, please enter the title number you will convert (usually the longest one):
	"
	read DVDTITLE
	echo -n "Please enter a name for the MPG/MPEG file you will convert:
	"
	read MPEGNAME
	mplayer dvd://"$DVDTITLE" -dumpstream -alang es -dumpfile "$MPEGNAME".mpg
}
alias dvd2mpeg='dvd2mpg'

###### DVD to VOB - requires vobcopy: sudo apt-get install vobcopy
alias dvd2vob='vobcopy -i /dev/dvd -o ~/ -l'
alias dvd2vob='dvd2mpg'

###### extract audio from DVD VOB files - USAGE:	dvdaudio input_file.vob output_file.ac3
function dvdaudio()
{
	echo -n "Please enter the name (full path) for the MPG/MPEG/VOB file you will extract the audio from:
	"
	read VOBNAME
	echo -n "Please enter a name for the audio file you will extract from the MPG/MPEG/VOB file:
	"
	read AC3NAME
	mplayer "$VOBNAME" -aid 128 -dumpaudio -dumpfile "$AC3NAME"
}

############ Video ############

###### Video to AVI
function video2avi()
{
	# Video To Avi
	# Created:	Inameiname
	# Version:	3.2
	####################### Run in the terminal on double-click
	tty -s; if [ $? -ne 0 ] ; then gnome-terminal -e "$0"; exit; fi
	####################### If it doesn't run in the terminal on double-click, say so
	[ -t 0 ] && [ -t 1 ] || { zenity --warning --text="${0}: this script must be run from a terminal." ; exit 1 ;}
	####################### Check whether environment variables are empty
	###### see if the Nautilus environment variable is empty
	# if it exists, set it equal to 'INPUT_FILE'
	for ARCHIVE_FULLPATH in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
	    ARCHIVE_PATH=${ARCHIVE_FULLPATH%.*}
	if [ -f $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ] ; then
	# if select iso file:
	if [ $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS = $ARCHIVE_PATH.iso ] ; then
	# to get desired title on dvd
	# requires lsdvd: sudo apt-get install lsdvd
	lsdvd $ARCHIVE_PATH.iso
	echo -n "Please enter the title number you will convert (usually the longest one):

	Press 'Enter' for default (default is '1')...

	"
	read TITLE
	# extra blank space
	echo "
	"
	# default
	if [[ -z $TITLE ]] ; then
	# If no title passed, default to 1
	    TITLE=1
	fi
	    INPUT_FILE="dvd://$TITLE -dvd-device $ARCHIVE_PATH.iso"
	fi
	# if select video file:
	if [ $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS != $ARCHIVE_PATH.iso ] ; then
	    INPUT_FILE=$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
	fi
	fi
	done
	# if it's blank, set it equal to $1
	if [ -z $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ] ; then
	    # If it's blank, set it equal to $1
	    NAUTILUS_SCRIPT_SELECTED_FILE_PATHS=$1
	###### see if the '$1' variable is empty
	# if it exists, set it equal to 'INPUT_FILE'
	for ARCHIVE_FULLPATH in $1; do
	    ARCHIVE_PATH=${ARCHIVE_FULLPATH%.*}
	if [ -f $1 ] ; then
	# if select iso file:
	if [ $1 = $ARCHIVE_PATH.iso ] ; then
	# to get desired title on dvd
	# requires lsdvd: sudo apt-get install lsdvd
	lsdvd $ARCHIVE_PATH.iso
	echo -n "Please enter the title number you will convert (usually the longest one):

	Press 'Enter' for default (default is '1')...

	"
	read TITLE
	# extra blank space
	echo "
	"
	# default
	if [[ -z $TITLE ]] ; then
	# If no title passed, default to 1
	    TITLE=1
	fi
	    INPUT_FILE="dvd://$TITLE -dvd-device $ARCHIVE_PATH.iso"
	fi
	# if select video file:
	if [ $1 != $ARCHIVE_PATH.iso ] ; then
	    INPUT_FILE=$1
	fi
	fi
	done
	# if it's blank, do the following:
	if [ -z "$1" ] ; then
	####################### Input DVD/ISO/VIDEO file menu
	echo -n "What do you want to convert to AVI?:

	(1) DVD
	(2) ISO file
	(3) Video file (such as MKV, VOB, MPEG, AVI, WMV, and etc.)

	Press 'Enter' for default (default is '1')...

	"
	read TYPE
	# extra blank space
	echo "
	"
	###### Input DVD/ISO/VIDEO source default ######
	if [[ -z $TYPE ]] ; then
	    # If no media passed, default to 1
	    TYPE=1
	fi
	###### Input DVD/ISO/VIDEO source ######
	###### DVD to AVI
	if [[ $TYPE = 1 ]] ; then
	# to get desired device
	df -h -x tmpfs -x usbfs
	echo -n "Please enter the appropriate DVD drive:

	(1) /dev/dvd
	(2) /dev/sr0
	(3) /dev/sr1
	(4) /dev/sr2
	(5) custom

	Press 'Enter' for default (default is '1')...

	"
	read DEVICE_NUMBER
	# extra blank space
	echo "
	"
	# default
	if [[ -z $DEVICE_NUMBER ]] ; then
	# If no device passed, default to /dev/dvd
	    DEVICE=/dev/dvd
	fi
	# preset
	if [[ $DEVICE_NUMBER = 1 ]] ; then
	    DEVICE=/dev/dvd
	fi
	if [[ $DEVICE_NUMBER = 2 ]] ; then
	    DEVICE=/dev/sr0
	fi
	if [[ $DEVICE_NUMBER = 3 ]] ; then
	    DEVICE=/dev/sr1
	fi
	if [[ $DEVICE_NUMBER = 4 ]] ; then
	    DEVICE=/dev/sr2
	fi
	# custom
	if [[ $DEVICE_NUMBER = 5 ]] ; then
	    echo -n "Please enter the appropriate DVD drive:  "
	    echo -n "...like this: '/dev/dvd'..."
	    read CUSTOM_DEVICE
	    DEVICE=$CUSTOM_DEVICE
	fi
	# to get desired title on dvd
	# requires lsdvd: sudo apt-get install lsdvd
	lsdvd $DEVICE
	echo -n "Please enter the title number you will convert (usually the longest one):

	Press 'Enter' for default (default is '1')...

	"
	read TITLE
	# extra blank space
	echo "
	"
	# default
	if [[ -z $TITLE ]] ; then
	# If no title passed, default to 1
	TITLE=1
	fi
	# to decide to copy straight from the DVD or first copy to hard drive to ISO
	echo -n "Would you first like to copy the DVD onto your hard drive (to ISO)?:

	(1) Yes (Highly Recommended)
	(2) No

	Press 'Enter' for default (default is '1')...

	"
	read DVD2ISO
	# extra blank space
	echo "
	"
	# default
	if [[ -z $DVD2ISO ]] ; then
	# If no DVD2ISO passed, default to 1
	dd if=$DEVICE of=NEW.iso
	INPUT_FILE="dvd://$TITLE -dvd-device NEW.iso"
	fi
	# preset
	if [[ $DVD2ISO = 1 ]] ; then
	dd if=$DEVICE of=NEW.iso
	INPUT_FILE="dvd://$TITLE -dvd-device NEW.iso"
	fi
	if [[ $DVD2ISO = 2 ]] ; then
	INPUT_FILE="dvd://$TITLE -dvd-device $DEVICE"
	fi
	fi
	###### ISO to AVI
	if [[ $TYPE = 2 ]] ; then
	echo -n "Please enter the full path for the ISO:

	Example: /home/(your username)/Videos/NEW.iso...

	"
	read ISO
	# extra blank space
	echo "
	"
	# to get desired title on dvd
	# requires lsdvd: sudo apt-get install lsdvd
	lsdvd $ISO
	echo -n "Please enter the title number you will convert (usually the longest one):

	Press 'Enter' for default (default is '1')...

	"
	read TITLE
	# extra blank space
	echo "
	"
	# default
	if [[ -z $TITLE ]] ; then
	# If no title passed, default to 1
	TITLE=1
	fi
	INPUT_FILE="dvd://$TITLE -dvd-device $ISO"
	fi
	###### Video to AVI
	if [[ $TYPE = 3 ]] ; then
	echo -n "Please enter the name for the input file (full path, with extension):

	It can be any type, such as MKV, VOB, MPEG, AVI, WMV, and etc...

	Example: /home/(your username)/Videos/NEW.avi...

	"
	read VIDEO_FILE
	# extra blank space
	echo "
	"
	INPUT_FILE=$VIDEO_FILE
	fi
	####################### Close the variable statements
	fi
	fi
	####################### Cropping (done automatically)
	###### start a timer to kill mplayer
	echo "Cropdetect is now running...

	A few seconds of your video should now be playing...
	"
	###### start a timer to kill mplayer
	(sleep 6 && killall mplayer)&
	###### start the mplayer cropdetect on on the DVD at a random time
	mplayer $INPUT_FILE -ss 0:03:10 -vf cropdetect &> mplayer.tmp
	###### get last crop value from mplayer output and store in variable
	CROP_VALUES=$(awk -F'crop=' '/\[CROP\]/{f=$2} END{print f}' ./mplayer.tmp |cut -d')' -f1)
	###### print detected crop values
	echo -e "\n\nDetected crop values = ${CROP_VALUES}\n\n"
	####################### Output desired name for file
	###### file input
	echo -n "Please enter a name for the output file (without extension):

	Press 'Enter' for default (default is 'NEW')...

	"
	read OUTPUT_FILE
	###### extra blank space
	echo "
	"
	###### default ######
	if [[ -z $OUTPUT_FILE ]] ; then
	    # If no file passed, default to NEW
	    OUTPUT_FILE=NEW_$(date "+%y.%m.%d_%H.%M")
	fi
	####################### Available processor number (done automatically)
	CPUS=$(grep -c processor /proc/cpuinfo)
	echo "Using $CPUS processor(s)..."
	###### extra blank space
	echo "
	"
	####################### Preset/Custom type options
	echo -n "Select a quality level:
	(1) exact copy quality MPEG		    (DVD/ISO sources only)
	(2) exact copy audio-only quality AC3	    (DVD/ISO sources only)
	(3) very high quality H.264 (2-pass)	    (350min:105min film w/2 1.5mhz cpus)
	(4) very high quality DIVX/MPEG-4 (2-pass)  (270min:105min film w/2 1.5mhz cpus)
	(5) very high quality XVID (2-pass)	    (220min:105min film w/2 1.5mhz cpus)
	(6) very high quality H.264 (1-pass)	    (400min:105min film w/2 1.5mhz cpus)
	(7) very high quality DIVX/MPEG-4 (1-pass)  (230min:105min film w/2 1.5mhz cpus)
	(8) very high quality XVID (1-pass)	    (180min:105min film w/2 1.5mhz cpus)
	(9) high quality H.264 (2-pass)		    (240min:105min film w/2 1.5mhz cpus)
	(10)high quality DIVX/MPEG-4 (2-pass)	    (190min:105min film w/2 1.5mhz cpus)
	(11)high quality XVID (2-pass)		    (135min:105min film w/2 1.5mhz cpus)
	(12)high quality H.264 (1-pass)	     	    (200min:105min film w/2 1.5mhz cpus)
	(13)high quality DIVX/MPEG-4 (1-pass)	    (150min:105min film w/2 1.5mhz cpus)
	(14)high quality XVID (1-pass)		    (090min:105min film w/2 1.5mhz cpus)
	(15)fast quality H.264 (1-pass)	     	    (155min:105min film w/2 1.5mhz cpus)
	(16)fast quality DIVX/MPEG-4 (1-pass)	    (065min:105min film w/2 1.5mhz cpus)
	(17)fast quality XVID (1-pass)		    (065min:105min film w/2 1.5mhz cpus)
	(18)fast quality XVID YouTube (1-pass)	    (025min:105min film w/2 1.5mhz cpus)
	(19)realtime quality DIVX/MPEG-4 (1-pass)   (050min:105min film w/2 1.5mhz cpus)
	(20)realtime quality XVID (1-pass)	    (060min:105min film w/2 1.5mhz cpus)
	(21)low quality WMV (1-pass)		    (017min:105min film w/2 1.5mhz cpus)
	(22)custom quality
	Press 'Enter' for default (default is '14')...  "
	read Q
	###### extra blank space
	echo "
	"
	###### default ######
	if [[ -z $Q ]] ; then
	    # If no quality passed, default to 14
	    Q=14
	fi
	####################### Frame rate
	###### frame rate menu
	if [[ $Q != 1 && $Q != 2 ]] ; then
	echo -n "Select a frame rate level:

	(1) NTSC-VIDEO 	(~ 30 fps)
	(2) NTSC-FILM	(~ 24 fps)
	(3) PAL		(~ 25 fps)
	(4) Streaming	(~ 15 fps)
	(5) custom

	Press 'Enter' for default (default is '2')...

	"
	read FRAME_RATE_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $FRAME_RATE_NUMBER ]] ; then
	    # If no frame rate passed, default to 2
	    FRAME_RATE="-ofps 24000/1001"
	fi
	###### preset
	if [[ $FRAME_RATE_NUMBER = 1 ]] ; then
	    FRAME_RATE="-ofps 30000/1001"
	fi
	if [[ $FRAME_RATE_NUMBER = 2 ]] ; then
	    FRAME_RATE="-ofps 24000/1001"
	fi
	if [[ $FRAME_RATE_NUMBER = 3 ]] ; then
	    FRAME_RATE="-ofps 25000/1001"
	fi
	if [[ $FRAME_RATE_NUMBER = 4 ]] ; then
	    FRAME_RATE="-ofps 15000/1001"
	fi
	###### custom
	if [[ $FRAME_RATE_NUMBER = 5 ]] ; then
	    echo -n "Please enter a frame rate:  "
	    echo -n "...like this: '-ofps 15000/1001'..."
	    read CUSTOM_FRAME_RATE
	    FRAME_RATE=$CUSTOM_FRAME_RATE
	fi
	fi
	####################### Divx ffourcc menu
	###### DivX ffourcc menu
	if [[ $Q != 1 && $Q != 2 && $Q != 3 && $Q != 5 && $Q != 6 && $Q != 8 && $Q != 9 && Q != 11 && $Q != 12 && $Q != 14 && $Q != 15 && $Q != 17 && $Q != 18 && $Q != 20 && $Q != 21 && $Q != 22 ]] ; then
	echo -n "Select the desired Divx or generic MPEG4 quality:

	(1) FFMPEG MPEG-4
	(2) DivX MPEG-4 Version 4
	(3) DivX MPEG-4 Version 5

	Press 'Enter' for default (default is '3')...

	"
	read DIVX_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $DIVX_NUMBER ]] ; then
	    # If no file passed, default to 3
	    DIVX="-ffourcc DX50"
	fi
	###### preset
	if [[ $DIVX_NUMBER = 1 ]] ; then
	    DIVX=
	fi
	if [[ $DIVX_NUMBER = 2 ]] ; then
	    DIVX="-ffourcc DIVX"
	fi
	if [[ $DIVX_NUMBER = 3 ]] ; then
	    DIVX="-ffourcc DX50"
	fi
	fi
	####################### Conversion is starting
	###### conversion is starting message
	if [[ $Q != 22 ]] ; then
	read -sn 1 -p "Your conversion is about to begin, press any key to continue..."
	fi
	###### extra blank space
	echo "
	"
	####################### Conversions
	###### preset ######
	###### exact copy quality (DVD/ISO sources only)
	if [[ $Q = 1 ]] ; then
	# If 1 passed, use MPEG exact copy quality
	mplayer $INPUT_FILE -dumpstream -dumpfile $OUTPUT_FILE.mpg
	fi
	if [[ $Q = 2 ]] ; then
	# If 2 passed, use MPEG exact copy audio-only quality
	mplayer $INPUT_FILE -dumpaudio -dumpfile $OUTPUT_FILE.ac3
	fi
	###### very high quality
	if [[ $Q = 3 ]] ; then
	# very high H.264 quality (2-pass)
	# actual two-pass conversion
	mencoder $INPUT_FILE -nosound -ovc x264 -x264encopts pass=1:subq=1:partitions=all:8x8dct:me=umh:frameref=1:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=2000 -vf pp=de,pullup,softskip,harddup,crop=${CROP_VALUES} $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=192:vol=3 -ovc x264 -x264encopts pass=2:subq=6:partitions=all:8x8dct:me=umh:frameref=5:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=2000 -vf pp=de,pullup,softskip,harddup,crop=${CROP_VALUES} $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 4 ]] ; then
	# very high MPEG4 quality (2-pass)
	# actual two-pass conversion
	mencoder $INPUT_FILE -nosound -ovc lavc $DIVX -lavcopts vpass=1:vcodec=mpeg4:mbd=2:trell:v4mv:last_pred=2:dia=-1:vmax_b_frames=2:vb_strategy=1:cmp=3:subcmp=3:precmp=0:vqcomp=0.6:turbo:vhq:threads=$CPUS:vbitrate=2000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES} $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=192:vol=3 -ovc lavc $DIVX -lavcopts vpass=2:vcodec=mpeg4:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:predia=2:dia=2:vmax_b_frames=2:vb_strategy=1:precmp=2:cmp=2:subcmp=2:preme=2:qns=2:vhq:threads=$CPUS:vbitrate=2000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES} $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 5 ]] ; then
	# very high XVID quality (2-pass)
	# actual two-pass conversion
	mencoder $INPUT_FILE -nosound -ovc xvid -xvidencopts pass=1:chroma_opt:vhq=1:bvhq=1:quant_type=mpeg:threads=$CPUS:bitrate=2000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES} $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=192:vol=3 -ovc xvid -xvidencopts pass=2:chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:threads=$CPUS:bitrate=2000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES} $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 6 ]] ; then
	# very high H.264 quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=192:vol=3 -ovc x264 -x264encopts subq=6:partitions=all:8x8dct:me=umh:frameref=5:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=2000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES} $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 7 ]] ; then
	# very high MPEG4 quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=192:vol=3 -ovc lavc $DIVX -lavcopts vcodec=mpeg4:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:predia=2:dia=2:vmax_b_frames=2:vb_strategy=1:precmp=2:cmp=2:subcmp=2:preme=2:qns=2:vhq:threads=$CPUS:vbitrate=2000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES} $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 8 ]] ; then
	# very high XVID quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=192:vol=3 -ovc xvid -xvidencopts chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:threads=$CPUS:bitrate=2000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES} $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	###### high quality
	if [[ $Q = 9 ]] ; then
	# high H.264 quality (2-pass)
	# actual two-pass conversion
	mencoder $INPUT_FILE -nosound -ovc x264 -x264encopts pass=1:subq=1:partitions=all:8x8dct:me=umh:frameref=1:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=-700000 -vf pp=de,pullup,softskip,harddup,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc x264 -x264encopts pass=2:subq=5:8x8dct:frameref=2:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=1200 -vf pp=de,pullup,softskip,harddup,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 10 ]] ; then
	# high MPEG4 quality (2-pass)
	# actual two-pass conversion
	mencoder $INPUT_FILE -nosound -ovc lavc $DIVX -lavcopts vpass=1:vcodec=mpeg4:mbd=2:trell:v4mv:last_pred=2:dia=-1:vmax_b_frames=2:vb_strategy=1:cmp=3:subcmp=3:precmp=0:vqcomp=0.6:turbo:vhq:threads=$CPUS:vbitrate=1100 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc lavc $DIVX -lavcopts vpass=2:vcodec=mpeg4:mbd=2:trell:v4mv:last_pred=2:dia=-1:vmax_b_frames=2:vb_strategy=1:cmp=3:subcmp=3:precmp=0:vqcomp=0.6:turbo:vhq:threads=$CPUS:vbitrate=1100 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 11 ]] ; then
	# high XVID quality (2-pass)
	# actual two-pass conversion
	mencoder $INPUT_FILE -nosound -ovc xvid -xvidencopts pass=1:vhq=1:bvhq=1:chroma_opt:quant_type=mpeg:threads=$CPUS:bitrate=-700000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc xvid -xvidencopts pass=2:vhq=2:bvhq=1:chroma_opt:quant_type=mpeg:threads=$CPUS:bitrate=-700000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 12 ]] ; then
	# high H.264 quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc x264 -x264encopts subq=5:8x8dct:frameref=2:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=-700000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 13 ]] ; then
	# high MPEG4 quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc lavc $DIVX -lavcopts vcodec=mpeg4:mbd=2:trell:v4mv:last_pred=2:dia=-1:vmax_b_frames=2:vb_strategy=1:cmp=3:subcmp=3:precmp=0:vqcomp=0.6:turbo:vhq:threads=$CPUS:vbitrate=1100 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 14 ]] ; then
	# high XVID quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc xvid -xvidencopts vhq=2:bvhq=1:chroma_opt:quant_type=mpeg:threads=$CPUS:bitrate=-700000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	###### fast quality
	if [[ $Q = 15 ]] ; then
	# fast H.264 quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc x264 -x264encopts subq=4:8x8dct:bframes=2:b_pyramid=normal:weight_b:threads=auto:bitrate=-700000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 16 ]] ; then
	# fast MPEG4 quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc lavc $DIVX -lavcopts vcodec=mpeg4:mbd=2:trell:v4mv:turbo:vhq:threads=$CPUS:vbitrate=1100 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 17 ]] ; then
	# fast XVID quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc xvid -xvidencopts turbo:vhq=0:threads=$CPUS:bitrate=-700000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	###### YouTube quality
	if [[ $Q = 18 ]] ; then
	# YouTube MPEG4 quality (1-pass)
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc lavc $DIVX -lavcopts vcodec=mpeg4:threads=$CPUS -ffourcc xvid -vf scale=320:-2,expand=:240:::1 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	###### realtime quality
	if [[ $Q = 19 ]] ; then
	# realtime MPEG4 quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc lavc $DIVX -lavcopts vcodec=mpeg4:mbd=2:turbo:vhq:threads=$CPUS:vbitrate=1100 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $Q = 20 ]] ; then
	# realtime XVID quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts abr:br=128:vol=3 -ovc xvid -xvidencopts turbo:nochroma_me:notrellis:max_bframes=0:vhq=0:threads=$CPUS:bitrate=-700000 -vf pp=de,pullup,softskip,crop=${CROP_VALUES},scale -zoom -xy 624 $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	###### low quality
	if [[ $Q = 21 ]] ; then
	# low WMV quality (1-pass)
	# actual one-pass conversion
	mencoder $INPUT_FILE -oac mp3lame -lameopts cbr:br=16:vol=3 -ovc lavc -lavcopts vcodec=wmv2:vbitrate=100 -vf scale -zoom -xy 240 $FRAME_RATE -o $OUTPUT_FILE.wmv
	fi
	####################### Custom quality
	if [[ $Q = 22 ]] ; then
	# If 22 passed, use custom quality (1-pass and 2-pass)
	####################### Custom type options
	echo -n "What type of AVI do you want to create with custom settings?:

	(1)  H.264		(2-Pass)
	(2)  H.264		(1-Pass)
	(3)  DIVX/MPEG-4	(2-Pass)
	(4)  DIVX/MPEG-4	(1-Pass)
	(5)  XVID		(2-Pass)
	(6)  XVID		(1-Pass)

	Press 'Enter' for default (default is '6')...

	"
	read MPEG4_TYPE
	###### extra blank space
	echo "
	"
	###### default ######
	if [[ -z $MPEG4_TYPE ]] ; then
	    # If no media passed, default to 6
	    MPEG4_TYPE=6
	fi
	####################### Custom Divx ffourcc menu
	###### DivX ffourcc menu
	if [[ $MPEG4_TYPE != 1 && $MPEG4_TYPE != 2 && $MPEG4_TYPE != 5 && $MPEG4_TYPE != 6 ]] ; then
	echo -n "Select the desired Divx or generic MPEG4 quality:

	(1) FFMPEG MPEG-4
	(2) DivX MPEG-4 Version 4
	(3) DivX MPEG-4 Version 5

	Press 'Enter' for default (default is '3')...

	"
	read CUSTOM_DIVX_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $CUSTOM_DIVX_NUMBER ]] ; then
	    # If no file passed, default to 3
	    CUSTOM_DIVX="-ffourcc DX50"
	fi
	###### preset
	if [[ $CUSTOM_DIVX_NUMBER = 1 ]] ; then
	    CUSTOM_DIVX=
	fi
	if [[ $CUSTOM_DIVX_NUMBER = 2 ]] ; then
	    CUSTOM_DIVX="-ffourcc DIVX"
	fi
	if [[ $CUSTOM_DIVX_NUMBER = 3 ]] ; then
	    CUSTOM_DIVX="-ffourcc DX50"
	fi
	fi
	####################### Custom scaling
	echo -n "Choose a resolution:

	(1)  original resolution(cropped, but no scaling)
	(2)  624 x 352 scaling	(fullscreen/widescreen)
	(3)  624 x ??? scaling	(fullscreen/widescreen)	(auto-height)
	(4)  800 x 600 scaling	(fullscreen)
	(5)  800 x ??? scaling	(fullscreen) 		(auto-height)
	(6)  600 x 400 scaling	(widescreen)
	(7)  600 x ??? scaling	(widescreen) 		(auto-height)
	(8)  640 x 480 scaling	(fullscreen)
	(9)  640 x ??? scaling	(fullscreen) 		(auto-height)
	(10) 704 x 294 scaling	(widescreen) (2.35:1)
	(11) 704 x ??? scaling	(widescreen) (2.35:1) 	(auto-height)
	(12) 768 x 432 scaling	(widescreen) (16:9)
	(13) 768 x ??? scaling	(widescreen) (16:9) 	(auto-height)
	(14) custom

	Press 'Enter' for default (default is '3')...

	"
	read SCALING_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $SCALING_NUMBER ]] ; then
	    # If no file passed, default to 3
	    SCALING="scale -zoom -xy 624"
	fi
	###### preset
	if [[ $SCALING_NUMBER = 1 ]] ; then
	    SCALING="scale=${CROP_VALUES}"
	fi
	if [[ $SCALING_NUMBER = 2 ]] ; then
	    SCALING="scale=624:352"
	fi
	if [[ $SCALING_NUMBER = 3 ]] ; then
	    SCALING="scale -zoom -xy 624"
	fi
	if [[ $SCALING_NUMBER = 4 ]] ; then
	    SCALING="scale=800:600"
	fi
	if [[ $SCALING_NUMBER = 5 ]] ; then
	    SCALING="scale -zoom -xy 800"
	fi
	if [[ $SCALING_NUMBER = 6 ]] ; then
	    SCALING="scale=600:400"
	fi
	if [[ $SCALING_NUMBER = 7 ]] ; then
	    SCALING="scale -zoom -xy 600"
	fi
	if [[ $SCALING_NUMBER = 8 ]] ; then
	    SCALING="scale=640:480"
	fi
	if [[ $SCALING_NUMBER = 9 ]] ; then
	    SCALING="scale -zoom -xy 640"
	fi
	if [[ $SCALING_NUMBER = 10 ]] ; then
	    SCALING="scale=704:294"
	fi
	if [[ $SCALING_NUMBER = 11 ]] ; then
	    SCALING="sscale -zoom -xy 704"
	fi
	if [[ $SCALING_NUMBER = 12 ]] ; then
	    SCALING="scale=768:432"
	fi
	if [[ $SCALING_NUMBER = 13 ]] ; then
	    SCALING="scale -zoom -xy 768"
	fi
	###### custom
	if [[ $SCALING_NUMBER = 14 ]] ; then
	    echo -n "Please enter a custom scale:  "
	    echo -n "...like this: 'scale=800:600' or 'scale -zoom -xy 624'..."
	    read CUSTOM_SCALING
	    SCALING=$CUSTOM_SCALING
	fi
	####################### Custom total/video bitrate level
	echo -n "Select a total/video bitrate level:

	(1)  -350000	(= max file size of ~ 350MB)	(H.264/XVID only)
	(2)  -700000	(= max file size of ~ 700MB)	(H.264/XVID only)
	(3)  -1000000	(= max file size of ~ 1GB)	(H.264/XVID only)
	(4)  400 kbps
	(5)  600 kbps
	(6)  800 kbps
	(7)  1000 kbps
	(8)  1100 kbps
	(9)  1150 kbps
	(10) 1200 kbps
	(11) 1250 kbps
	(12) 1500 kbps
	(13) 2000 kbps
	(14) 3000 kbps
	(15) 4000 kbps
	(16) 5000 kbps
	(17) custom

	Press 'Enter' for default (default is '2')...

	"
	read BITRATE_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $BITRATE_NUMBER ]] ; then
	    # If no file passed, default to 2
	    BITRATE=-700000
	fi
	###### preset
	if [[ $BITRATE_NUMBER = 1 ]] ; then
	    BITRATE=-350000
	fi
	if [[ $BITRATE_NUMBER = 2 ]] ; then
	    BITRATE=-700000
	fi
	if [[ $BITRATE_NUMBER = 3 ]] ; then
	    BITRATE=-1000000
	fi
	if [[ $BITRATE_NUMBER = 4 ]] ; then
	    BITRATE=400
	fi
	if [[ $BITRATE_NUMBER = 5 ]] ; then
	    BITRATE=600
	fi
	if [[ $BITRATE_NUMBER = 6 ]] ; then
	    BITRATE=800
	fi
	if [[ $BITRATE_NUMBER = 7 ]] ; then
	    BITRATE=1000
	fi
	if [[ $BITRATE_NUMBER = 8 ]] ; then
	    BITRATE=1100
	fi
	if [[ $BITRATE_NUMBER = 9 ]] ; then
	    BITRATE=1150
	fi
	if [[ $BITRATE_NUMBER = 10 ]] ; then
	    BITRATE=1200
	fi
	if [[ $BITRATE_NUMBER = 11 ]] ; then
	    BITRATE=1250
	fi
	if [[ $BITRATE_NUMBER = 12 ]] ; then
	    BITRATE=1500
	fi
	if [[ $BITRATE_NUMBER = 13 ]] ; then
	    BITRATE=2000
	fi
	if [[ $BITRATE_NUMBER = 14 ]] ; then
	    BITRATE=3000
	fi
	if [[ $BITRATE_NUMBER = 15 ]] ; then
	    BITRATE=4000
	fi
	if [[ $BITRATE_NUMBER = 16 ]] ; then
	    BITRATE=5000
	fi
	###### custom
	if [[ $BITRATE_NUMBER = 17 ]] ; then
	    echo -n "Please enter a custom total/video bitrate:  "
	    echo -n "...like this: '1175'..."
	    read CUSTOM_BITRATE
	    BITRATE=$CUSTOM_BITRATE
	fi
	####################### Custom audio track
	echo -n "Select an audio track:

	(1) -aid 0	(good when getting no audio with others) (ex.: Custom DVD rips)
	(2) -aid 127
	(3) -aid 128	(often main language non-director's commentary audio track)
	(4) -aid 129	(often second track, such as director's commentary)
	(5) -aid 130
	(6) -aid 131
	(7) -aid 132
	(8) -aid 160
	(9) custom

	Press 'Enter' for default (default is 'null', which is DVD default)...

	"
	read AUDIO_TRACK_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $AUDIO_TRACK_NUMBER ]] ; then
	    # If no file passed, default to null
	    AUDIO_TRACK=
	fi
	###### preset
	if [[ $AUDIO_TRACK_NUMBER = 1 ]] ; then
	    AUDIO_TRACK="-aid 0"
	fi
	if [[ $AUDIO_TRACK_NUMBER = 2 ]] ; then
	    AUDIO_TRACK="-aid 127"
	fi
	if [[ $AUDIO_TRACK_NUMBER = 3 ]] ; then
	    AUDIO_TRACK="-aid 128"
	fi
	if [[ $AUDIO_TRACK_NUMBER = 4 ]] ; then
	    AUDIO_TRACK="-aid 129"
	fi
	if [[ $AUDIO_TRACK_NUMBER = 5 ]] ; then
	    AUDIO_TRACK="-aid 130"
	fi
	if [[ $AUDIO_TRACK_NUMBER = 6 ]] ; then
	    AUDIO_TRACK="-aid 131"
	fi
	if [[ $AUDIO_TRACK_NUMBER = 7 ]] ; then
	    AUDIO_TRACK="-aid 132"
	fi
	if [[ $AUDIO_TRACK_NUMBER = 8 ]] ; then
	    AUDIO_TRACK="-aid 160"
	fi
	###### custom
	if [[ $AUDIO_TRACK_NUMBER = 9 ]] ; then
	    echo -n "Please enter a custom audio track:  "
	    echo -n "...like this: '-aid 128'..."
	    read CUSTOM_AUDIO_TRACK
	    AUDIO_TRACK=$CUSTOM_AUDIO_TRACK
	fi
	####################### Custom audio track language
	echo -n "Select an audio track language:

	(1)  Chinese - zh
	(2)  Dansk (Danish) - da
	(3)  Deutsch - de
	(4)  English - en
	(5)  Español - es
	(6)  Français - fr
	(7)  Greek - el
	(8)  Italiano (Italian) - it
	(9)  Japanese - ja
	(10) Korean - ko
	(11) Nederlands - nl
	(12) Polish - pl
	(13) Portugues - pt
	(14) Russian - ru

	Or input your own (like this: 'en')...

	Press 'Enter' for default (default is 'null', which is DVD default)...

	"
	read AUDIO_LANGUAGE_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $AUDIO_LANGUAGE_NUMBER ]] ; then
	    # If no file passed, default to null
	    AUDIO_LANGUAGE=
	fi
	###### preset
	if [[ $AUDIO_LANGUAGE_NUMBER = 1 ]] ; then
	    AUDIO_LANGUAGE="-alang zh"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 2 ]] ; then
	    AUDIO_LANGUAGE="-alang da"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 3 ]] ; then
	    AUDIO_LANGUAGE="-alang de"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 4 ]] ; then
	    AUDIO_LANGUAGE="-alang en"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 5 ]] ; then
	    AUDIO_LANGUAGE="-alang es"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 6 ]] ; then
	    AUDIO_LANGUAGE="-alang fr"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 7 ]] ; then
	    AUDIO_LANGUAGE="-alang el"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 8 ]] ; then
	    AUDIO_LANGUAGE="-alang it"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 9 ]] ; then
	    AUDIO_LANGUAGE="-alang ja"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 10 ]] ; then
	    AUDIO_LANGUAGE="-alang ko"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 11 ]] ; then
	    AUDIO_LANGUAGE="-alang nl"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 12 ]] ; then
	    AUDIO_LANGUAGE="-alang pl"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 13 ]] ; then
	    AUDIO_LANGUAGE="-alang pt"
	fi
	if [[ $AUDIO_LANGUAGE_NUMBER = 14 ]] ; then
	    AUDIO_LANGUAGE="-alang ru"
	fi
	####################### Custom audio bitrate level
	echo -n "Select an audio bitrate level:

	(1) 48 kbps
	(2) 64 kbps
	(3) 128 kbps
	(4) 160 kbps
	(5) 192 kbps
	(6) 224 kbps
	(7) 256 kbps
	(8) 320 kbps
	(9) custom

	Press 'Enter' for default (default is '3')...

	"
	read AUDIO_BITRATE_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $AUDIO_BITRATE_NUMBER ]] ; then
	    # If no file passed, default to 3
	    AUDIO_BITRATE=128
	fi
	###### preset
	if [[ $AUDIO_BITRATE_NUMBER = 1 ]] ; then
	    AUDIO_BITRATE=48
	fi
	if [[ $AUDIO_BITRATE_NUMBER = 2 ]] ; then
	    AUDIO_BITRATE=96
	fi
	if [[ $AUDIO_BITRATE_NUMBER = 3 ]] ; then
	    AUDIO_BITRATE=128
	fi
	if [[ $AUDIO_BITRATE_NUMBER = 4 ]] ; then
	    AUDIO_BITRATE=160
	fi
	if [[ $AUDIO_BITRATE_NUMBER = 5 ]] ; then
	    AUDIO_BITRATE=192
	fi
	if [[ $AUDIO_BITRATE_NUMBER = 6 ]] ; then
	    AUDIO_BITRATE=224
	fi
	if [[ $AUDIO_BITRATE_NUMBER = 7 ]] ; then
	    AUDIO_BITRATE=256
	fi
	if [[ $AUDIO_BITRATE_NUMBER = 8 ]] ; then
	    AUDIO_BITRATE=320
	fi
	###### custom
	if [[ $AUDIO_BITRATE_NUMBER = 9 ]] ; then
	    echo -n "Please enter a custom audio bitrate level:  "
	    echo -n "...like this: '100'..."
	    read CUSTOM_AUDIO_BITRATE
	    AUDIO_BITRATE=$CUSTOM_AUDIO_BITRATE
	fi
	####################### Custom audio bitrate type
	echo -n "Select an audio bitrate type:

	(1) Average Bitrate
	(2) Constant Bitrate
	(3) Variable Bitrate

	Press 'Enter' for default (default is '1')...

	"
	read AUDIO_BITRATE_TYPE_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $AUDIO_BITRATE_TYPE_NUMBER ]] ; then
	    # If no file passed, default to abr
	    AUDIO_BITRATE_TYPE=abr
	fi
	###### preset
	if [[ $AUDIO_BITRATE_TYPE_NUMBER = 1 ]] ; then
	    AUDIO_BITRATE_TYPE=abr
	fi
	if [[ $AUDIO_BITRATE_TYPE_NUMBER = 2 ]] ; then
	    AUDIO_BITRATE_TYPE=cbr
	fi
	if [[ $AUDIO_BITRATE_TYPE_NUMBER = 3 ]] ; then
	    AUDIO_BITRATE_TYPE=vbr
	fi
	####################### Custom audio volume level
	echo -n "Select an audio volume increase level (1-10):

	Press 'Enter' for default (default is '3')...

	"
	read AUDIO_VOLUME_LEVEL
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $AUDIO_VOLUME_LEVEL ]] ; then
	    # If no file passed, default to 3
	    AUDIO_VOLUME_LEVEL=3
	fi
	####################### Subtitles?
	echo -n "Do you want subtitles?:

	(1) No
	(2) Yes (DVD/ISO only)

	Press 'Enter' for default (default is '1', for no subtitles)...

	"
	read SUBTITLE_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $SUBTITLE_NUMBER ]] ; then
	    # If no file passed, default to null
	    SUBTITLE_TRACK=
	    SUBTITLE_LANGUAGE=
	    SUBTITLE_TYPE=
	fi
	###### preset
	if [[ $SUBTITLE_NUMBER = 1 ]] ; then
	    SUBTITLE_TRACK=
	    SUBTITLE_LANGUAGE=
	    SUBTITLE_TYPE=
	fi
	if [[ $SUBTITLE_NUMBER = 2 ]] ; then
	####################### Custom subtitle track
	echo -n "Select a subtitle track:

	(1) -sid 0
	(2) -sid 1
	(3) -sid 2
	(4) -sid 3
	(5) -sid 4
	(6) -sid 5
	(7) -sid 6
	(8) -sid 7
	(9) custom

	Press 'Enter' for default (default is 'null')...

	"
	read SUBTITLE_TRACK_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $SUBTITLE_TRACK_NUMBER ]] ; then
	    # If no file passed, default to null
	    SUBTITLE_TRACK=
	fi
	###### preset
	if [[ $SUBTITLE_TRACK_NUMBER = 1 ]] ; then
	    SUBTITLE_TRACK="-sid 0"
	fi
	if [[ $SUBTITLE_TRACK_NUMBER = 2 ]] ; then
	    SUBTITLE_TRACK="-sid 1"
	fi
	if [[ $SUBTITLE_TRACK_NUMBER = 3 ]] ; then
	    SUBTITLE_TRACK="-sid 2"
	fi
	if [[ $SUBTITLE_TRACK_NUMBER = 4 ]] ; then
	    SUBTITLE_TRACK="-sid 3"
	fi
	if [[ $SUBTITLE_TRACK_NUMBER = 5 ]] ; then
	    SUBTITLE_TRACK="-sid 4"
	fi
	if [[ $SUBTITLE_TRACK_NUMBER = 6 ]] ; then
	    SUBTITLE_TRACK="-sid 5"
	fi
	if [[ $SUBTITLE_TRACK_NUMBER = 7 ]] ; then
	    SUBTITLE_TRACK="-sid 6"
	fi
	if [[ $SUBTITLE_TRACK_NUMBER = 8 ]] ; then
	    SUBTITLE_TRACK="-sid 7"
	fi
	###### custom
	if [[ $SUBTITLE_TRACK_NUMBER = 9 ]] ; then
	    echo -n "Please enter a custom subtitles track:  "
	    echo -n "...like this: '-sid 10'..."
	    read CUSTOM_SUBTITLE_TRACK
	    SUBTITLE_TRACK=$CUSTOM_SUBTITLE_TRACK
	fi
	####################### Custom subtitles track language
	echo -n "Select a subtitles track language:

	(1)  Chinese - zh
	(2)  Dansk (Danish) - da
	(3)  Deutsch - de
	(4)  English - en
	(5)  Español - es
	(6)  Français - fr
	(7)  Greek - el
	(8)  Italiano (Italian) - it
	(9)  Japanese - ja
	(10) Korean - ko
	(11) Nederlands - nl
	(12) Polish - pl
	(13) Portugues - pt
	(14) Russian - ru

	Or input your own (like this: 'en')...

	Press 'Enter' for default (default is 'null')...

	"
	read SUBTITLE_LANGUAGE_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $SUBTITLE_LANGUAGE_NUMBER ]] ; then
	    # If no file passed, default to null
	    SUBTITLE_LANGUAGE=
	fi
	###### preset
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 1 ]] ; then
	    SUBTITLE_LANGUAGE="-slang zh"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 2 ]] ; then
	    SUBTITLE_LANGUAGE="-slang da"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 3 ]] ; then
	    SUBTITLE_LANGUAGE="-slang de"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 4 ]] ; then
	    SUBTITLE_LANGUAGE="-slang en"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 5 ]] ; then
	    SUBTITLE_LANGUAGE="-slang es"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 6 ]] ; then
	    SUBTITLE_LANGUAGE="-slang fr"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 7 ]] ; then
	    SUBTITLE_LANGUAGE="-slang el"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 8 ]] ; then
	    SUBTITLE_LANGUAGE="-slang it"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 9 ]] ; then
	    SUBTITLE_LANGUAGE="-slang ja"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 10 ]] ; then
	    SUBTITLE_LANGUAGE="-slang ko"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 11 ]] ; then
	    SUBTITLE_LANGUAGE="-slang nl"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 12 ]] ; then
	    SUBTITLE_LANGUAGE="-slang pl"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 13 ]] ; then
	    SUBTITLE_LANGUAGE="-slang pt"
	fi
	if [[ $SUBTITLE_LANGUAGE_NUMBER = 14 ]] ; then
	    SUBTITLE_LANGUAGE="-slang ru"
	fi
	####################### Subtitle Kind?
	echo -n "What kind of subtitles do you prefer?:

	(1)  Embed onto the video
	(2)  Embed into a separate file

	Press 'Enter' for default (default is '1')...

	"
	read SUBTITLE_TYPE_NUMBER
	###### extra blank space
	echo "
	"
	###### default
	if [[ -z $SUBTITLE_TYPE_NUMBER ]] ; then
	    # If no file passed, default to null
	    SUBTITLE_TYPE=
	fi
	###### preset
	if [[ $SUBTITLE_TYPE_NUMBER = 1 ]] ; then
	    SUBTITLE_TYPE=
	fi
	if [[ $SUBTITLE_TYPE_NUMBER = 2 ]] ; then
	    SUBTITLE_TYPE="-vobsubout ${OUTPUT_FILE}"
	fi
	###### closes the preset of 'yes' for subtitles
	fi
	####################### Custom conversion is starting
	###### extra blank space
	echo "
	"
	###### custom conversion is starting message
	read -sn 1 -p "Your custom conversion is about to begin, press any key to continue..."
	####################### Custom conversions (very high quality settings)
	###### custom preset ######
	###### H.264
	if [[ $MPEG4_TYPE = 1 ]] ; then
	# actual two-pass conversion
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -nosound -ovc x264 -x264encopts pass=1:subq=1:partitions=all:8x8dct:me=umh:frameref=1:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=$BITRATE -vf pp=de,pullup,softskip,harddup,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -oac mp3lame -lameopts $AUDIO_BITRATE_TYPE:br=$AUDIO_BITRATE:vol=$AUDIO_VOLUME_LEVEL -ovc x264 -x264encopts pass=2:subq=6:partitions=all:8x8dct:me=umh:frameref=5:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=$BITRATE -vf pp=de,pullup,softskip,harddup,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $MPEG4_TYPE = 2 ]] ; then
	# actual one-pass conversion
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -oac mp3lame -lameopts $AUDIO_BITRATE_TYPE:br=$AUDIO_BITRATE:vol=$AUDIO_VOLUME_LEVEL -ovc x264 -x264encopts subq=6:partitions=all:8x8dct:me=umh:frameref=5:bframes=3:b_pyramid=normal:weight_b:threads=auto:bitrate=$BITRATE -vf pp=de,pullup,softskip,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	###### MPEG4
	if [[ $MPEG4_TYPE = 3 ]] ; then
	# actual two-pass conversion
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -nosound -ovc lavc $CUSTOM_DIVX -lavcopts vpass=1:vcodec=mpeg4:mbd=2:trell:v4mv:last_pred=2:dia=-1:vmax_b_frames=2:vb_strategy=1:cmp=3:subcmp=3:precmp=0:vqcomp=0.6:turbo:threads=$CPUS:vbitrate=$BITRATE -vf pp=de,pullup,softskip,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -oac mp3lame -lameopts $AUDIO_BITRATE_TYPE:br=$AUDIO_BITRATE:vol=$AUDIO_VOLUME_LEVEL -ovc lavc $CUSTOM_DIVX -lavcopts vpass=2:vcodec=mpeg4:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:predia=2:dia=2:vmax_b_frames=2:vb_strategy=1:precmp=2:cmp=2:subcmp=2:preme=2:qns=2:threads=$CPUS:vbitrate=$BITRATE -vf pp=de,pullup,softskip,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $MPEG4_TYPE = 4 ]] ; then
	# actual one-pass conversion
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -oac mp3lame -lameopts $AUDIO_BITRATE_TYPE:br=$AUDIO_BITRATE:vol=$AUDIO_VOLUME_LEVEL -ovc lavc $CUSTOM_DIVX -lavcopts vcodec=mpeg4:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:predia=2:dia=2:vmax_b_frames=2:vb_strategy=1:precmp=2:cmp=2:subcmp=2:preme=2:qns=2:threads=$CPUS:vbitrate=$BITRATE -vf pp=de,pullup,softskip,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	###### XVID
	if [[ $MPEG4_TYPE = 5 ]] ; then
	# actual two-pass conversion
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -nosound -ovc xvid -xvidencopts pass=1:chroma_opt:vhq=1:bvhq=1:quant_type=mpeg:threads=$CPUS:bitrate=$BITRATE -vf pp=de,pullup,softskip,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o '/dev/null'
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -oac mp3lame -lameopts $AUDIO_BITRATE_TYPE:br=$AUDIO_BITRATE:vol=$AUDIO_VOLUME_LEVEL -ovc xvid -xvidencopts pass=2:chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:threads=$CPUS:bitrate=$BITRATE -vf pp=de,pullup,softskip,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	if [[ $MPEG4_TYPE = 6 ]] ; then
	# actual one-pass conversion
	mencoder $INPUT_FILE $AUDIO_TRACK $AUDIO_LANGUAGE $SUBTITLE_TRACK $SUBTITLE_LANGUAGE $SUBTITLE_TYPE -oac mp3lame -lameopts $AUDIO_BITRATE_TYPE:br=$AUDIO_BITRATE:vol=$AUDIO_VOLUME_LEVEL -ovc xvid -xvidencopts chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:threads=$CPUS:bitrate=$BITRATE -vf pp=de,pullup,softskip,crop=${CROP_VALUES},$SCALING $FRAME_RATE -o $OUTPUT_FILE.avi
	fi
	####################### Close the custom quality option #17
	fi
	####################### Cleanup
	if [ -f mplayer.tmp ];then
	    rm mplayer.tmp
	fi
	if [ -f divx2pass.log ];then
	    rm divx2pass.log
	fi
	####################### Conversion finished notifications
	###### extra blank spaces
	echo "
	"
	###### notifications
	notify-send -t 7000 -i /usr/share/icons/gnome/32x32/status/info.png "Conversion Finished" ; espeak "Conversion Finished"
	# extra blank spaces
	echo "
	"
	read -sn 1 -p "Your conversion has finished, press any key to continue and close this terminal session..."
}
alias dvdrip='video2avi'
alias rip='video2avi'

###### video2dvd
function video2dvd()
{
	# video2dvd - Make a DVD ISO from a video file
	#           Burn ISO after script runs
	#
	# Author  - Inameiname
	#
	# Version:	1.0
	#
	# Usage   - video2dvd $1
	#           Run this script either from the terminal or by right clicking the video file and selecting the script
	# Ensure 'export VIDEO_FORMAT=NTSC' is in '~/.bashrc' or '~/.bash.profile' OR that its below
	##########
	# See if the Nautilus environment variable is empty
	if [ -z $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ]; then
	    # If it's blank, set it equal to $1
	    NAUTILUS_SCRIPT_SELECTED_FILE_PATHS=$1
	fi
	# Loop through the list (from either Nautilus or the command line)
	for ARCHIVE_FULLPATH in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
	    NEWDIRNAME=${ARCHIVE_FULLPATH%.*}
	    FILENAME=${ARCHIVE_FULLPATH##*/}
	    NAME=${ARCHIVE_FULLPATH##*/.*}
	    ###### open and run all of the following in a terminal window
	    tty -s; if [ $? -ne 0 ]; then gnome-terminal -e "$0"; exit; fi
	    ###### be sure there is a "VIDEO_FORMAT=" specified
	    export VIDEO_FORMAT=NTSC
	    ###### cd to the video file's folder
	    mkdir "$NEWDIRNAME"
	    cd "$NEWDIRNAME"
	    cd ..
	    rmdir "$NEWDIRNAME"
	    ###### check to see if the file is an mpg/vob file; if not, convert it and rename the mpeg file to "dvd_movie.mpg"
	    echo 'Is this video file not already a DVD-compliant MPEG file (MPEG/mpeg/MPG/mpg/VOB/vob), 1 for true 0 for false? '
	    read MEDIA_TYPE
	    if [ "$MEDIA_TYPE" -eq 1 ] ; then
		   ###### convert the video file to '.mpg'
		   ffmpeg -i "$ARCHIVE_FULLPATH" -target ntsc-dvd -acodec mp2 -ab 224 -sameq "$NEWDIRNAME".mpg
		   notify-send -t 5000 -i /usr/share/icons/gnome/32x32/status/info.png "Conversion to an MPEG File Finished"
		   ###### rename the '.mpg' file to "dvd_movie.mpg"
		   mv -fv "$NEWDIRNAME".mpg "dvd_movie.mpg"
	    else
		   ###### rename the mpg/mpeg/vob file to "dvd_movie.mpg"
		   mv -fv "$ARCHIVE_FULLPATH" "dvd_movie.mpg"
	    fi
	    ###### create a "dvdauthor.xml" file - (save in the same directory as movie file)
    cat > "dvdauthor.xml" <<"End-of-message"
    <dvdauthor dest="DVD">
      <vmgm />
       <titleset>
         <titles>
           <pgc>
             <vob file="dvd_movie.mpg" chapters="0,05:00,10:00,15:00,20:00,25:00,30:00,35:00,40:00,45:00,50:00,55:00,1:00:00,1:05:00,1:10:00,1:15:00,1:20:00,1:25:00,1:30:00,1:35:00,1:40:00,1:45:00,1:50:00,1:55:00,2:00:00,2:05:00,2:10:00,2:15:00,2:20:00,2:25:00,2:30:00,2:35:00,2:40:00,2:45:00,2:50:00,2:55:00,3:00:00,3:05:00,3:10:00,3:15:00,3:20:00,3:25:00,3:30:00,3:35:00,3:40:00,3:45:00,3:50:00,3:55:00,4:00:00,4:05:00,4:10:00,4:15:00,4:20:00,4:25:00,4:30:00,4:35:00,4:40:00,4:45:00,4:50:00,4:55:00,5:00:00,5:05:00,5:10:00,5:15:00,5:20:00,5:25:00,5:30:00,5:35:00,5:40:00,5:45:00,5:50:00,5:55:00,6:00:00"/>
           </pgc>
          </titles>
       </titleset>
     </dvdauthor>
End-of-message
	    ###### the actual mpg/mpeg/vob conversion to dvd-compliant folders
	    dvdauthor -x dvdauthor.xml
	    ###### rename the mpg/mpeg/vob file from "dvd_movie.mpg" back to the original
	    if [ "$MEDIA_TYPE" -eq 1 ] ; then
		   ###### rename the '.mpg' file to "dvd_movie.mpg"
		   mv -fv "dvd_movie.mpg" "$NEWDIRNAME".mpg
	    else
		   ###### rename the mpg/mpeg/vob file to "dvd_movie.mpg"
		   mv -fv "dvd_movie.mpg" "$ARCHIVE_FULLPATH"
	    fi
	    ###### rename the 'DVD' file to same name as the original
	    mv -fv "DVD" "$NEWDIRNAME"
	    ###### remove the "dvdauthor.xml" file created and used from this script
	    rm -fv -R dvdauthor.xml
	    ###### convert the dvd-compliant folders to an ISO
	    echo 'Would you like to create an ISO from the DVD-complaint folders now, 1 for true 0 for false? '
	    read boole
	    if [ $boole -eq 1 ]; then
		   cd "$NEWDIRNAME"
		   mkisofs -v -dvd-video -o "$NEWDIRNAME.iso" .
		   cd ..
		   notify-send -t 2000 -i /usr/share/icons/gnome/32x32/status/info.png "ISO created"
	    else
		   notify-send -t 2000 -i /usr/share/icons/gnome/32x32/status/info.png "no ISO created"
	    fi
	    ###### option to burn the ISO
	    echo 'Would you like to burn this disc now, 1 for true 0 for false? '
	    read boole1
	    if [ $boole1 -eq 1 ]; then
		   # to get desired device
		   df -h -x tmpfs -x usbfs
		   echo -n "Please enter the appropriate DVD drive:

		   (1) /dev/dvd
		   (2) /dev/sr0
		   (3) /dev/sr1
		   (4) /dev/sr2
		   (5) custom

		   Press 'Enter' for default (default is '1')...

		   "
		   read DEVICE_NUMBER
		   # extra blank space
		   echo "
		   "
		   # default
		   if [[ -z $DEVICE_NUMBER ]] ; then
		   # If no device passed, default to /dev/dvd
			  DEVICE=/dev/dvd
		   fi
		   # preset
		   if [[ $DEVICE_NUMBER = 1 ]] ; then
			  DEVICE=/dev/dvd
		   fi
		   if [[ $DEVICE_NUMBER = 2 ]] ; then
			  DEVICE=/dev/sr0
		   fi
		   if [[ $DEVICE_NUMBER = 3 ]] ; then
			  DEVICE=/dev/sr1
		   fi
		   if [[ $DEVICE_NUMBER = 4 ]] ; then
			  DEVICE=/dev/sr2
		   fi
		   # custom
		   if [[ $DEVICE_NUMBER = 5 ]] ; then
			  echo -n "Please enter the appropriate DVD drive:  "
			  echo -n "...like this: '/dev/dvd'..."
			  read CUSTOM_DEVICE
			  DEVICE=$CUSTOM_DEVICE
		   fi
		   growisofs -dvd-compat -speed=1 -Z "$DEVICE"="$NEWDIRNAME"
		   notify-send -t 2000 -i /usr/share/icons/gnome/32x32/status/info.png "DVD burned"
	    else
		   notify-send -t 2000 -i /usr/share/icons/gnome/32x32/status/info.png "no DVD burned"
	    fi
	    ###### notify-send notification showing when the job has finished
	    notify-send -t 5000 -i /usr/share/icons/gnome/32x32/status/info.png "All Conversions Finished"
	done
}

############ Audio ############

###### rip audio from video ("$1" for output file & "$2" for input file)
function audioextract()
{
	mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile "$1" "$2"
}

###### flac2mp3 - call this like: flac2mp3 /path/to/source/file.flac /path/to/destination - needs: getFileName function; flac encoder/decoder; lame
function flac2mp3() 
{
   local old_file="${1}"
   local new_dir="${2}"
   local short_filename=`getFileName "${old_file}"`
   local new_file="${short_filename:0:${#short_filename}-5}.mp3"

   flac -d -o - "${old_file}" | lame -b 320 -h - > "${new_dir}/${new_file}"
}

###### flac2ogg - call this like: flac2ogg /path/to/source/file.flac /path/to/destination needs: getFileName function; flac encoder/decoder; oggenc
function flac2ogg()
{
   local old_file="${1}"
   local new_dir="${2}"
   local short_filename=`getFileName "${old_file}"`
   local new_file="${short_filename:0:${#short_filename}-5}.ogg"
   ###### get artist and album before release #########
   # flac -d -o - "${old_file}" | oggenc -a "$artist" -l "$album" -t "${title}" - -o "${new_dir}/${new_file}"
   #------------------------------------------////##
   local title="${short_filename:0:${#short_filename}-4}"

   flac -d -o - "${old_file}" | oggenc -t "${title}" - -o "${new_dir}/${new_file}"
}
alias flvaudio='ffmpeg -i "$1" -f mp3 -vn -acodec copy output.mp3'			# extract sound from flv & make mp3

###### fix MP3 tags encoding (to UTF-8) - batch fixes all MP3s in one directory
function mp3_tagging()
{
	find . -iname "*.mp3" -execdir mid3iconv -e <encoding> {} \;
}

###### ogg2mp3 - call this like: ogg2mp3 /path/to/source/file.flac /path/to/destination - needs: getFileName function; oggdec; lame
function ogg2mp3()
{
   local old_file="${1}"
   local new_dir="${2}"
   local short_filename=`getFileName "${old_file}"`
   local new_file="${short_filename:0:${#short_filename}-4}.mp3"
   local info_string=`get_ogg_info "$old_file"`
   local cartist=`cut -d| -f1 ${info_string}`
   local ctitle=`cut -d| -f2 ${info_string}`
   local calbum=`cut -d| -f3 ${info_string}`
   local cgenre=`cut -d| -f4 ${info_string}`
   local cdate=`cut -d| -f5 ${info_string}`
   local ctracknumber=`cut -d| -f6 ${info_string}`

   oggdec "${old_file}" -o - | lame  -b 320 --tt "$ctitle" --ta "$cartist" --tl "$calbum" --ty $cdate --tn $ctracknumber --tg "$cgenre" -h - > "${new_dir}/${new_file}"
   sleep .5
}

###### ogg_info - call this like: - ogg_info_string=`get_ogg_info "/path/to/file.ogg"` - ofcourse the string would have to be parsed - it is pipe | delimited - in order artist, title, album, genre, date, and track number - inStr function needed; vorbiscomment (comes with oggenc)
function ogg_info()
{
   local turn=""
   local index=0
   local item=""
   local cartist=""
   local ctitle=""
   local calbum=""
   local cgenre=""
   local cdate=""
   local ctracknumber=""

   vorbiscomment -l "$1" > info.lst
   for turn in artist title album genre date tracknumber
   do
      tmp_comment=`grep -i "$turn" info.lst`
      item=`inStr "=" "$tmp_comment"`
      comment=${tmp_comment:${item}+1}
      ((index++))
      case $index in
      1)   cartist="$comment";
         ;;
      2)   ctitle="$comment";
         ;;
      3)   calbum="$comment";
         ;;
      4)   cgenre="$comment";
         ;;
      5)   cdate="$comment";
         ;;
      6)   ctracknumber="$comment";
         ;;
      esac
   done
   info="${cartist}|${ctitle}|${calbum}|${cgenre}|${cdate}|${ctracknumber}"
   echo "${info}"
   rm -f info.lst
}

alias wma2mp3='for f in *.wma; do ffmpeg -i "$f" -ab 128k "${f%.wma}.mp3" -ab 128K; done'		
# convert wma to mp3@128k

alias wma2ogg='for f in *.wma; do ffmpeg -i "$f" -ab 128k "${f%.wma}.ogg" -ab 128K; done'		
# convert wma to ogg@128

alias wma2wav='for i in *.wma; do mplayer -vo null -vc dummy -af resample=44100 -ao pcm:waveheader:file="${i%.wma}.wav" "$i" ; done'	
# convert wma to wav

###### record audio and use sox to eliminate silence outputs an ogg file that only contains the audio signal exceeding -45dB - useful for recording radio scanner
function audiorecord-45dB()
{
	rec -r 44100 -p | sox -p "audio_name-$(date '+%Y-%m-%d').ogg" silence -l 1 00:00:00.5 -45d -1 00:00:00.5 -45d
}

####### Download AUR package using best guess at filename
function aurget() {
  local DIR=$HOME/Packages
  cd $DIR && wget http://aur.archlinux.org/packages/${1}/${1}.tar.gz
  ls -l
}

###### shows a gui color chart
# function color-picker()
# 	{
# 	# for GNOME3 only
# 	# sudo apt-get install python-webkit
# 	# also requires: "~/.gnome2/nemo-scripts/.colorchart/view.html"
# 	echo "When you are finished, press "Control C" to continue..."
# 	cat > "/tmp/color-picker.py" <<"End-of-message"
# 	#!/usr/bin/python
# 	import os
# 	import pygtk
# 	pygtk.require('2.0')
# 	import gtk
# 	import webkit
# 	homedir = os.path.expanduser('~')
# 	try:
#  	   from win32com.shell import shellcon, shell
#  	   homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
# 	except ImportError:
# 	    homedir = os.path.expanduser("~/.gnome2/nemo-scripts/.colorchart/view.html")
# 	class ColorChart:
#	 	def __init__(self):
# 	                self.moz = webkit.WebView()
# 			box = gtk.VBox(False,0)
# 			win = gtk.Window()
# 			win.add(box)
# 			hbox = gtk.HBox(False,0)
#  	                box.pack_start(hbox,False,False)
# 	                hbox.show()
# 			box.pack_start(self.moz,True,True,0)
# 	                self.moz.show()
# 			self.moz.open(homedir)
# 	                self.moz.set_size_request(650,550)
# 			title=self.moz.get_title()
# 			win.set_title("RGB/HEX Color Picker")
# 			win.show_all()
# 	if __name__ == "__main__":
# 		ColorChart()
# 		gtk.main()
# 	End-of-message
# 	chmod +x "/tmp/color-picker-.py"
# 	/usr/bin/python "/tmp/color-picker.py"
# 	/bin/rm "/tmp/color-picker.py"
# }

###### creates an authentic and correct debian file / uploads to a Launchpad PPA for debian file creation
# function debmaker()
# {
# function searchnreplace_()
# {
# # Store old text and new text in variables
# old=$1;
# new=$2;
# # Shift positional parameters to places to left (get rid of old and
# # new from command line)
# shift;
# shift;
# # Store list of files as a variable
# files=$@;
# a='';
# for a in $files
#  do
#   temp=$(echo "/tmp/$LOGNAME-$a");
# # echo "$temp";
#   echo -n ".";
#   sed -e "s/$old/$new/g" $a > $temp;
#   mv $temp $a;
#  done
# echo;
# echo -e "Searched $# files for '$old' and replaced with '$new'";
# }
# sudo apt-get install devscripts dh-make dput
# echo -n "Please enter the full path to Public keys (spaces are fine)...
#
# Example: '/home/(your username)/Public_Key-public.key'...
#
# "
# read MYKEYS_PUBLIC_LOCATION
# gpg --import "$MYKEYS_PUBLIC_LOCATION"
# echo -n "Please enter the full path to Private keys (spaces are fine)...
#
# Example: '/home/(your username)/Private_Keys-private.key'...
#
# "
# read MYKEYS_PRIVATE_LOCATION
# gpg --import "$MYKEYS_PRIVATE_LOCATION"
# echo -n "All done."
# echo -n "Please enter the name of the package:
# "
# read PACKAGE_NAME
# echo -n "Please enter your name as it is on Launchpad:
# "
# read YOUR_NAME
# echo -n "Please enter your email address as it is on Launchpad:
# "
# read YOUR_EMAILADDRESS
# dh_make -n -s -e $YOUR_EMAILADDRESS
# cd debian
# searchnreplace_ ""$USER" <"$YOUR_EMAILADDRESS">" ""YOUR_PPA_USERNAME" <"$YOUR_EMAILADDRESS">" *
# searchnreplace_ "unstable; urgency=low" "saucy; urgency=low" *
# echo '#!/usr/bin/make -f' >> $PACKAGE_NAME.install
# echo ''
# echo '# add more lines like below when necessary' >> $PACKAGE_NAME.install
# echo '<put_whatever_directory(s)_here>/ /' >> $PACKAGE_NAME.install
# sudo chmod +x $PACKAGE_NAME.install
# gedit control changelog $PACKAGE_NAME.install
# cd ..
# read -sn 1 -p "If you are ready to build the package, press any key to continue...
# "
# echo -n "What do you want to compile the original source to?:
#
# (1) a debian binary for personal use / check to see if the building works
# (2) a new source for potential Launchpad PPA upload
# (3) a debian binary for checking AND a new source for potential Launchpad PPA upload
#
# Press 'Enter' for default (default is '3')...
#
# "
# read OPTION_NUMBER
# # extra blank space
# echo "
# "
# # default
# if [[ -z $OPTION_NUMBER ]] ; then
# # If no device passed, default to "3"
#   debuild -b
#   read -sn 1 -p "Built deb is done; if it looks good, and you feel its good enough to make the source for a PPA upload, press any key to continue...
# "
#   debuild -S
#   cd ..
#   mkdir Debian-Package
#     mv -fv *_all.* Debian-Package
#     mv -fv *_amd64.* Debian-Package
#     mv -fv *_i386.* Debian-Package
#   read -sn 1 -p "If you are ready to upload the built package to Launchpad, press any key to continue...
# "
#   echo -n "Please enter the name of your Launchpad PPA that you would like to upload the package to:
#
#   ...like this...('ppa:myppa/oneiric')...
# "
#   read PPA_NAME
#   dput $PPA_NAME *.changes
# fi
# # preset
# if [[ $OPTION_NUMBER = 1 ]] ; then
#     debuild -b
# fi
# if [[ $OPTION_NUMBER = 2 ]] ; then
#   debuild -S
#   cd ..
#   read -sn 1 -p "If you are ready to upload the built package to Launchpad, press any key to continue...
# "
#   echo -n "Please enter the name of your Launchpad PPA that you would like to upload the package to:
#
#   ...like this...('ppa:myppa/oneiric')...
# "
#   read PPA_NAME
#   dput $PPA_NAME *.changes
# fi
# if [[ $OPTION_NUMBER = 3 ]] ; then
#   debuild -b
#   read -sn 1 -p "Built deb is done; if it looks good, and you feel its good enough to make the source for a PPA upload, press any key to continue...
# "
#   debuild -S
#   cd ..
#   mkdir Debian-Package
#     mv -fv *_all.* Debian-Package
#     mv -fv *_amd64.* Debian-Package
#     mv -fv *_i386.* Debian-Package
#   read -sn 1 -p "If you are ready to upload the built package to Launchpad, press any key to continue...
# "
#   echo -n "Please enter the name of your Launchpad PPA that you would like to upload the package to:
#
#   ...like this...('ppa:myppa/oneiric')...
# "
#   read PPA_NAME
#   dput $PPA_NAME *.changes
# fi
# }

####### Pseudo namespaces in bash
#------------------------------------------////

## copyright: 2009, Poor Yorick
## author url:  http://www.pooryorick.com
## license: http://www.ynform.org/w/Pub/OpenSourceSharewareLicense
## to "import" functions and assign them to pseudo namespaces using prefixes
## caveat: works well for functions, but there is still only one global namespace -- no script-level namespace like Python's
# function shimport() {
#	local magic part prefix script script2 t tvar var vartype
#	magic=__shimport__
#	script='
#	{ @1 ; } >&2
#	@script2
#	'
#	script="${script//@1/$(< /dev/stdin)}"
#	script=$(printf '%s\n%s' "$script" "declare -p $magic")
#	prefix="$1"
#	shift
#	script2=''
#	while test ${#@} -gt 0; do
#		var=${1%%=*}
#		vartype=${1#*=}
#		case "$vartype" in
#			f*)
#				t=-f
#				;;
#			v*)
#				t=-p
#				;;
#			*)
#				echo "$vartype" is an invalid type specifier for "$var"!
#				return 1
#				;;
#		esac
#		read -d '' part <<-'EOF'
#			@magic=$(declare @t @var)
#			@magic=${@magic/@var/@prefix@var}
#			printf '%s\\n' "$@magic"
#		EOF
#		for tvar in magic t var prefix; do
#			part=${part//@$tvar/${!tvar}}
#		done
#		script2="$(printf '%s\n%s\n' "$script2" "$part")"
#		shift
#	done
#	printf '%s\n' "$(bash -c "${script//@script2/$script2}")"
# }
# shimport_test1=$(cat <<-'EOG'
#	eval "$(shimport mod1_ var1=v var2=v func1=f <<-'EOF'
#		echo welcome to the inner script!
#		var1=( one two "forty three" )
#		var2=val2
#		function func1() {
#			echo welcome to func1!
#		}
#		EOF
#	)"
#	mod1_func1
#	printf 'mod1_var1: %s\n' "${mod1_var1[@]}"
# EOG
# )
# eval "$shimport_test1"
#    }}}

# Sudo stuff
#------------------------------------------////

###### Apt-get via sudo
# An apt-get wrapper function which will run the command via sudo, but will run it normally if you're only downloading source files.
# function apt-get() { [ "$1" = source ] && (command apt-get "$@";true) || sudo apt-get "$@" }

# function sudo()
# {
#   command="$@"
#   if [ -z "$command" ]; then
#     command sudo -s
#   else
#      command sudo "$@"
#   fi
# }

###### Wrap sudo to handle aliases and functions
# (enabled means all 'sudo' in this file need
# to be removed) (disabled for now by adding
# a single '#')
# function sudo()
# {
# local c o t parse
## Parse sudo args
# OPTIND=1
# while getopts xVhlLvkKsHPSb:p:c:a:u: t; do
# if [ "$t" = x ]; then
# parse=true
# else
# o="$o -$t"
# [ "$OPTARG" ] && o="$o $OPTARG"
# fi
# done
# shift $(( $OPTIND - 1 ))
## If no arguments are left, it's a simple call to sudo
# if [ $#  -ge 1 ]; then
# c="$1";
# shift;
# case $(type -t "$c") in
# "")
# echo No such command "$c"
# return 127
# ;;
# alias)
# c="$(type "$c"|sed "s/^.* to \`//;s/.$//")"
# ;;
# function)
# c=$(type "$c"|sed 1d)";\"$c\""
# ;;
# *)
# c="\"$c\""
# ;;
# esac
# if [ -n "$parse" ]; then
## Quote the rest once, so it gets processed by bash.
## Done this way so variables can get expanded.
# while [ -n "$1" ]; do
# c="$c \"$1\""
# shift
# done
# else
## Otherwise, quote the arguments. The echo gets an extra
## space to prevent echo from parsing arguments like -n
## Note the lovely interactions between " and ' ;-)
# while [ -n "$1" ]; do
# c="$c '$(echo " $1"|sed -e "s/^ //" -e "s/'/'\"'\"'/")'"
# shift
# done
# fi
## Run the command with verbose options
## echo Executing sudo $o -- bash -x -v -c "$c" >&2
# command sudo $o bash -xvc "$c"
# else
## echo sudo $o >&2
# command sudo $o
# fi
# }

###### Sudo for entire line (including pipes and redirects)
# USAGE: $ sudor your command
# This command uses a dirty hack with history, so be sure you not turned it off.
# WARNING!: This command behavior differ from other commands. It more like text macro, so you shouldn't use it in subshells, non-interactive sessions, other # functions/aliases and so on. You shouldn't pipe into sudor (any string that prefixes sudor will be removed), but if you really want, use this commands:
# function proceed_sudo() { sudor_command="`HISTTIMEFORMAT=\"\" history 1 | sed -r -e 's/^.*?sudor//' -e 's/\"/\\\"/g'`" ; sudo sh -c "$sudor_command"; }; alias sudor="proceed_sudo # "

####### Arch latest news long
#if [ "$PS1" ] && [[ $(ping -c1 www.google.com 2>&-) ]]; then
#    # The characters "£, §" are used as metacharacters. They should not be encountered in a feed...
#    echo -e "$(echo $(curl --silent https://www.archlinux.org/feeds/news/ | sed -e ':a;N;$!ba;s/\n/ /g') | \
#       sed -e 's/&amp;/\&/g
#       s/&lt;\|&#60;/</g
#       s/&gt;\|&#62;/>/g
#       s/<\/a>/£/g
#       s/href\=\"/§/g
#       s/<title>/\\n\\n\\n   :: \\e[01;31m/g; s/<\/title>/\\e[00m ::\\n/g
#       s/<link>/ [ \\e[01;36m/g; s/<\/link>/\\e[00m ]/g
#       s/<description>/\\n\\n\\e[00;37m/g; s/<\/description>/\\e[00m\\n\\n/g
#       s/<p\( [^>]*\)\?>\|<br\s*\/\?>/\n/g
#       s/<b\( [^>]*\)\?>\|<strong\( [^>]*\)\?>/\\e[01;30m/g; s/<\/b>\|<\/strong>/\\e[00;37m/g
#       s/<i\( [^>]*\)\?>\|<em\( [^>]*\)\?>/\\e[41;37m/g; s/<\/i>\|<\/em>/\\e[00;37m/g
#       s/<u\( [^>]*\)\?>/\\e[4;37m/g; s/<\/u>/\\e[00;37m/g
#       s/<code\( [^>]*\)\?>/\\e[00m/g; s/<\/code>/\\e[00;37m/g
#       s/<a[^§|t]*§\([^\"]*\)\"[^>]*>\([^£]*\)[^£]*£/\\e[01;31m\2\\e[00;37m \\e[01;34m[\\e[00;37m \\e[04m\1\\e[00;37m\\e[01;34m ]\\e[00;37m/g
#       s/<li\( [^>]*\)\?>/\n \\e[01;34m*\\e[00;37m /g
#       s/<!\[CDATA\[\|\]\]>//g
#       s/\|>\s*<//g
#       s/ *<[^>]\+> */ /g
#       s/[<>£§]//g')\n\n";
#fi

####### Arch latest news short - http://1.f.ix.de/icons/ho/rss.gif
#if [ "$PS1" ] && [[ $(ping -c1 www.google.com 2>&-) ]]; then
#    # The characters "£, §" are used as metacharacters. They should not be encountered in a feed...
#    echo -e "$(echo $(curl --silent https://www.archlinux.org/feeds/news/ | awk ' NR == 1 {while ($0 !~ /<\/item>/) {print;getline} sub(/<\/item>.*/,"</item>") ;print}' | sed -e #':a;N;$!ba;s/\n/ /g') | \
#        sed -e 's/&amp;/\&/g
#        s/&lt;\|&#60;/</g
#        s/&gt;\|&#62;/>/g
#        s/<\/a>/£/g
#        s/href\=\"/§/g
#       s/<title>/\\n\\n\\n   :: \\e[01;31m/g; s/<\/title>/\\e[00m ::\\n/g
#        s/<link>/ [ \\e[01;36m/g; s/<\/link>/\\e[00m ]/g
#        s/<description>/\\n\\n\\e[00;37m/g; s/<\/description>/\\e[00m\\n\\n/g
#        s/<p\( [^>]*\)\?>\|<br\s*\/\?>/\n/g
#        s/<b\( [^>]*\)\?>\|<strong\( [^>]*\)\?>/\\e[01;30m/g; s/<\/b>\|<\/strong>/\\e[00;37m/g
#        s/<i\( [^>]*\)\?>\|<em\( [^>]*\)\?>/\\e[41;37m/g; s/<\/i>\|<\/em>/\\e[00;37m/g
#        s/<!\[CDATA\[\|\]\]>//g
#        s/\|>\s*<//g
#        s/ *<[^>]\+> */ /g
#        s/[<>£§]//g')\n\n";
#fi

function mdr() { pandoc $1 | lynx -stdin -dump } 
# Render #markdown in the shell.

function topuniq(){ sort|uniq -c|sort "${@:--rn}"; } 
# Function to shorten this commonly used command line pattern & allow for options for final sort

function vercomp () {
# bash: version compare function 
    A=$1
    OP="$2"
    B=$3

    if [ "$A" == "$B" ]; then
        if [ "$OP" == "!=" ]; then
            if [[ $A == $B ]]
            then
                return 1
            else
                return 0
            fi
        fi

        if [ "$OP" == "=" ]; then
            if [[ $A == $B ]]
            then
                return 0
            else
                return 1
            fi
        else
            return 1
        fi
    else
        if [ "$OP" == "!=" ]; then
            if [[ $A == $B ]]
            then
                return 1
            else
                return 0
            fi
        fi

        if [ "$OP" == "=" ]; then
            if [[ $A == $B ]]
            then
                return 0
            else
                return 1
            fi
        fi
    fi

    local IFS=.
    local i ver1=($A) ver2=($B)
    # fill empty fields in ver1 with zeros
    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
    do
        ver1[i]=0
    done

    if [ "$OP" == "<" ]; then
        for ((i=0; i<${#ver1[@]}; i++))
        do
            if [[ -z ${ver2[i]} ]]
            then
                # fill empty fields in ver2 with zeros
                ver2[i]=0
            fi
            if ((10#${ver1[i]} < 10#${ver2[i]}))
            then
                return 0
            fi
            if ((10#${ver1[i]} > 10#${ver2[i]}))
            then
                return 1
            fi
        done
    fi

    local IFS=.
    local i ver1=($A) ver2=($B)
    # fill empty fields in ver1 with zeros
    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
    do
        ver1[i]=0
    done

    if [ "$OP" == ">" ]; then
        for ((i=0; i<${#ver1[@]}; i++))
        do
            if [[ -z ${ver2[i]} ]]
            then
                # fill empty fields in ver2 with zeros
                ver2[i]=0
            fi
            if ((10#${ver1[i]} > 10#${ver2[i]}))
            then
                return 0
            fi
            if ((10#${ver1[i]} < 10#${ver2[i]}))
            then
                return 1
            fi
        done
    fi
}
#-----------------------------------------------------------------------------------------------------------------------------#

# Prints msec in format "[d days ]hh:mm:ss.SSS"
function format_duration #(msec=0)
{
    local t=${1:-0}
    local days=$((t/60/60/24))
    [ $days -gt 0 ] && echo -ne "$days days "
    printf "%d:%02d:%02d" $((t/60/60%24)) $((t/60%60)) $((t%60))
}

# Prints file permissions in decimal mode, ex. 755.
# $ perm ~
# $ 750
function perm #(path=.)
{
    [ -e "${1:-.}" ] && stat -c %a "${1:-.}"
}

# Prints timestamp of elderly modified file matching mask in provided directory.
# If directory does not exist or no files matching mask present then nothing is output.
function eldest_content_mod_ts #(path=., filename_mask=.*)
{
    #if [ -n "`basename '$1'`" ]; then
    if [ -d "${1:-.}" ]; then

        #find "`dirname '$1'`" -type f -maxdepth 1 -name "`basename '$1'`" -printf "%C@ %T@ %P\n"
        
        find "${1:-.}" -maxdepth 1 -name "${2:-.*}" -printf "%C@ %T@ %P\n" \
            | awk '{ print ($1>$2?$1:$2) }' \
            | sort -bgk 1 \
            | tail -n 1

    fi
}

# Prints names of files which match.
# perm - exact match
# -perm - greater or equal
# +perm - less or equal
function match_perm #(filename_mask, perm)
{
    find "`dirname $1`" -maxdepth 1 -name "`basename $1`" -printf "%P\n" -perm +`printf %03d "${2:-0}"`
}

# Prints directory content age in msec.
function content_age #(path=., filename_mask=.*)
{
    local mod_ts="`eldest_content_mod_ts \"$1\" \"$2\"`"
    if [ -n "$mod_ts" ]; then
        expr "`date +%s` - $mod_ts"
    fi
}

# Returns 0 iff provided path is mounted, otherwhise 1.
function mounted #(path=.)
{
    [ -d "${1:-.}" ] && [[ ! `stat -f -L -c %T "${1:-.}"` =~ "ext.*" ]] && return 0
    return 1
}

# Returns 0 iff permissions for path are greater or equal to perm.
function enough_perm #(path, perm)
{
    local act=`perm "$1"`
    local exp=`printf %03d "${2:-0}"`
    [ "${act:0:1}" -ge "${exp:0:1}" ] && [ "${act:1:1}" -ge "${exp:1:1}" ] && [ "${act:2:1}" -ge "${exp:2:1}" ] && return 0
    return 1
}

function blue(){ tput setaf 4; echo $@; tput sgr0; } 
# Make text passed by argument to this function blue. ex: blue "I'm blue"

function box() { t="$1xxxx";c=${2:-=}; echo ${t//?/$c}; echo "$c $1 $c"; echo ${t//?/$c}; } 
# Make box around text. By @bartonski See https://www.youtube.com/watch?v=9bZ85aMuf6c … for an explanation of how it works.

function man2txt() { man "$@" | col -bx ;}
# Dump man page as clean text - Dumping man pages to text typically retains certain formatting such as foo^H^H^H___ for underscoring, and reverse-line feeds (not sure why). 'col -bx' removes these. 

function hex2bin () { s=${@^^}; for i in $(seq 0 1 $((${#s}-1))); do printf "%04s" `printf "ibase=16; obase=2; ${s:$i:1};\n" | bc` ; done; printf "\n"; }
# Convert hex data to binary with a bash function (requires bash v4+ for the @^^ lowercase hex demangling)
# Use this function with bash version 4+ to convert arbitrary hexadecimal sequences to binary. If you don't have bash 4+ then modify the lowercase to uppercase demangling statement s=${@^^} to set s equal to the uppercase hex input or the bc command throws an input parser error. This is sample output - yours may be different.
$ bash --version
GNU bash, version 4.4.23(1)-release (x86_64-apple-darwin17.5.0)
$ hex2bin 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
0000000000000000000000000000000000000000000110011101011001101000100111000000100001011010111000010110010110000011000111101001001101001111111101110110001110101110010001101010001010100110110000010111001010110011111100011011011000001010100011001110001001101111

function yesterday(){ date -d "${1:-now} - 1 day" +"${2:-%Y%m%d}"; } 
# A function that can give you previous day. Can take date arg and format.

function thirdline(){ awk '{if (NR%3==0){print "\033[32m" $0 "\033[0m"} else{print}}'; } 
# Function that will make every 3rd line of input green to make it easier to follow the lines among others. Usage: ps auxww | thirdline ip addr show | thirdline
#"greenbar" look with something like: 
awk '{if (NR%2==0){print "\033[48;5;36m" $0 "\033[48;5;0m"} else{print}}'
# Want to make sure you get the white lines too? 
awk '{print "\033[30;48;5;" (NR % 3 ? 15 : 45) "m" $0 "\033[0m"}'

function uploadphotos(){ rsync -av "$@" you@webserver:www/photos/; } 
# A function you can set up to make it easy to upload photos to your website. Example usage: uploadphotos IMG_*.JPG 01535.jpg anotherphoto.JPG

# Pluralize user input - Pluralize a word, aka change from single to multiple; text formatting. echo hamburgler | pluralize Show Sample Output
pluralize() { if [ -n "$1" ]; then echo ${1}s else while read line; do pluralize $line done fi }

# Check if your desired password is already available in haveibeenpwnd database. This command uses the API provided by HIBP
function hibp() { sha1=$(echo -n "$1"|sha1sum|awk '{print toupper($0)}'|tr -d '\n'); curl -s -H $'Referer: https://haveibeenpwned.com/' https://api.pwnedpasswords.com/range/$(echo -n $sha1|cut -c1-5)|grep -i $(echo -n $sha1|cut -c6-40); }

#Backup with versioning - Apart from an exact copy of your recent contents, also keep all earlier versions of files and folders that were modified or deleted. Inspired by the excellent EVACopy http://evacopy.sourceforge.net Show Sample Output
backup() { source=$1 ; rsync --relative --force --ignore-errors --no-perms --chmod=ugo=rwX --delete --backup --backup-dir=$(date +%Y%m%d-%H%M%S)_Backup --whole-file -a -v $source/ ~/Backup ; } ; backup /source_folder_to_backup

# Make .bashrc function to backup the data you changed last houres - The original overwrites any previous backups, and only saves exactly the last hours worth, but not 1 hour + 1 minute. This version creates or appends files, and backs up everything since the last backup (using the backups timestamp as the reference), plus it uses TMPDIR if set.
echo "function backup() { local CA=c T=${TMPDIR:+/tmp}/backup.tar.gz; [[ -f $T ]]&& C=r; find ~ -type f -newer $T | tar ${CA}vfz $T -T - ;}" >> ~/.bashrc

# Funktion for cmd post to transfer.sh
function transfer() { if [ $# -eq 0  ]; then echo -e "No arguments specified. Usage:\necho transfer /tmp/test.md\ncat /tmp/test.md | transfer test.md"; return 1; fi
tmpfile=$( mktemp -t transferXXX  ); if tty -s; then basefile=$(basename "(" | sed -e 's/[^a-zA-Z0-9._-]/-/g'); curl --progress-bar --upload-file "(" "https://transfer.sh/$basefile" >> $tmpfile; else curl --progress-bar --upload-file "-" "https://transfer.sh/(" >> $tmpfile ; fi; cat $tmpfile; rm -f $tmpfile; }")))")}

# Bash function that saves bash functions to file from shell session - The simpler, 1-arg version is save_function(){ { date +"# %F.%T $1; declare -f "$1";}| tee -a ~/.bash_functions; }`
function save_function(){ while [[ $# > 0 ]]; do { date +"# %F.%T $1; declare -f "$1";}| tee -a ~/.bash_functions; shift; done;}
#" Sample output
	    # $ save_function save_function
	    # 2019-07-16.18:03:57 save_function
	    # save_function ()
	    # {
		# while [[ $# > 0 ]]; do
		    # {
			# date +"# %F.%T $1";
			# declare -f "$1"
		    # } | tee -a ~/.bash_functions;
		    # shift;
		# done
	    # }

# Line Separator That is Width of Terminal - Creates a line seperator that will be the width of your window.
function CL () { WORDS=$@; termwidth="$(tput cols)"; padding="$(printf '%0.1s' ={1..500})"; printf '%*.*s %s %*.*s\n' 0 "$(((termwidth-2-${#WORDS})/2))" "$padding" "$WORDS" 0 "$(((termwidth-1-${#WORDS})/2))" "$padding"; }
# Sample output
	    # ???? CL test                                                                                         
	    # ============================================== test ==============================================

# edit, view or execute last modified file with a single key-press - Copy this function to command line, press 'Enter' 'f'' 'Enter' to execute (sentence on the left written only for newbies). Hint 'e|x|v|1..9' in front of displayed last modified file name means: "Press 'e' for edit,'x' for execute,'v' for view or a digit-key '1..9' to touch one file from the recent files list to be last modified" and suggested (hidden files are listed too, else remove 'a' from 'ls -tarp' statement if not intended). If you find this function useful you can then rename it if needed and append or include into your ~/.bashrc config script. With the command . ~/.bashrc the function then can be made immediately available. In the body of the function modifications can be made, i.e. replaced joe editor command or added new option into case statement, for example 'o) exo-open $h;;' command for opening file with default application - or something else (here could not be added since the function would exceed 255 chars). To cancel execution of function started is no need to press Ctrl-C - if the mind changed and want to leave simple Enter-press is enough. Once defined, this function can with typeset -f f command be displayed in easy readable form
function f() { ls -lart;e="ls -tarp|grep -v /|tail -9";j=${e/9/1};g=${e/9/9|nl -nln};h=$(eval $j);eval $g;read -p "e|x|v|1..9 $(eval $j)?" -n 1 -r;case $REPLY in e) joe $h;;v)cat $h;;x) eval $h;;[1-9]) s=$(eval $g|egrep ^$REPLY) && touch "${s:7}" && f;;esac ; }
    # Sample output
	    # knoppix5@kanta:~/SKRIPTE$ f
	     # ...
	     # 1       rdiff_backup_to_sda3.txt
	     # 2       arrange_windows_simple_from_xfce_panel.txt
	     # 3       .config.sh
	     # 4       arrange_windows.txt
	     # 5       read1.sh
	     # 6       read3.sh
	     # 7       lsb.sh
	     # 8       board9.pgn
	     # 9       read4.sh
	     # e|x|v|1..9 read4.sh?

# create a nicely formatted example of a shell command and its output - Shell function which takes a bash command as its input, and displays the following formatted output: EXAMPLE: command OUTPUT: output from command
function example() { echo "EXAMPLE:"; echo; echo " $@"; echo; echo "OUTPUT:"; echo ; eval "$@" | sed 's/^/ /'; }
    # Sample output
    # EXAMPLE:
	# example ls -l
    # OUTPUT:
	# EXAMPLE:   
	    # ls -l    
	# OUTPUT:   
	    # total 0
	    # -rw-rw-r-- 1 bartonc bartonc 0 Nov 10 13:58 a
	    # -rw-rw-r-- 1 bartonc bartonc 0 Nov 10 13:58 b
	    # -rw-rw-r-- 1 bartonc bartonc 0 Nov 10 13:58 c

# Listen to a song from youtube
function listen-to-yt() { if [[ -z "$1" ]]; then echo "Enter a search string!"; else mpv "$(youtube-dl --default-search 'ytsearch1:' \"$1\" --get-url | tail -1)"; fi }

    
# Compute factorial of positive integer using only built-ins
function factorial() { eval let N=1 N*={1..$1} ; echo $N; }

# Recursively compute factorial of positive integer using only built-ins
function factorial() {  [ "$1" = "0" ] && echo ${2:-1} || factorial $(( $1 - 1 )) $(( ${2:-1} * $1 )); }

# Listen to a song from youtube with youtube-dl and mpv - Explanation Firstly the function checks if user gave it any input, and notifies the user if they failed to do so. If user has inputed a search string, the function will call upon youtube-dl to find url of the audio of the first matching youtube video and play that with mpv. Call function by wrapping search string in quotes: listen-to-yt "sultans of swing" You have to paste the line in your .zshrc and source .zshrc for it to work. Limitations The dependancies are youtube-dl and mpv. 
function listen-to-yt() { if [[ -z "$1" ]]; then echo "Enter a search string!"; else mpv "$(youtube-dl --default-search 'ytsearch1:' \"$1\" --get-url | tail -1)"; fi }

# Cipher the file, upload it using tor.
# The link can be used only once, and expires after 24H.
function fileIoupload() {
  PASS=$(openssl rand -base64 16)
  zip -P "$PASS" - "$1" | proxychains curl -F "file=@-" "https://file.io/?expires=1d" | cut -d '"' -f 10

  echo "PASSWORD: $PASS"
}

#-------------------------------------#
# Awk float comparison hack for Bash
# By default Bash does not support floating point number comparisons…
[[ '2.1' -gt '1.2' ]] && {
  printf 'true\n'
} || {
  printf 'false\n'
}
	# syntax error: invalid arithmetic operator (error token is ".1")

(('1.2' < '2.1')) && {
  printf 'true\n'
} || {
  printf 'false\n'
}
	# 	syntax error: invalid arithmetic operator (error token is ".2 < 2.1")

#… however, with a bit of Awk redirection it is possible to add this functionality…

function compare_floats() {
  awk 'BEGIN { if ('"$@"') { exit 0; } exit 1; }'
}

# Example usage…
compare_floats '2.1 > 1.2' && {
  printf 'totally true\n'
} || {
  printf >&2 'oh so false\n'
}
	# totally true

if compare_floats '2.1 < 1.2'; then
  printf 'totally true\n'
else
  printf >&2 'oh so false\n'
fi
	# oh so false
#-------------------------------------#

#-------------------------------------#

# Awk/#Bash _slugify_ string...
function slugger() {
  awk '{
    gsub(" ", "-", $0)
    gsub(/[^a-zA-Z0-9\-]/, "", $0)
    gsub(/--*/, "-", $0)
    print tolower($0)
  }' <<<"$@"
}
slugger 'SPAM-`-`-' '"Flavored--ham'
	# 	spam-flavored-ham

# stdout to array...
_dir="/tmp/somewhere"
_s=($(ls -ld "${_dir}" | awk '{ print $1, $3, $4; }'))

printf 'Group -> %s\n' "${_s[1]}"
printf 'User -> %s\n' "${_s[2]}"

#-------------------------------------#

#-------------------------------------#

# Bash trick for stripping any number of trailing slashes...the `%%<pastern>` bit is the _magic sauce_
function slash_stripper() {
  local _path="${1%%*(//|/)}"
  printf '%s\n' "${_path}"
}
slash_stripper '/home/user/bad-path///'
	#	 /home/user/bad-path

#-------------------------------------#

# Bash regex-like pastern branching...the `=~` bit is the _magic sauce_
function escape_double_quotes() {
  local _input="$@"
  [[ "${_input}" =~ '"' ]] && {
    _input="${@//\"/'\"'}"
  }
  printf '%s\n' "${_input}"
}
escape_double_quotes '"foo"'
	#	 \"foo\"

#-------------------------------------#

#-------------------------------------#

# Quick SSH - Bash redirection example...
function push_key(){
  _host="${1:?}"
  _key="${2:?}"
  ssh "${_host}" <<EOF
mkdir ~/.ssh
tee -a ~/.ssh/authorized_keys 1>/dev/null <<<"$(<"${_key}")"
chmod 644 ~/.ssh/authorized_keys
EOF
}
push_key raspberrypi ~/.ssh/pi.pub
	#	Adds key to server

#-------------------------------------#

#-------------------------------------#

# bash scripting tip; how to pass multiple arrays by reference with `local -n`...
function nth(){
  _i="$1"
  local -n _ref1="$2"
  local -n _ref2="$3"
  printf '%s | %s\n' "${_ref1[$_i]}" "${_ref2[$_i]}"
}
_a0=(spam space ham)
_a1=(1 2 3)

nth '0' '_a0' '_a1'
	#	 spam | 1
#-------------------------------------#

#-------------------------------------#

function spam { <command>; }
	# verses...
function ham(){ <command>; }

#-------------------------------------#

#==============================##==============================#
# CMD function						       #
#==============================##==============================#
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

  █║▌│║█║▌★ KALI ★ PARROT ★ DEBIAN 🔴 PENTESTING ★ HACKING ★ █║▌│║█║▌

              ██╗ ██╗ ██████╗  ██████╗ ██╗  ██╗███████╗██████╗
             ████████╗██╔══██╗██╔═══██╗╚██╗██╔╝██╔════╝██╔══██╗
             ╚██╔═██╔╝██║  ██║██║   ██║ ╚███╔╝ █████╗  ██║  ██║
             ████████╗██║  ██║██║   ██║ ██╔██╗ ██╔══╝  ██║  ██║
             ╚██╔═██╔╝██████╔╝╚██████╔╝██╔╝ ██╗███████╗██████╔╝
              ╚═╝ ╚═╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═════╝

               █║▌│║█║▌ WITH COMMANDLINE-KUNGFU POWER █║▌│║█║▌

░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░