# Globbing is simple? Sure .. See zshexpn(1) /Glob Qualifiers for details and
# come back ;) 
function H-Glob()
{
echo -e "
     /      directories
      .      plain files
      @      symbolic links
      =      sockets
      p      named pipes (FIFOs)
      *      executable plain files (0100)
      %      device files (character or block special)
      %b     block special files
      %c     character special files
      r      owner-readable files (0400)
      w      owner-writable files (0200)
      x      owner-executable files (0100)
      A      group-readable files (0040)
      I      group-writable files (0020)
      E      group-executable files (0010)
      R      world-readable files (0004)
      W      world-writable files (0002)
      X      world-executable files (0001)
      s      setuid files (04000)
      S      setgid files (02000)
      t      files with the sticky bit (01000)
 print *(m-1)          # Dateien, die vor bis zu einem Tag modifiziert wurden.
 print *(a1)           # Dateien, auf die vor einem Tag zugegriffen wurde.
 print *(@)            # Nur Links
 print *(Lk+50)        # Dateien die ueber 50 Kilobytes grosz sind
 print *(Lk-50)        # Dateien die kleiner als 50 Kilobytes sind
 print **/*.c          # Alle *.c - Dateien unterhalb von \$PWD
 print **/*.c~file.c   # Alle *.c - Dateien, aber nicht 'file.c'
 print (foo|bar).*     # Alle Dateien mit 'foo' und / oder 'bar' am Anfang
 print *~*.*           # Nur Dateien ohne '.' in Namen
 chmod 644 *(.^x)      # make all non-executable files publically readable
 print -l *(.c|.h)     # Nur Dateien mit dem Suffix '.c' und / oder '.h'
 print **/*(g:users:)  # Alle Dateien/Verzeichnisse der Gruppe >users<
 echo /proc/*/cwd(:h:t:s/self//) # Analog zu >ps ax | awk '{print $1}'<"
}

# colorizing the output of make
if [[ -x ~/bin/makefilter ]]
then
        make() { command make "$@" |& makefilter }
fi

# check if ~/.errorlogs/ exist (otherwise create it) and create a
# ``logfile'' e. g. ``makelog-vim-6.3''
function mmake()
{
	[[ ! -d ~/.errorlogs ]] && mkdir ~/.errorlogs
	=make -n install > ~/.errorlogs/${PWD##*/}-makelog
}

# Search for the argument in the system libraries
function lcheck()
{
	nm -go /usr/lib/lib*.a /usr/lobal/lib/lib*.a 2>/dev/null | grep ":[[:xdigit:]]\{8\} . .*$1"":[[:xdigit:]]\{8\} . .*$1"
}

# clean directory
function purge()
{
	FILES=(*~(N) .*~(N) \#*\#(N) *.o(N) a.out(N) *.core(N) *.cmo(N) *.cmi(N) .*.swp(N))
	NBFILES=${#FILES}
	if [[ $NBFILES > 0 ]]; then
		print $FILES
		local ans
		echo -n "Remove this files? [y/n] "
		read -q ans
		if [[ $ans == "y" ]]
		then
			rm ${FILES}
			echo ">> $PWD purged, $NBFILES files removed"
		else
			echo "Ok. .. than not.."
		fi
	fi
}

# display a of possible passwords.
function makepasswords()
{
	perl <<EOPERL
	my @a = ("a".."z","A".."Z","0".."9",(split //, q{#@,.<>$%&()*^}));
	for (1..10) { 
		print join "", map { \$a[rand @a] } (1..rand(3)+7);
		print qq{\n} 
	}
EOPERL
}
# AUTOMATIC ls on chpwd *if* directly isn't too big.
# Not really needed ;o)
#function chpwd
#{
#	integer ls_lines="$(ls -C | wc -l)"
#	if [ $ls_lines -eq 0 ]; then
#		echo No files found: Empty Directory 
#	elif [ $ls_lines -le 18 ]; then
#		ls
#		echo "\e[1;32m --[ Items: `ls -l | wc -l` \e[1;32m]--"
#	else
#		echo Directory Exceeds Limits.
#	fi
#}

# ssh-add -- wrap ssh-add to default to adding all identities in
# ${HOME}/.ssh
function ssh-add()
{
	local files
	if [[ $# -eq 0 ]] ; then
		for i in id_dsa id_rsa identity ; do
			if [[ -f $HOME/.ssh/$i ]] ; then
				files=($files $HOME/.ssh/$i)
			fi
		done
	else
		files=( "$@" )
	fi
	command ssh-add $files
}

# Name (``hash -d'') all the subdirectories in given directory
# $ mkdir -p foo/{bar,foo,fnord,recursion}
# $ quick-hash foo
# $ hash -d
# bar=foo/bar
# fnord=foo/fnord
# foo=foo/foo
# recursion=foo/recursion
function quick-hash()
{
	for i in $1/*(/)
	do
		hash -d ${i##*/}=$i
	done
}

# print current settings of LC_*
function plocale()
{
	print LC_ALL=$LC_ALL
	print LANG=$LANG
	print LC_CTYPE=$LC_CTYPE
	print LC_NUMERIC=$LC_NUMERIC
	print LC_TIME=$LC_TIME
	print LC_COLLATE=$LC_COLLATE
	print LC_MONETARY=$LC_MONETARY
	print LC_MESSAGES=$LC_MESSAGES
	print LC_PAPER=$LC_PAPER
	print LC_NAME=$LC_NAME
	print LC_ADDRESS=$LC_ADDRESS
	print LC_TELEPHONE=$LC_TELEPHONE
	print LC_MEASUREMENT=$LC_MEASUREMENT
	print LC_IDENTIFICATION=$LC_IDENTIFICATION
}
# a clock in the prompt. 
#trap CRON ALRM
#TMOUT=1
#CRON() {
#   local STRING
#   local COL
#   local x
#   STRING=$(date)
#   COL=$[COLUMNS-5]
#   COL=$[COL-$#STRING]
#   x=$(echo $PREBUFFER | wc -l )
#   x=$[x+1]
#   echo -n "7[$x;A[$COL;G[0;37;44m-- $STRING --[0m8"
#}

# invoke this every time when u change .zshrc to recompile it.
function src()
{
        autoload -U zrecompile
                [ -f ~/.zshrc ] && zrecompile -p ~/.zshrc
                [ -f ~/.zcompdump ] && zrecompile -p ~/.zcompdump
                [ -f ~/.zcompdump ] && zrecompile -p ~/.zcompdump
                [ -f ~/.zshrc.zwc.old ] && rm -f ~/.zshrc.zwc.old
                [ -f ~/.zcompdump.zwc.old ] && rm -f ~/.zcompdump.zwc.old
                source ~/.zshrc
}

# Search for links in a directory and format the output
# Note: '~/.fnord.awk' is a *very* simple script based on >awk<.
#  ,----
#  | $ cat ~/bin/fnord.awk
#  |   BEGIN {
#  |     regexp = ""
#  |     regexp = regexp "((http|ftp)://)"
#  |     regexp = regexp  "[-0-9A-Za-z#%&+./:;?_~]"
#  |     regexp = regexp "*[-0-9A-Za-z#%&+/:;?_~]"
#  |   }
#  |   NF {
#  |        while (match($0, regexp))
#  |          {
#  |            print substr($0, RSTART, RLENGTH)
#  |             $0 = substr($0, RSTART + RLENGTH)
#  |          }
#  |      }
#  | END {}
#  `----
function URL-search()
{
        if [[ $# = 0 ]]
        then
                echo "Usage   : $0 directory"
                echo "Example : $0 ~/Mail"
                echo "Example : $0 directory | \$PAGER"
                echo "Example : $0 directory > logfile"
        else
                egrep -r -h -i '((ftp|https|http|www):.*)' $1 | awk -f ~/bin/fnord.awk | sort | uniq 
        fi
}

# Happy CVS'ing
function cvsd() { cvs diff -N $* |& $PAGER }
function cvsl() { cvs log $* |& $PAGER }
function cvsr() { rcs2log $* | $PAGER }
function cvss() { cvs status -v $* }
function cvsq() { cvs -nq update }
function cvsa() { cvs add $* && cvs com -m 'initial checkin' $* }

# Display the permissions in octal from given file. Not really needed.
# Use http://www.strcat.de/hacks/perm-oktal.pl instead
# function perm-oktal()
#{
#	echo $1 | perl -e 'chomp($s=<>);$p=(stat($s))[2] & 07777;printf "$s -> %04o\n",$p'
#}

# Translate DE<=>EN
# *narf* .. 'translate' looks up fot a word in a file with language-to-language
# translations (field separator should be " : "). A typical wordlist looks
# like at follows:
#  | english-word : german-transmission
# It's also only possible to translate english to german but not reciprocal.
# Use the following oneliner to turn back the sort order:
#  $ awk -F ':' '{ print $2" : "$1" "$3 }' \
#    /usr/local/lib/words/en-de.ISO-8859-1.vok > ~/.translate/de-en.ISO-8859-1.vok
function trans()
{
        case "$1" in
                -[dD]*) translate -l de-en $2
                ;;
                -[eE]*) translate -l en-de $2
                ;;
                *)
                echo "Usage: $0 { -D | -E }"
                echo "         -D == German to English"
                echo "         -E == English to German"
        esac
}

# Some quick Perl-hacks aka /useful/ oneliner
function bew() { perl -e 'print unpack "B*","'$1'"' ; perl -e 'print "\n"' }
function web() { perl -e 'print pack "B*","'$1'"' ; perl -e 'print "\n"' }
function hew() { perl -e 'print unpack "H*","'$1'"' ; perl -e 'print "\n"' }
function weh() { perl -e 'print pack "H*","'$1'"' ; perl -e 'print "\n"' }
function pversion() { perl -M$1 -le "print $1->VERSION" } # i. e."pversion LWP -> 5.79"
function getlinks () { perl -ne 'while ( m/"((www|ftp|http):\/\/.*?)"/gc ) { print $1, "\n"; }' $* }
function gethrefs () { perl -ne 'while ( m/href="([^"]*)"/gc ) { print $1, "\n"; }' $* }
function getanames () { perl -ne 'while ( m/a name="([^"]*)"/gc ) { print $1, "\n"; }' $* }
function getforms () { perl -ne 'while ( m:(\</?(input|form|select|option).*?\>):gic ) { print $1, "\n"; }' $* }
function getstrings () { perl -ne 'while ( m/"(.*?)"/gc ) { print $1, "\n"; }' $*}
function getanchors () { perl -ne 'while ( m/([^\n]+)/gc ) { print $1, "\n"; }' $* }
function showINC () { perl -e 'for (@INC) { printf "%d %s\n", $i++, $_ }' }
function vimpm () { vim `perldoc -l $1 | sed -e 's/pod$/pm/'` }
function vimhelp () { vim -c "help $1" -c on -c "au! VimEnter *" }

# set the DISPLAY to where i'm logged from or - if an argument is specified -
# to the value of the argument
function disp()
{
        if [[ $# == 0 ]]
        then
                DISPLAY=$(who am i | awk '{print $6}' | tr -d '()'):0
        else
                DISPLAY="${*}:0"
        fi
        export DISPLAY
}

# adds a directory to the PATH, without making duplicate entries
function add_to_path()
{
        if [[ "$1" == "" ]]
        then
                echo "Usage: $0 directory"
        else
                unset SPACEPATH
                local SPACEPATH
                for i in  ${(s.:.)PATH}
        do
                SPACEPATH=( $SPACEPATH $i )
        done
        typeset -U SPACEPATH
        if [[ -d "$1" ]]; then; SPACEPATH=( $SPACEPATH "$1" ); fi
        PATH="`echo $SPACEPATH`"
        PATH=${PATH:gs/ /:/}
        export PATH
        rehash
fi
}

# Shameless stolen from Sven Guckes (<http://www.guckes.net/setup/zshrc.mine>)
# _lap foo -- list all programs with prefix "foo":
function _lap()
{
        if [[ $# = 0 ]]
        then
                echo "Usage:    $0 program"
                echo "Example:  $0 zsh"
                echo "Lists all occurrences of program in the current PATH."
        else
		ls -l ${^path}/*$1*(*N)
	fi
}

# A life without 'diff'? Unimaginably!!!!11!
function mdiff() { diff -udrP "$1" "$2" > diff.`date "+%Y-%m-%d"`."$1" }
function udiff() { diff -urd $* | egrep -v "^Only in |^Binary files " }
function cdiff() { diff -crd $* | egrep -v "^Only in |^Binary files " }

# List / Search / Browse in a archive without unpack
function lynxbzgrep() { lynx -force_html -dump =(bzip2 -cd $1) | grep -i $2 }
function browse-archive() { lynx -force_html <( gzip -cd $1 ) }

# show/search signatures ;-)
# random-signature.pl can be found at
# <http://www.strcat.de/hacks/random-signature.pl>
function sig() 
{
        if [[ $# = 0 ]]; then
                random-signature.pl; < ~/.signature
        else
                agrep -d "^-- $" $@ ~/.sigs/own-stuff
        fi
}

# mkdir && cd
function mcd() { mkdir "$1"; cd "$1" } 

# $ ls -l =ls
# $ -r-xr-xr-x    1 root     bin        167936 Oct  4  2002 /bin/ls
# $ pls ls
# $ -r-xr-xr-x    1 root     bin        167936 Oct  4  2002 /bin/ls 
function pls() { ls -l =$1 }

# cd && ls
function cl() { cd $1 && ls -a }

# Use vim to convert plaintext to HTML
function 2html() { vim -n -c ':so $VIMRUNTIME/syntax/2html.vim' -c ':wqa' $1 > /dev/null 2> /dev/null }

# Often needed (if i rape '$LS_COLORS' again *g*)
function _cols()
{
        esc="\033["
        echo -e "\t 40\t 41\t 42\t 43\t 44\t 45\t 46\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
}

# Usage: simple-extract <file>
# Description: extracts archived files (maybe)
simple-extract () 
{
        if [[ -f $1 ]]
        then
                case $1 in
                        *.tar.bz2)  bzip2 -v -d $1      ;;
                        *.tar.gz)   tar -xvzf $1        ;;
                        *.rar)      unrar $1            ;;
                        *.deb)      ar -x $1            ;;
                        *.bz2)      bzip2 -d $1         ;;
                        *.lzh)      lha x $1            ;;
                        *.gz)       gunzip -d $1        ;;
                        *.tar)      tar -xvf $1         ;;
                        *.tgz)      gunzip -d $1        ;;
                        *.tbz2)     tar -jxvf $1        ;;
                        *.zip)      unzip $1            ;;
                        *.Z)        uncompress $1       ;;
                        *)          echo "'$1' Error. Please go away" ;;
                esac
        else
                echo "'$1' is not a valid file"
        fi
}

# Usage: smartcompress <file> (<type>)
# Description: compresses files or a directory.  Defaults to tar.gz
smartcompress()
{
	if [ $2 ]; then
		case $2 in
			tgz | tar.gz)   tar -zcvf$1.$2 $1 ;;
			tbz2 | tar.bz2) tar -jcvf$1.$2 $1 ;;
                        tar.Z)          tar -Zcvf$1.$2 $1 ;;
                        tar)            tar -cvf$1.$2  $1 ;;
                        gz | gzip)      gzip           $1 ;;
                        bz2 | bzip2)    bzip2          $1 ;;
			*)
			echo "Error: $2 is not a valid compression type"
                        ;;
		esac
	else
		smartcompress $1 tar.gz
	fi
}

# Usage: show-archive <archive>
# Description: view archive without unpack
show-archive()
{
        if [[ -f $1 ]]
        then
                case $1 in
                        *.tar.gz)      gunzip -c $1 | tar -tf - -- ;;
                        *.tar)         tar -tf $1 ;;
                        *.tgz)         tar -ztf $1 ;;
                        *.zip)         unzip -l $1 ;;
                        *.bz2)         bzless $1 ;;
                        *)             echo "'$1' Error. Please go away" ;;
                esac
        else
                echo "'$1' is not a valid archive"
        fi
}

# find process and kill it
morons() { reply=(`ps ax | grep -v COMMAND |perl -nle '@a=split(" ",$_,9);$_=$a[4];s/[()]//g;s/.*\///g;print'`) }
compctl -K morons pskill pkill
pskill()
{
        local signal="HUP"
        if [[ $1 == "" || $3 != "" ]]; then
                print "Usage: $0 processname [signal]" && return 1
        fi
        [[ $2 != "" ]] && signal=$2
        set -A pids $(command ps wwaux | grep $1 | grep -v "grep $1" | awk '{ print $2 }')
        if [[ ${#pids} -lt 1 ]]; then
                print "No matching processes for $1" && return 1
        fi
        if [[ ${#pids} -gt 1 ]]; then
                print "${#pids} processes matched: $pids"
                read -q "?Kill all? [y/n] " || return 0
        fi
        if kill -$signal $pids; then
                echo "Killed $1 pid $pids with SIG$signal"
        fi
}

# Use 'view' to read manpages, if u want colors, regex - search, ...
# like vi(m).
# It's shameless stolen from <http://www.vim.org/tips/tip.php?tip_id=167>
function vman() { man $* | col -b | view -c 'set ft=man nomod nolist' - }

# J-E-H-O-V-A!!!11!!
#  ,----
#  |  $ (cd $PORTS_DIR && make print-index ~/.ports)
#  |  $ grep -i "^Port.*xchat-" -B1 -A8 .ports
#  |
#  |    Port:   xchat-1.8.11
#  |    Path:   net/xchat
#  |    Info:   X-Chat is an X11 IRC client
#  |    Maint:  Damien Couderc <couderc@openbsd.org>
#  |    Index:  net x11
#  |    L-deps: gdk_pixbuf::graphics/gdk-pixbuf iconv.2::converters/libiconv intl.1:gettext->=0.10.38:devel/gettext
#  |    B-deps: :devel/gmake bzip2-*:archivers/bzip2 gettext->=0.10.38:devel/gettext
#  |    R-deps: gettext->=0.10.38:devel/gettext libiconv-*:converters/libiconv
#  |
#  `----
if [ "${OS}" = openbsd ]; then
        function port() 
        {
                case "$1" in
                        -p) =grep -i "^Port.*$2" -B1 -A8 ~/.ports
                        ;;
                        -i) =grep -i "^Info.*$2" -B1 -A5 ~/.ports
                        ;;
                        *)
                        echo "Usage: $0 {-i | -p } string }"
                        echo "       -i (Info)       Search parse Info:"
                        echo "       -p (Port)       Search parse Port:"
                esac
        }
fi

# Exchange ' ' for '_' in filenames.
unspaceit()
{
        for _spaced in "${@:+"$@"}"; do
                if [ ! -f "${_spaced}" ]; then
                        continue;
                fi
                _underscored=$(echo ${_spaced} | tr ' ' '_');
                if [ "${_underscored}" != "${_spaced}" ]; then
                        mv "${_spaced}" "${_underscored}";
                fi
        done
}

# summarized google, ggogle, mggogle, agoogle and fm
function search()
{
	case "$1" in
		-g) ${BROWSER:-lynx} "http://www.google.com/search?q="$2""
		;;
		-u) ${BROWSER:-lynx} "http://groups.google.com/groups?q="$2""
		;;
		-m) ${BROWSER:-lynx} "http://groups.google.com/groups?selm="$2""
		;;
		-a) ${BROWSER:-lynx} "http://groups.google.com/groups?as_uauthors="$2""
		;;
		-c) ${BROWSER:-lynx} "http://search.cpan.org/search?query="$2"&mode=module"
		;;
		-f) ${BROWSER:-lynx} "http://freshmeat.net/search/?q=$2&section=projects"
		;;
		-F) ${BROWSER:-lynx} "http://www.filewatcher.com/?q="$2""
		;;
		-s) ${BROWSER:-lynx} "http://sourceforge.net/search/?type=soft&q="$2""
		;;
		*) 
		  echo "Usage: $0 {-g | -u | -m | -a | -f | -c | -F}"
		  echo "	-g: Searching for keyword in google.com"
		  echo "	-u: Searching for keyword in groups.google.com"
		  echo "	-m: Searching for message-id in groups.google.com"
		  echo "	-a: Searching for Authors in groups.google.com"
		  echo "	-c: Searching for Modules on cpan.org."
		  echo "	-f: Searching for projects on Freshmeat."
		  echo "	-F: Searching for packages on FileWatcher."
		  echo "	-s: Searching for software on Sourceforge."
	esac
}

# Quick&dirty hack to read heise-news (<http://www.heise.de/>
function heise()
{
	CURDIR=${pwd};
        cd /tmp;
        if [[ -s tmp/heise.rdf ]]
		then
			rm heise.rdf
		fi
		wget -q -O - http://heise.de/newsticker/heise.rdf |\
		sed -e '/title/!d;s, <title>\(.*\)</title>,\1,' -e '/heise online/d' ; 
		cd $CURDIR
}

# make screenshot of current desktop (use 'import' from ImageMagic)
# See man date(1) and man import(1) for details.
# Note: If you don't have 'import', install ImageMagick and stop
#       crying.
function sshot() 
{ 
	[[ ! -d ~/shots  ]] && mkdir ~/shots
	cd ~/shots ; sleep 5 ; import -window root -depth 8 -quality 80 `date "+%Y-%m-%d%--%H:%M:%S"`.png
#	cd ~/shots && sleep 5; import -window root `date "+%Y-%m-%d%--%H:%M:%S"`.jpg

}

# Needs ImageMagick
function gif2png() 
{
	if [[ $# = 0 ]]
	then
		echo "Usage: $0 foo.gif"
		echo "Purpose: change a GIF file to a PNG file"
	else
		output=`basename $1 .gif`.png
		convert  $1 $output
		touch -r $1 $output
		ls -l $1 $output
	fi
}

# search for various types or README file in dir and display them in $PAGER
# function readme() { $PAGER -- (#ia3)readme* }
function readme()
{
        local files
        files=(./(#i)*(read*me|lue*m(in|)ut)*(ND))
        if (($#files))
        then $PAGER $files
        else
                print 'No README files. Please lart \$MAINTAINER!'
        fi
}

# find all suid files in $PATH
function suidfind() { ls -latg ${(s.:.)PATH} | grep '^...s' }

# See above but this is /better/ ... anywise ..
#  Note: Add $USER and 'find' with "NOPASSWD" in your /etc/sudoers or run it
#        as root (UID == 0)
function findsuid()
{
        sudo find / -type f \( -perm -4000 -o -perm -2000 \) -ls > ~/.suid/suidfiles.`date "+%Y-%m-%d"`.out 2>&1
        sudo find / -type d \( -perm -4000 -o -perm -2000 \) -ls > ~/.suid/suiddirs.`date "+%Y-%m-%d"`.out 2>&1
        sudo find / -type f \( -perm -2 -o -perm -20 \) -ls > ~/.suid/writefiles.`date "+%Y-%m-%d"`.out 2>&1
        sudo find / -type d \( -perm -2 -o -perm -20 \) -ls > ~/.suid/writedirs.`date "+%Y-%m-%d"`.out 2>&1
}

# csh compatibility
setenv() { typeset -x "${1}${1:+=}${(@)argv[2,$#]}" }

# if [ Now-Playing == "relaxmusic" ];then .. ;-)
beer()
{
        echo "         _.._..,_,_"
        echo "        (          )"
        echo "         ]~,\"-.-~~["
        echo "       .=])' (;  ([    PANTS OFF!"
        echo "       | ]:: '    ["
        echo "       '=]): .)  (["
        echo "         |:: '    |"
        echo "          ~~----~~"
}

# Add directory to a bookmark-list
# % bmadd       # add directory to bookmark list
# % bmls        # show list of bookmark list
# % bmvi        # edit bookmark list
# % bm $NUMBER  # change directory to $NUMBER bookmark
BMRC=~/.bmrc
/usr/bin/touch $BMRC
bmls() { cat $BMRC | sort -n}
bmvi() { vi $BMRC }
bmadd() {
        local bmdir=`pwd`
        local newid=$1
        local bmname=''
        for bmname in `bm_path_list`
        do
                if [ "$bmname" = "$bmdir" ]; then
                        echo "$bmdir is already in bm list"
                        return
                fi
        done
        if [ -z $newid ]; then
                maxid=`cat $BMRC | cut -f 1 | sort -n -r | head -1`
                if [ "$maxid" -ge 1 ]; then
                        newid=`expr 0$maxid + 1`
                else
                        newid=1
                fi
        fi
        echo "$newid\t$bmdir" >> $BMRC
}
bm() {
        local num=$1
        local bmdir=`bm_get $num`
        if [ -z "$bmdir" ]; then
                bmls     
                [ -z "$num" ] || echo "$num is not in bm list"
                return
        fi
        cd "$bmdir"
}
bm_get() {
        local bmdir=`cat $BMRC | egrep "^${1}[[:space:]]" | cut -f 2`
        echo $bmdir
}

bm_path_list() {
        cut -f 2 < $BMRC
}

# Temporary (interactive) removes. Alternative to this u can use
# http://www.strcat.de/hacks/rm-replacements.shar
function rf()
{
        [[ -z ${SHITDIR} ]] && print "No ${SHITDIR} defined." && return 1
        [[ ! -d ${SHITDIR} ]] && mkdir ${SHITDIR}
        mv $* ${SHITDIR}
}

# Reload functions.
function refunc()
{
        for func in $argv
        do
                unfunction $func
                autoload $func
        done
}

# a small check to see which DIR is located on which server/partition.
# stolen and modified from Sven's zshrc.forall
function dirspace()
{
        for dir in ${(s.:.)PATH};
        do
                (cd $dir; echo "-<$dir>"; du -shx .; echo);
        done
}

# Create a archive for my homepage (<http://strcat.neessen.net/>)
function mkz()
{
	cd ~/homepage/dotfiles/zsh
	cp ~/.zlogin ~/homepage/dotfiles/zsh/zlogin
	cp ~/.zlogout ~/homepage/dotfiles/zsh/zlogout
	cp ~/.zshrc ~/homepage/dotfiles/zsh/zshrc
	cp ~/.zsh/z* ~/homepage/dotfiles/zsh/
	cd ~/homepage/dotfiles/zsh/
	rm ~/homepage/dotfiles/zsh/zshdevel.old
	tar cf dot-zsh.tar * 
	gzip --best ~/homepage/dotfiles/zsh/dot-zsh.tar
	cd ~1
}

# FIXME: works not so as i like
#--------------------------------------------------
# function verify() {
#         for i in "$1"
#         do
#                 if [ -r "$1" ]
#                 then
#                   #cd `dirname $1`
#                   cd =$1(:h)
#                 shortname=`basename $1`
#                   md5 "$shortname" > "~/.checksums/$shortname.md5sum"
#                   echo "Verified $shortname to $shortname.md5sum"
#                 else
#                   echo "Can not find $1"
#                 fi
#         done
# }
#-------------------------------------------------- 


# Find (and print) all symbolic links without a target within the
# current directorytree (i. e. ll symlinks that dont point to files,
# directories, sockets, devices, or named pipes).
# Note: all three functions works but the last is nicer
# function brlinks() { for i in **/*(D@); [[ -f $i || -d $i ]] || echo $i }
# function brlinks() { print -l **/*(@-^./=%p) }
function brlinks() { print -l **/*(-@) }

# *fg*
# function show_print () {
#    for argument in "${@}"
#      do
#for ((i = 1; i <= ${#1} ;i++)) {
#    print -n "${argument[i]}"
#    sleep 0.005
#}
#print -n " "
#      done
#    print ""
#}

# display some informations
function status()
{
        print ""
        print "Date..: "$(date "+%Y-%m-%d %H:%M:%S")""
        print "Shell.: Zsh $ZSH_VERSION (PID = $$, $SHLVL nests)"
        print "Term..: $TTY ($TERM), $BAUD bauds, $COLUMNS x $LINES cars"
        print "Login.: $LOGNAME (UID = $EUID) on $HOST"
        print "System: $(cat /etc/[A-Za-z]*[_-][rv]e[lr]*)"
        print "Uptime:$(uptime)"
        print ""
}

# a fucking lazy poor man clock..
# check time every minute
# PERIOD=60
# show time every 15 minutes
#function periodic()
#{
#       if [ `date +'%M'` = '00' ] ||
#               [ `date +'%M'` = '15' ] ||
#               [ `date +'%M'` = '30' ] ||
#               [ `date +'%M'` = '45' ]
#       then
#               echo Time: `date +'%H:%M'`
#       fi
#}

# For my Linux boxes
if [ ${OS} = linux-gnu ]; then
function mkernel() 
{
	make clean && make dep && make modules && make modules_install && make bzImage
        cd arch/i386/boot
}

function getkernel()
{
	if [ $# -ne 3 ] ; then
		echo "Usage:"
	        echo "$0 MAJOR MINOR SUBMINOR"
                echo ""
                echo "eg:"
	        echo "   $0 2 6 7"
		latest=`echo -e "GET /kdist/finger_banner HTTP/1.0\n" | netcat www.kernel.org 80 | sed -ne "/^
$/,//p"`
		echo ""
                echo "current versions: $latest"
	        echo ""
		echo -n 'Used release is: '
		uname -r
	else
		cd /Source
		SERVER=http://www.de.kernel.org/pub/linux/kernel/
		KERNEL=$SERVER/v$1.$2/linux-$1.$2.$3.tar.bz2
		SIGN=$SERVER/v$1.$2/linux-$1.$2.$3.tar.bz2.sign
		echo 'starting download'
		wget -c $KERNEL &&
		wget -c $SIGN   &&
		echo 'done'
		echo 'checking signature:'
		gpg --verify `basename $SIGN $KERNEL` &&
		echo 'done'
	fi
}

function audiorip()
{
        mkdir -p ~/ripps
        cd ~/ripps
        cdrdao read-cd --device $DEVICE --driver generic-mmc audiocd.toc
        cdrdao read-cddb --device $DEVICE --driver generic-mmc audiocd.toc
        echo " * Would you like to burn the cd now? (yes/no)"
        read input
        if
                [ "$input" = "yes" ]; then
                echo " ! Burning Audio CD"
                audioburn
                echo " * done."
        else
                echo " ! Invalid response."
        fi
}

function audioburn()
{
        cd ~/ripps
        cdrdao write --device $DEVICE --driver generic-mmc audiocd.toc
        echo " * Should I remove the temporary files? (yes/no)"
        read input
        if [ "$input" = "yes" ]; then
                echo " ! Removing Temporary Files."
                cd ~
                rm -rf ~/ripps
                echo " * done."
        else
                echo " ! Invalid response."
        fi
}

function mkaudiocd()
{
        cd ~/ripps
        for i in *.[Mm][Pp]3; do mv "$i" `echo $i | tr '[A-Z]' '[a-z]'`; done
        for i in *.mp3; do mv "$i" `echo $i | tr ' ' '_'`; done 
        for i in *.mp3; do mpg123 -w `basename $i .mp3`.wav $i; done 
        normalize -m *.wav
        for i in *.wav; do sox $i.wav -r 44100 $i.wav resample; done
}

function mkiso()
{
        echo " * Volume name "
        read volume
        echo " * ISO Name (ie. tmp.iso)"
        read iso
        echo " * Directory or File"
        read files
        mkisofs -o ~/$iso -A $volume -allow-multidot -J -R -iso-level 3 -V $volume -R $files
}

# rmmodcomplete() looks for modules in memory, for use with "rmmod".
rmmodcomplete () { reply=(`/sbin/lsmod|cut -f1 -d" "|grep -v Module`) }
compctl -K rmmodcomplete rmmod

# insmodcomplete() looks for modules to use with "insmod" or
# "modprobe".
function insmodcomplete() { reply=(`find /lib/modules/$(uname -r)/* ! -type d -printf "%f\n"|sed "s/\.o$//"`) }
compctl -K insmodcomplete insmod modprobe

fi

# Complete a howto-filename or FAQ-name (see howto script below).
# Use like "howto zsh[TAB]".
function howtocomplete() { reply=(`howto --find "$1"`) }
compctl -U -K howtocomplete howto
p0rncomplete() { reply=(`p0rn --find "$1"`) }
compctl -U -K p0rncomplete p0rn

# a quick hack for GNU Emacs && emacsclient
function e()
{
	if [ "$1" = "" ]; then
		echo "No file specified you have, think before you must."
	else
		if emacsclient -n "$1" >/dev/null 2>&1; then
			echo "Alrite, opened $1 in the Holy Emacs."
		else
			echo "There's no Holy Emacs running here.. starting.."
			exec emacs "$1" &
		fi
	fi
}

# Show days since given birthday
function days () 
{
	if [ "$*" = "" ]; then
		echo "Use $0 day month year"
		echo "Example: $0 "12 aug 1999""
	else
		BIRTHDAY="$*"
		print $(( (`date +%s -d ${2:="now"}` - `date +%s -d ${1:=$BIRTHDAY}` )/60/60/24 ))
	fi
}

# generate thumbnails ;)
function genthumbs ()
{
    rm -rf thumb-* index.html
    echo "
<html>
  <head>
    <title>Images</title>
  </head>
  <body>" > index.html
    for f in *.(gif|jpeg|jpg|png)
    do
        convert -size 100x200 "$f" -resize 100x200 thumb-"$f"
        echo "    <a href=\"$f\"><img src=\"thumb-$f\"></a>" >> index.html
    done
    echo "
  </body>
</html>" >> index.html
}
