summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--maintainers/docs/coding-conventions.txt97
-rw-r--r--pkgs/applications/audio/audacity/default.nix12
-rw-r--r--pkgs/applications/audio/aumix/default.nix24
-rw-r--r--pkgs/applications/audio/cdparanoia/default.nix4
-rw-r--r--pkgs/applications/audio/flac/default.nix30
-rw-r--r--pkgs/applications/audio/ladspa-plugins/default.nix8
-rw-r--r--pkgs/applications/audio/ladspa-plugins/ladspah.nix5
-rw-r--r--pkgs/applications/audio/lame/default.nix6
-rw-r--r--pkgs/applications/audio/mpg321/default.nix17
-rw-r--r--pkgs/applications/audio/snd/default.nix10
-rw-r--r--pkgs/applications/audio/vorbis-tools/default.nix24
-rw-r--r--pkgs/applications/audio/vorbis-tools/ogg123-curlopt-mute.patch13
-rw-r--r--pkgs/applications/audio/xmms/default.nix1
-rw-r--r--pkgs/applications/display-managers/slim/default.nix4
-rw-r--r--pkgs/applications/editors/bvi/default.nix17
-rwxr-xr-xpkgs/applications/editors/eclipse/builder.sh1
-rw-r--r--pkgs/applications/editors/eclipse/default.nix10
-rw-r--r--pkgs/applications/editors/emacs-22/default.nix3
-rw-r--r--pkgs/applications/editors/emacs-22/makefile-pwd.patch129
-rw-r--r--pkgs/applications/editors/emacs-modes/bbdb/builder.sh12
-rw-r--r--pkgs/applications/editors/emacs-modes/bbdb/default.nix22
-rw-r--r--pkgs/applications/editors/emacs-modes/bbdb/install-infodir.patch28
-rw-r--r--pkgs/applications/editors/joe/default.nix14
-rw-r--r--pkgs/applications/editors/nano/default.nix32
-rw-r--r--pkgs/applications/editors/nedit/default.nix4
-rw-r--r--pkgs/applications/editors/vim-diet/default.nix4
-rw-r--r--pkgs/applications/editors/vim/configurable.nix72
-rw-r--r--pkgs/applications/editors/vim/default.nix18
-rw-r--r--pkgs/applications/graphics/ImageMagick/6.3.8-5.nix26
-rw-r--r--pkgs/applications/graphics/ImageMagick/default.nix23
-rw-r--r--pkgs/applications/graphics/PythonMagick/default.nix3
-rw-r--r--pkgs/applications/graphics/dia/default.nix1
-rw-r--r--pkgs/applications/graphics/exrdisplay/default.nix27
-rw-r--r--pkgs/applications/graphics/f-spot/default.nix4
-rw-r--r--pkgs/applications/graphics/gimp/default.nix6
-rw-r--r--pkgs/applications/graphics/gocr/0.44.nix5
-rw-r--r--pkgs/applications/graphics/gocr/default.nix2
-rw-r--r--pkgs/applications/graphics/gqview/default.nix1
-rw-r--r--pkgs/applications/graphics/inkscape/default.nix37
-rw-r--r--pkgs/applications/graphics/xara/default.nix26
-rw-r--r--pkgs/applications/graphics/xfig/builder.sh5
-rw-r--r--pkgs/applications/graphics/xfig/default.nix5
-rw-r--r--pkgs/applications/graphics/xscreensaver/5.04.nix39
-rw-r--r--pkgs/applications/jedit/default.nix28
-rw-r--r--pkgs/applications/jedit/wrapper.nix18
-rw-r--r--pkgs/applications/misc/acrobat-reader/default.nix4
-rw-r--r--pkgs/applications/misc/audio/sox/default.nix2
-rw-r--r--pkgs/applications/misc/blender/default.nix41
-rw-r--r--pkgs/applications/misc/bluez-firmware/default.nix4
-rw-r--r--pkgs/applications/misc/bluez-utils/default.nix4
-rw-r--r--pkgs/applications/misc/d4x/default.nix10
-rw-r--r--pkgs/applications/misc/djvulibre/default.nix6
-rw-r--r--pkgs/applications/misc/fetchmail/default.nix9
-rw-r--r--pkgs/applications/misc/fetchmail/security-fix.patch11
-rw-r--r--pkgs/applications/misc/flite/default.nix8
-rw-r--r--pkgs/applications/misc/freemind/default.nix45
-rw-r--r--pkgs/applications/misc/gkrellm/default.nix33
-rw-r--r--pkgs/applications/misc/gphoto2/default.nix18
-rw-r--r--pkgs/applications/misc/gv/default.nix4
-rw-r--r--pkgs/applications/misc/hello/ex-1/default.nix1
-rw-r--r--pkgs/applications/misc/lyx/default.nix18
-rw-r--r--pkgs/applications/misc/maxima/default.nix7
-rw-r--r--pkgs/applications/misc/mrxvt/default.nix4
-rw-r--r--pkgs/applications/misc/pgadmin/default.nix18
-rw-r--r--pkgs/applications/misc/pinfo/default.nix12
-rw-r--r--pkgs/applications/misc/procmail/default.nix3
-rw-r--r--pkgs/applications/misc/pstree/default.nix7
-rw-r--r--pkgs/applications/misc/qgis_svn/default.nix74
-rw-r--r--pkgs/applications/misc/rxvt/default.nix8
-rw-r--r--pkgs/applications/misc/rxvt_unicode/default.nix19
-rw-r--r--pkgs/applications/misc/sbagen/default.nix6
-rw-r--r--pkgs/applications/misc/synergy/default.nix12
-rw-r--r--pkgs/applications/misc/wordnet/default.nix25
-rw-r--r--pkgs/applications/misc/xchm/default.nix1
-rw-r--r--pkgs/applications/misc/xpdf/default.nix1
-rw-r--r--pkgs/applications/misc/xpdf/xpdf-3.02-protection.patch74
-rw-r--r--pkgs/applications/misc/xterm/default.nix14
-rw-r--r--pkgs/applications/networking/browsers/elinks/default.nix6
-rw-r--r--pkgs/applications/networking/browsers/firefox-3/binary.nix55
-rw-r--r--pkgs/applications/networking/browsers/firefox-3/builder.sh30
-rw-r--r--pkgs/applications/networking/browsers/firefox-3/default.nix64
-rw-r--r--pkgs/applications/networking/browsers/firefox-wrapper/builder.sh2
-rw-r--r--pkgs/applications/networking/browsers/firefox-wrapper/default.nix4
-rw-r--r--pkgs/applications/networking/browsers/firefox/default.nix7
-rw-r--r--pkgs/applications/networking/browsers/mozilla-plugins/flashplayer-9/default.nix18
-rw-r--r--pkgs/applications/networking/browsers/mozilla-plugins/mplayerplug-in/default.nix6
-rw-r--r--pkgs/applications/networking/browsers/mozilla/default.nix3
-rw-r--r--pkgs/applications/networking/browsers/opera/builder.sh11
-rw-r--r--pkgs/applications/networking/browsers/opera/default.nix33
-rw-r--r--pkgs/applications/networking/browsers/w3m/default.nix4
-rw-r--r--pkgs/applications/networking/instant-messengers/amsn/default.nix4
-rw-r--r--pkgs/applications/networking/instant-messengers/bitlbee/default.nix17
-rw-r--r--pkgs/applications/networking/instant-messengers/pidgin-plugins/otr/default.nix1
-rw-r--r--pkgs/applications/networking/instant-messengers/pidgin-plugins/pidgin-latex/default.nix1
-rw-r--r--pkgs/applications/networking/instant-messengers/pidgin/default.nix7
-rw-r--r--pkgs/applications/networking/instant-messengers/teamspeak/client.nix71
-rw-r--r--pkgs/applications/networking/irc/chatzilla/default.nix6
-rw-r--r--pkgs/applications/networking/irc/irssi/default.nix10
-rw-r--r--pkgs/applications/networking/irc/xchat/default.nix10
-rw-r--r--pkgs/applications/networking/mailreaders/mutt/default.nix4
-rw-r--r--pkgs/applications/networking/mailreaders/sylpheed/default.nix6
-rw-r--r--pkgs/applications/networking/mailreaders/thunderbird-1.x/builder.sh30
-rw-r--r--pkgs/applications/networking/mailreaders/thunderbird-1.x/default.nix47
-rw-r--r--pkgs/applications/networking/mailreaders/thunderbird-2.x/default.nix6
-rw-r--r--pkgs/applications/networking/msmtp/default.nix8
-rw-r--r--pkgs/applications/networking/remote/rdesktop/default.nix20
-rw-r--r--pkgs/applications/networking/skype/default.nix10
-rw-r--r--pkgs/applications/networking/sniffers/wireshark/default.nix6
-rw-r--r--pkgs/applications/networking/sync/unison/default.nix22
-rw-r--r--pkgs/applications/office/openoffice/builder.sh2
-rw-r--r--pkgs/applications/office/openoffice/default.nix29
-rw-r--r--pkgs/applications/office/openoffice/libawt_problem10
-rw-r--r--pkgs/applications/version-management/arch/configure-tmpdir.patch11
-rw-r--r--pkgs/applications/version-management/arch/default.nix29
-rw-r--r--pkgs/applications/version-management/bazaar/default.nix22
-rw-r--r--pkgs/applications/version-management/cvs2svn/default.nix28
-rw-r--r--pkgs/applications/version-management/darcs_2_pre.nix16
-rw-r--r--pkgs/applications/version-management/git/default.nix33
-rw-r--r--pkgs/applications/version-management/mercurial/default.nix29
-rw-r--r--pkgs/applications/version-management/monotone/default.nix10
-rw-r--r--pkgs/applications/version-management/subversion-1.4.x/builder.sh12
-rw-r--r--pkgs/applications/version-management/subversion-1.4.x/default.nix18
-rw-r--r--pkgs/applications/version-management/subversion-1.4.x/subversion-respect_CPPFLAGS_in_perl_bindings.patch22
-rw-r--r--pkgs/applications/video/kino/default.nix90
-rw-r--r--pkgs/applications/video/vlc/default.nix7
-rw-r--r--pkgs/applications/video/xine-ui/default.nix9
-rw-r--r--pkgs/applications/virtualization/qemu/0.9.0.nix27
-rw-r--r--pkgs/applications/virtualization/qemu/linux-img/0.2.nix28
-rw-r--r--pkgs/applications/virtualization/virtualbox/1.5.2.nix22
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/bcop/0.6.0.nix6
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/bcop/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/ccsm/0.6.0.nix5
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/ccsm/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/compiz-manager/0.6.0.nix5
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/compiz-manager/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/compizconfig-python/0.6.0.nix5
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/compizconfig-python/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/config-backend/0.6.0.nix5
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/config-backend/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/default.nix17
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/extra/0.6.0.nix5
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/extra/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/general-dependencies.nix4
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/libcompizconfig/0.6.0.nix5
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/libcompizconfig/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/main/0.6.0.nix5
-rw-r--r--pkgs/applications/window-managers/compiz-fusion/main/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz/0.6.2.nix12
-rw-r--r--pkgs/applications/window-managers/compiz/default.nix2
-rw-r--r--pkgs/applications/window-managers/compiz/extra.nix2
-rw-r--r--pkgs/applications/window-managers/fbpanel/4.12.nix23
-rw-r--r--pkgs/applications/window-managers/xmonad/default.nix42
-rw-r--r--pkgs/build-support/fetchcvs/builder.sh13
-rw-r--r--pkgs/build-support/fetchcvs/default.nix12
-rw-r--r--pkgs/build-support/fetchsvn/builder.sh2
-rw-r--r--pkgs/build-support/fetchsvn/default.nix9
-rw-r--r--pkgs/build-support/fetchurl/mirrors.nix62
-rw-r--r--pkgs/build-support/gcc-wrapper/builder.sh27
-rw-r--r--pkgs/build-support/make-wrapper/make-wrapper.sh19
-rw-r--r--pkgs/build-support/substitute/substitute-all.sh4
-rw-r--r--pkgs/data/documentation/man-pages/default.nix11
-rw-r--r--pkgs/data/fonts/fontWrap/default.nix28
-rw-r--r--pkgs/data/fonts/freefont-ttf/default.nix8
-rw-r--r--pkgs/data/misc/shared-mime-info/0.22.nix2
-rw-r--r--pkgs/data/misc/shared-mime-info/0.23.nix2
-rw-r--r--pkgs/data/misc/shared-mime-info/common.nix16
-rw-r--r--pkgs/data/misc/shared-mime-info/default.nix12
-rw-r--r--pkgs/data/misc/xkeyboard-config/0.9.nix23
-rw-r--r--pkgs/data/misc/xkeyboard-config/1.2.nix22
-rw-r--r--pkgs/data/misc/xkeyboard-config/default.nix5
-rw-r--r--pkgs/data/misc/xkeyboard-config/level3-deadkeys-us-intl95
-rw-r--r--pkgs/desktops/gnome/default.nix14
-rw-r--r--pkgs/desktops/gnome/gnome-doc-utils.nix17
-rw-r--r--pkgs/desktops/gnome/gnome-vfs.nix7
-rw-r--r--pkgs/desktops/gnome/gtksourceview.nix2
-rwxr-xr-xpkgs/desktops/kde-4/base/builder.sh (renamed from pkgs/desktops/kde-4/kdebase/builder.sh)11
-rw-r--r--pkgs/desktops/kde-4/base/default.nix14
-rw-r--r--pkgs/desktops/kde-4/decibel/default.nix11
-rw-r--r--pkgs/desktops/kde-4/default.nix35
-rw-r--r--pkgs/desktops/kde-4/edu/default.nix20
-rw-r--r--pkgs/desktops/kde-4/edu/myCmakeFiles/CheckBoostAndPythonCompatible.cmake38
-rw-r--r--pkgs/desktops/kde-4/edu/myCmakeFiles/FindBoostPython.cmake90
-rw-r--r--pkgs/desktops/kde-4/edu/myCmakeFiles/FindLibfacile.cmake45
-rw-r--r--pkgs/desktops/kde-4/edu/myCmakeFiles/PythonLibsUtils.cmake46
-rw-r--r--pkgs/desktops/kde-4/extragear/default.nix14
-rw-r--r--pkgs/desktops/kde-4/games/default.nix12
-rw-r--r--pkgs/desktops/kde-4/graphics/default.nix13
-rw-r--r--pkgs/desktops/kde-4/kdebase/default.nix55
-rw-r--r--pkgs/desktops/kde-4/kdelibs/default.nix48
-rwxr-xr-xpkgs/desktops/kde-4/kdepim/builder.sh18
-rw-r--r--pkgs/desktops/kde-4/kdepim/default.nix55
-rw-r--r--pkgs/desktops/kde-4/kdepimlibs/default.nix48
-rw-r--r--pkgs/desktops/kde-4/libs/FindIlmBase.cmake74
-rw-r--r--pkgs/desktops/kde-4/libs/FindOpenEXR.cmake68
-rw-r--r--pkgs/desktops/kde-4/libs/default.nix27
-rwxr-xr-xpkgs/desktops/kde-4/libs/setup.sh5
-rw-r--r--pkgs/desktops/kde-4/multimedia/default.nix13
-rw-r--r--pkgs/desktops/kde-4/network/default.nix12
-rwxr-xr-xpkgs/desktops/kde-4/pim/builder.sh10
-rw-r--r--pkgs/desktops/kde-4/pim/default.nix15
-rw-r--r--pkgs/desktops/kde-4/pimlibs/default.nix12
-rwxr-xr-xpkgs/desktops/kde-4/runtime/builder.sh12
-rw-r--r--pkgs/desktops/kde-4/runtime/default.nix15
-rw-r--r--pkgs/desktops/kde-4/support/akode.nix7
-rw-r--r--pkgs/desktops/kde-4/support/default.nix22
-rw-r--r--pkgs/desktops/kde-4/support/eigen.nix7
-rw-r--r--pkgs/desktops/kde-4/support/gmm.nix7
-rw-r--r--pkgs/desktops/kde-4/support/qca.nix8
-rw-r--r--pkgs/desktops/kde-4/support/qimageblitz.nix7
-rw-r--r--pkgs/desktops/kde-4/support/soprano.nix8
-rw-r--r--pkgs/desktops/kde-4/support/strigi.nix9
-rw-r--r--pkgs/desktops/kde-4/support/taglib.nix7
-rw-r--r--pkgs/desktops/kde-4/toys/default.nix12
-rw-r--r--pkgs/desktops/kde-4/utils/default.nix13
-rwxr-xr-xpkgs/desktops/kde-4/workspace/builder.sh12
-rw-r--r--pkgs/desktops/kde-4/workspace/default.nix15
-rw-r--r--pkgs/development/compilers/bigloo/default.nix130
-rw-r--r--pkgs/development/compilers/fpc/binary.nix7
-rw-r--r--pkgs/development/compilers/fpc/default.nix8
-rw-r--r--pkgs/development/compilers/gcc-3.4/builder.sh12
-rw-r--r--pkgs/development/compilers/gcc-3.4/default.nix19
-rw-r--r--pkgs/development/compilers/gcc-4.1/default.nix12
-rw-r--r--pkgs/development/compilers/gcc-4.2/builder.sh25
-rw-r--r--pkgs/development/compilers/gcc-4.2/default.nix20
-rw-r--r--pkgs/development/compilers/ghc-6.6.1/builder.sh26
-rw-r--r--pkgs/development/compilers/ghc-6.6.1/default.nix31
-rw-r--r--pkgs/development/compilers/ghc-6.8/builder.sh26
-rw-r--r--pkgs/development/compilers/ghc-6.8/default.nix39
-rw-r--r--pkgs/development/compilers/ghc-6.8/setup-hook.sh2
-rw-r--r--pkgs/development/compilers/ghc-6.8/x86_64-linux_patch24
-rw-r--r--pkgs/development/compilers/ghc/boot.nix66
-rw-r--r--pkgs/development/compilers/ghc/boot.sh10
-rw-r--r--pkgs/development/compilers/ghc/createGhcWrapper/default.nix17
-rw-r--r--pkgs/development/compilers/ghcs/default.nix198
-rw-r--r--pkgs/development/compilers/ghcs/nix_ghc_pkg_tool.hs48
-rw-r--r--pkgs/development/compilers/ghcs/splitpackagedb.hs25
-rw-r--r--pkgs/development/compilers/gwt/builder.sh33
-rw-r--r--pkgs/development/compilers/gwt/default.nix14
-rw-r--r--pkgs/development/compilers/java-front/builder.sh4
-rw-r--r--pkgs/development/compilers/java-front/default.nix14
-rw-r--r--pkgs/development/compilers/jdk/builder.sh1
-rw-r--r--pkgs/development/compilers/jdk/default-5.nix9
-rw-r--r--pkgs/development/compilers/jdk/jdk5-sun-linux.nix23
-rw-r--r--pkgs/development/compilers/jdk/jdk6-linux.nix10
-rw-r--r--pkgs/development/compilers/ocaml/3.08.0.nix (renamed from pkgs/development/compilers/ocaml/ocaml-3.08.0.nix)2
-rw-r--r--pkgs/development/compilers/ocaml/3.09.1.nix (renamed from pkgs/development/compilers/ocaml/ocaml-3.09.1.nix)2
-rw-r--r--pkgs/development/compilers/ocaml/3.10.0.nix23
-rw-r--r--pkgs/development/compilers/ocaml/default.nix8
-rw-r--r--pkgs/development/compilers/qi/9.1.nix5
-rw-r--r--pkgs/development/compilers/qi/default.nix2
-rw-r--r--pkgs/development/compilers/roadsend/default.nix33
-rw-r--r--pkgs/development/compilers/strategoxt/strategoxt-0.17.nix15
-rw-r--r--pkgs/development/compilers/webdsl/builder.sh8
-rw-r--r--pkgs/development/compilers/webdsl/default.nix14
-rw-r--r--pkgs/development/guile-modules/guile-lib/default.nix38
-rw-r--r--pkgs/development/interpreters/clisp/builder.sh22
-rw-r--r--pkgs/development/interpreters/clisp/default.nix43
-rw-r--r--pkgs/development/interpreters/erlang/R11B-5.nix12
-rw-r--r--pkgs/development/interpreters/erlang/R12B-1.nix12
-rw-r--r--pkgs/development/interpreters/guile/default.nix28
-rw-r--r--pkgs/development/interpreters/guile/setup-hook.sh8
-rw-r--r--pkgs/development/interpreters/lua-5/default.nix2
-rw-r--r--pkgs/development/interpreters/perl/perl-5.10.nix21
-rw-r--r--pkgs/development/interpreters/perl/setup-hook.sh2
-rw-r--r--pkgs/development/interpreters/php_configurable/default.nix97
-rw-r--r--pkgs/development/interpreters/pyrex/0.9.6.nix5
-rw-r--r--pkgs/development/interpreters/pyrex/default.nix2
-rw-r--r--pkgs/development/interpreters/python/2.4.nix52
-rw-r--r--pkgs/development/interpreters/python/2.5/default.nix2
-rw-r--r--pkgs/development/interpreters/python/2.5/setup-hook.sh2
-rw-r--r--pkgs/development/interpreters/python/default.nix58
-rw-r--r--pkgs/development/interpreters/tcl/default.nix6
-rw-r--r--pkgs/development/libraries/SDL_image/default.nix24
-rw-r--r--pkgs/development/libraries/SDL_mixer/default.nix25
-rw-r--r--pkgs/development/libraries/SDL_net/default.nix22
-rw-r--r--pkgs/development/libraries/SDL_ttf/default.nix9
-rw-r--r--pkgs/development/libraries/a52dec/default.nix14
-rw-r--r--pkgs/development/libraries/acl/acl-2.2.45-patch222
-rw-r--r--pkgs/development/libraries/acl/builder.sh (renamed from pkgs/development/libraries/tk/builder.sh)6
-rw-r--r--pkgs/development/libraries/acl/default.nix14
-rw-r--r--pkgs/development/libraries/apr-util/default.nix26
-rw-r--r--pkgs/development/libraries/apr/default.nix12
-rw-r--r--pkgs/development/libraries/aspell/default.nix14
-rw-r--r--pkgs/development/libraries/aspell/dict-path.patch30
-rw-r--r--pkgs/development/libraries/aspell/dictionaries.nix17
-rw-r--r--pkgs/development/libraries/aterm/2.4.2-fixes.nix1
-rw-r--r--pkgs/development/libraries/aterm/2.5.nix14
-rw-r--r--pkgs/development/libraries/attr/builder.sh2
-rw-r--r--pkgs/development/libraries/audiofile/default.nix6
-rw-r--r--pkgs/development/libraries/avahi/0.6.21.nix2
-rw-r--r--pkgs/development/libraries/avahi/0.6.22.nix2
-rw-r--r--pkgs/development/libraries/avahi/common.nix18
-rw-r--r--pkgs/development/libraries/avahi/default.nix14
-rw-r--r--pkgs/development/libraries/boehm-gc/default.nix10
-rw-r--r--pkgs/development/libraries/boost/default.nix1
-rw-r--r--pkgs/development/libraries/boost/gcc-4.2.patch11
-rw-r--r--pkgs/development/libraries/cairomm/default.nix15
-rw-r--r--pkgs/development/libraries/cfitsio/default.nix13
-rw-r--r--pkgs/development/libraries/chmlib/builder.sh19
-rw-r--r--pkgs/development/libraries/chmlib/default.nix17
-rw-r--r--pkgs/development/libraries/clucene-contrib/default.nix18
-rw-r--r--pkgs/development/libraries/clucene-core/default.nix25
-rw-r--r--pkgs/development/libraries/coredumper/default.nix6
-rw-r--r--pkgs/development/libraries/cracklib/default.nix6
-rw-r--r--pkgs/development/libraries/ctl/default.nix23
-rw-r--r--pkgs/development/libraries/db4/db4-4.4.nix5
-rw-r--r--pkgs/development/libraries/dbus-glib/default.nix23
-rw-r--r--pkgs/development/libraries/dbus/default.nix52
-rw-r--r--pkgs/development/libraries/dbus_x/default.nix13
-rw-r--r--pkgs/development/libraries/enchant/1.3.0.nix14
-rw-r--r--pkgs/development/libraries/enchant/default.nix10
-rw-r--r--pkgs/development/libraries/expat/default.nix6
-rw-r--r--pkgs/development/libraries/facile/default.nix19
-rw-r--r--pkgs/development/libraries/fcgi/default.nix18
-rw-r--r--pkgs/development/libraries/ffmpeg_svn_snapshot/default.nix6
-rw-r--r--pkgs/development/libraries/fftw/default.nix5
-rw-r--r--pkgs/development/libraries/fltk/default.nix72
-rw-r--r--pkgs/development/libraries/freeglut/default.nix1
-rw-r--r--pkgs/development/libraries/freeglut/freeglut-gcc-4.2.patch13
-rw-r--r--pkgs/development/libraries/gamin/default.nix12
-rw-r--r--pkgs/development/libraries/geos/default.nix42
-rw-r--r--pkgs/development/libraries/gettext/0.14.6.nix3
-rw-r--r--pkgs/development/libraries/gettext/0.15.nix3
-rw-r--r--pkgs/development/libraries/gettext/0.16.x.nix3
-rw-r--r--pkgs/development/libraries/gettext/default.nix8
-rw-r--r--pkgs/development/libraries/giflib/default.nix10
-rw-r--r--pkgs/development/libraries/giflib/libungif.nix (renamed from pkgs/development/libraries/libungif/default.nix)2
-rw-r--r--pkgs/development/libraries/glew/default.nix19
-rw-r--r--pkgs/development/libraries/glibc-2.5/builder.sh (renamed from pkgs/development/libraries/glibc/builder.sh)0
-rw-r--r--pkgs/development/libraries/glibc-2.5/default.nix (renamed from pkgs/development/libraries/glibc/default.nix)0
-rw-r--r--pkgs/development/libraries/glibc-2.5/glibc-getcwd-param-MAX.patch (renamed from pkgs/development/libraries/glibc-nptl/glibc-getcwd-param-MAX.patch)0
-rw-r--r--pkgs/development/libraries/glibc-2.5/glibc-pwd.patch (renamed from pkgs/development/libraries/glibc-nptl/glibc-pwd.patch)0
-rw-r--r--pkgs/development/libraries/glibc-2.7/builder.sh (renamed from pkgs/development/libraries/glibc-nptl/builder.sh)5
-rw-r--r--pkgs/development/libraries/glibc-2.7/default.nix (renamed from pkgs/development/libraries/glibc-nptl/default.nix)2
-rw-r--r--pkgs/development/libraries/glibc-2.7/glibc-getcwd-param-MAX.patch (renamed from pkgs/development/libraries/glibc/glibc-getcwd-param-MAX.patch)0
-rw-r--r--pkgs/development/libraries/glibc-2.7/glibc-pwd.patch (renamed from pkgs/development/libraries/glibc/glibc-pwd.patch)0
-rw-r--r--pkgs/development/libraries/gmp/default.nix15
-rw-r--r--pkgs/development/libraries/gpgme/default.nix4
-rw-r--r--pkgs/development/libraries/gsl/default.nix15
-rw-r--r--pkgs/development/libraries/gtk-libs-2.10/default.nix26
-rw-r--r--pkgs/development/libraries/gtk-libs-2.10/gtk+/default.nix22
-rw-r--r--pkgs/development/libraries/gtk-libs-2.2/atk/default.nix13
-rw-r--r--pkgs/development/libraries/gtk-libs-2.2/glib/default.nix12
-rw-r--r--pkgs/development/libraries/gtk-libs-2.2/gtk+/default.nix21
-rw-r--r--pkgs/development/libraries/gtk-libs-2.2/pango/default.nix14
-rw-r--r--pkgs/development/libraries/gtk-libs-2.4/atk/default.nix13
-rw-r--r--pkgs/development/libraries/gtk-libs-2.4/default.nix23
-rw-r--r--pkgs/development/libraries/gtk-libs-2.4/glib/default.nix12
-rw-r--r--pkgs/development/libraries/gtk-libs-2.4/gtk+/default.nix21
-rw-r--r--pkgs/development/libraries/gtk-libs-2.4/pango/default.nix14
-rw-r--r--pkgs/development/libraries/gtk-libs-2.6/default.nix23
-rw-r--r--pkgs/development/libraries/gtk-libs/1.x/default.nix (renamed from pkgs/development/libraries/gtk-libs-1.x/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/1.x/gdk-pixbuf/default.nix (renamed from pkgs/development/libraries/gtk-libs-1.x/gdk-pixbuf/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/1.x/glib/default.nix (renamed from pkgs/development/libraries/gtk-libs-1.x/glib/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/1.x/glib/gcc34.patch (renamed from pkgs/development/libraries/gtk-libs-1.x/glib/gcc34.patch)0
-rw-r--r--pkgs/development/libraries/gtk-libs/1.x/gtk+/builder.sh (renamed from pkgs/development/libraries/gtk-libs-1.x/gtk+/builder.sh)0
-rw-r--r--pkgs/development/libraries/gtk-libs/1.x/gtk+/default.nix (renamed from pkgs/development/libraries/gtk-libs-1.x/gtk+/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.10/atk/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.10/atk/default.nix)4
-rw-r--r--pkgs/development/libraries/gtk-libs/2.10/default.nix16
-rw-r--r--pkgs/development/libraries/gtk-libs/2.10/glib/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.10/glib/default.nix)4
-rw-r--r--pkgs/development/libraries/gtk-libs/2.10/glibmm/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.10/glibmm/default.nix)5
-rw-r--r--pkgs/development/libraries/gtk-libs/2.10/gtk+/default.nix13
-rw-r--r--pkgs/development/libraries/gtk-libs/2.10/gtkmm/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.10/gtkmm/default.nix)5
-rw-r--r--pkgs/development/libraries/gtk-libs/2.10/pango/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.10/pango/default.nix)8
-rw-r--r--pkgs/development/libraries/gtk-libs/2.6/atk/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.6/atk/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.6/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.2/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.6/glib/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.6/glib/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.6/glibmm/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.6/glibmm/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.6/gtk+/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.6/gtk+/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.6/gtkmm/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.6/gtkmm/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.6/pango/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.6/pango/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.8/atk/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.8/atk/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.8/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.8/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.8/glib/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.8/glib/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.8/glibmm/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.8/glibmm/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.8/gtk+/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.8/gtk+/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.8/gtkmm/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.8/gtkmm/default.nix)0
-rw-r--r--pkgs/development/libraries/gtk-libs/2.8/pango/default.nix (renamed from pkgs/development/libraries/gtk-libs-2.8/pango/default.nix)0
-rw-r--r--pkgs/development/libraries/haskell/Crypto/default.nix11
-rw-r--r--pkgs/development/libraries/haskell/HDBC/HDBC-1.1.4.nix10
-rw-r--r--pkgs/development/libraries/haskell/HDBC/HDBC-postgresql-1.1.4.0.nix12
-rw-r--r--pkgs/development/libraries/haskell/HDBC/HDBC-sqlite3-1.1.4.0.nix12
-rw-r--r--pkgs/development/libraries/haskell/X11/default.nix13
-rw-r--r--pkgs/development/libraries/haskell/binary/default.nix11
-rw-r--r--pkgs/development/libraries/haskell/cabal/cabal.nix95
-rw-r--r--pkgs/development/libraries/haskell/gtk2hs/default.nix20
-rw-r--r--pkgs/development/libraries/haskell/pcre-light/default.nix12
-rw-r--r--pkgs/development/libraries/haskell/uulib-ghc-6.6/builder.sh21
-rw-r--r--pkgs/development/libraries/haskell/uulib-ghc-6.6/default.nix11
-rw-r--r--pkgs/development/libraries/haskell/uulib/builder.sh51
-rw-r--r--pkgs/development/libraries/haskell/uulib/default.nix18
-rw-r--r--pkgs/development/libraries/haskell/vty/default.nix13
-rw-r--r--pkgs/development/libraries/haskell/zlib/default.nix11
-rw-r--r--pkgs/development/libraries/ilbc/default.nix17
-rw-r--r--pkgs/development/libraries/ilmbase/default.nix6
-rw-r--r--pkgs/development/libraries/indilib/default.nix16
-rw-r--r--pkgs/development/libraries/iniparser/default.nix34
-rw-r--r--pkgs/development/libraries/iniparser/no-usr.patch14
-rw-r--r--pkgs/development/libraries/jasper/default.nix18
-rw-r--r--pkgs/development/libraries/kerberos/heimdal.nix12
-rw-r--r--pkgs/development/libraries/libaal/default.nix19
-rw-r--r--pkgs/development/libraries/libao/default.nix19
-rw-r--r--pkgs/development/libraries/libarchive/2.4.11.nix2
-rw-r--r--pkgs/development/libraries/libarchive/2.4.12.nix2
-rw-r--r--pkgs/development/libraries/libarchive/common.nix18
-rw-r--r--pkgs/development/libraries/libassuan/default.nix16
-rw-r--r--pkgs/development/libraries/libavc1394/default.nix18
-rw-r--r--pkgs/development/libraries/libcaca/default.nix6
-rw-r--r--pkgs/development/libraries/libdbi-drivers/0.8.2-1.nix40
-rw-r--r--pkgs/development/libraries/libdbi/0.8.2.nix22
-rw-r--r--pkgs/development/libraries/libdv/default.nix30
-rw-r--r--pkgs/development/libraries/libexif/default.nix12
-rw-r--r--pkgs/development/libraries/libextractor/0.5.18.nix22
-rw-r--r--pkgs/development/libraries/libgcrypt/default.nix11
-rw-r--r--pkgs/development/libraries/libgphoto2/default.nix17
-rw-r--r--pkgs/development/libraries/libgsf/default.nix19
-rw-r--r--pkgs/development/libraries/libid3tag/default.nix17
-rw-r--r--pkgs/development/libraries/libiec61883/default.nix18
-rw-r--r--pkgs/development/libraries/libjingle/0.3.11.nix10
-rw-r--r--pkgs/development/libraries/libjingle/0.4.0.nix10
-rw-r--r--pkgs/development/libraries/libksba/default.nix19
-rw-r--r--pkgs/development/libraries/libmad/default.nix11
-rw-r--r--pkgs/development/libraries/libnotify/default.nix17
-rw-r--r--pkgs/development/libraries/libnova/default.nix15
-rw-r--r--pkgs/development/libraries/liboop/default.nix17
-rw-r--r--pkgs/development/libraries/libpcap/default.nix6
-rw-r--r--pkgs/development/libraries/libpng/default.nix6
-rw-r--r--pkgs/development/libraries/libraw1394/default.nix15
-rw-r--r--pkgs/development/libraries/libsamplerate/default.nix2
-rw-r--r--pkgs/development/libraries/libsexy/default.nix17
-rw-r--r--pkgs/development/libraries/libsigsegv/2.5.nix14
-rw-r--r--pkgs/development/libraries/libsigsegv/default.nix9
-rw-r--r--pkgs/development/libraries/libtheora/default.nix6
-rw-r--r--pkgs/development/libraries/libunwind/default.nix14
-rw-r--r--pkgs/development/libraries/libvorbis/default.nix6
-rw-r--r--pkgs/development/libraries/libwmf/default.nix11
-rw-r--r--pkgs/development/libraries/libwpd/default.nix11
-rw-r--r--pkgs/development/libraries/libxklavier/3.4.nix21
-rw-r--r--pkgs/development/libraries/log4cxx/default.nix2
-rw-r--r--pkgs/development/libraries/loudmouth/default.nix14
-rw-r--r--pkgs/development/libraries/mediastreamer/2.2.0-cvs20080207.nix22
-rw-r--r--pkgs/development/libraries/mediastreamer/h264.patch12
-rw-r--r--pkgs/development/libraries/mediastreamer/plugins.patch49
-rw-r--r--pkgs/development/libraries/msilbc/2.0.0.nix24
-rw-r--r--pkgs/development/libraries/openalSoft/default.nix21
-rw-r--r--pkgs/development/libraries/openexr/default.nix10
-rw-r--r--pkgs/development/libraries/openexr_ctl/default.nix24
-rw-r--r--pkgs/development/libraries/openssl/default.nix3
-rw-r--r--pkgs/development/libraries/ortp/0.13.1.nix16
-rw-r--r--pkgs/development/libraries/ortp/0.7.1.nix16
-rw-r--r--pkgs/development/libraries/pcre/default.nix20
-rw-r--r--pkgs/development/libraries/popt/popt-1.7.nix5
-rw-r--r--pkgs/development/libraries/proj.4/default.nix15
-rw-r--r--pkgs/development/libraries/pth/default.nix14
-rwxr-xr-xpkgs/development/libraries/qt-4/builder.sh9
-rw-r--r--pkgs/development/libraries/qt-4/default.nix14
-rw-r--r--pkgs/development/libraries/readline/readline5.nix6
-rw-r--r--pkgs/development/libraries/readline/shobj-darwin.patch11
-rw-r--r--pkgs/development/libraries/redland/default.nix14
-rw-r--r--pkgs/development/libraries/speex/default.nix6
-rw-r--r--pkgs/development/libraries/strigi/default.nix20
-rw-r--r--pkgs/development/libraries/t1lib/default.nix9
-rw-r--r--pkgs/development/libraries/tapioca-qt/default.nix16
-rw-r--r--pkgs/development/libraries/telepathy-gabble/default.nix17
-rw-r--r--pkgs/development/libraries/telepathy-glib/default.nix17
-rw-r--r--pkgs/development/libraries/telepathy-qt/default.nix16
-rw-r--r--pkgs/development/libraries/tk/8.4.16.nix18
-rw-r--r--pkgs/development/libraries/tk/default.nix12
-rw-r--r--pkgs/development/libraries/xine-lib/default.nix36
-rw-r--r--pkgs/development/libraries/xine-lib/xine-lib-linux-headers-2.6.23.patch22
-rw-r--r--pkgs/development/perl-modules/DB_File/default.nix11
-rw-r--r--pkgs/development/perl-modules/DB_File/hook.sh11
-rw-r--r--pkgs/development/python-modules/ZopeInterface/default.nix6
-rw-r--r--pkgs/development/python-modules/pil/default.nix12
-rw-r--r--pkgs/development/python-modules/pygame/default.nix12
-rw-r--r--pkgs/development/python-modules/twisted/default.nix6
-rwxr-xr-xpkgs/development/tools/build-managers/cmake/setup-hook.sh48
-rw-r--r--pkgs/development/tools/build-managers/gnumake/log.patch27
-rw-r--r--pkgs/development/tools/documentation/haddock/default.nix11
-rw-r--r--pkgs/development/tools/guile/guile-lint/default.nix26
-rw-r--r--pkgs/development/tools/haskell/uuagc/default.nix26
-rw-r--r--pkgs/development/tools/misc/automake/setup-hook.sh2
-rw-r--r--pkgs/development/tools/misc/avrdude/default.nix2
-rw-r--r--pkgs/development/tools/misc/ccache/default.nix15
-rw-r--r--pkgs/development/tools/misc/elfutils/0.127.nix (renamed from pkgs/development/tools/misc/elfutils/default.nix)5
-rw-r--r--pkgs/development/tools/misc/elfutils/0.131.nix9
-rw-r--r--pkgs/development/tools/misc/gdb/default.nix10
-rw-r--r--pkgs/development/tools/misc/hasktags/default.nix24
-rw-r--r--pkgs/development/tools/misc/indent/2.2.9.nix29
-rw-r--r--pkgs/development/tools/misc/intltool/0.36.2.nix8
-rw-r--r--pkgs/development/tools/misc/intltool/default.nix2
-rw-r--r--pkgs/development/tools/misc/libtool/default.nix8
-rw-r--r--pkgs/development/tools/misc/ltrace/0.5-3deb.nix (renamed from pkgs/development/tools/misc/ltrace/default.nix)16
-rw-r--r--pkgs/development/tools/misc/pkgconfig/default.nix8
-rw-r--r--pkgs/development/tools/misc/pkgconfig/setup-hook.sh2
-rw-r--r--pkgs/development/tools/misc/strace/default.nix6
-rw-r--r--pkgs/development/tools/misc/swig/default.nix6
-rw-r--r--pkgs/development/tools/misc/uisp/default.nix8
-rw-r--r--pkgs/development/tools/misc/valgrind/default.nix7
-rw-r--r--pkgs/development/tools/parsing/alex/default.nix12
-rw-r--r--pkgs/development/tools/parsing/bison/bison-1.875.nix4
-rw-r--r--pkgs/development/tools/parsing/flex-iputils/builder.sh10
-rw-r--r--pkgs/development/tools/parsing/flex-iputils/default.nix13
-rw-r--r--pkgs/development/tools/parsing/flex-iputils/flex-new.nix16
-rw-r--r--pkgs/development/tools/parsing/flex/flex-2.5.34.nix19
-rw-r--r--pkgs/development/tools/parsing/flex/flex-2.5.4a.nix2
-rw-r--r--pkgs/development/tools/parsing/happy/happy-1.17.nix12
-rw-r--r--pkgs/development/tools/parsing/sdf/sdf2-bundle-2.4.nix12
-rw-r--r--pkgs/development/tools/selenium/remote-control/default.nix23
-rw-r--r--pkgs/games/construo/0.2.2.nix30
-rw-r--r--pkgs/games/fsg/alt-builder.nix8
-rw-r--r--pkgs/games/orbit/1.01.nix43
-rw-r--r--pkgs/games/scummvm/default.nix6
-rw-r--r--pkgs/games/thePenguinMachine/default.nix17
-rw-r--r--pkgs/games/wesnoth/default.nix22
-rw-r--r--pkgs/lib/annotatedDerivations.nix56
-rw-r--r--pkgs/lib/default-unstable.nix429
-rw-r--r--pkgs/lib/default.nix414
-rw-r--r--pkgs/lib/strings-with-deps.nix36
-rw-r--r--pkgs/misc/emulators/wine/default.nix20
-rw-r--r--pkgs/misc/emulators/wine/opengl-child-window.patch1286
-rw-r--r--pkgs/misc/gxemul/default.nix2
-rw-r--r--pkgs/misc/maven/maven-2.nix21
-rw-r--r--pkgs/misc/ntfs-3g/default.nix9
-rw-r--r--pkgs/misc/ntfsprogs/default.nix16
-rw-r--r--pkgs/misc/screensavers/xlockmore/default.nix30
-rw-r--r--pkgs/misc/screensavers/xlockmore/makefile-libcrypt.patch11
-rw-r--r--pkgs/misc/tex/auctex/default.nix3
-rw-r--r--pkgs/misc/tex/nix/find-includes.pl1
-rw-r--r--pkgs/misc/trac/builder.sh6
-rw-r--r--pkgs/misc/trac/default.nix17
-rw-r--r--pkgs/misc/xsane/default.nix6
-rw-r--r--pkgs/os-specific/linux/alsa/library/default.nix4
-rw-r--r--pkgs/os-specific/linux/alsa/utils/default.nix4
-rw-r--r--pkgs/os-specific/linux/atheros/0.9.3.3.nix35
-rw-r--r--pkgs/os-specific/linux/atheros/r2756.nix36
-rw-r--r--pkgs/os-specific/linux/atheros/r3122.nix23
-rw-r--r--pkgs/os-specific/linux/aufs/default.nix38
-rw-r--r--pkgs/os-specific/linux/bridge_utils/default.nix19
-rw-r--r--pkgs/os-specific/linux/dietlibc/default.nix6
-rw-r--r--pkgs/os-specific/linux/dmidecode/2.9.nix23
-rw-r--r--pkgs/os-specific/linux/dvd+rw-tools/7.0.nix29
-rw-r--r--pkgs/os-specific/linux/firmware/iwlwifi-3945-ucode/default.nix19
-rw-r--r--pkgs/os-specific/linux/firmware/iwlwifi-4965-ucode/default.nix19
-rw-r--r--pkgs/os-specific/linux/firmware/zd1211/default.nix21
-rw-r--r--pkgs/os-specific/linux/fuse/builder.sh2
-rw-r--r--pkgs/os-specific/linux/fuse/default.nix18
-rw-r--r--pkgs/os-specific/linux/fxload/default.nix39
-rw-r--r--pkgs/os-specific/linux/hal/default.nix8
-rw-r--r--pkgs/os-specific/linux/iputils/builder.sh20
-rw-r--r--pkgs/os-specific/linux/iputils/default.nix2
-rw-r--r--pkgs/os-specific/linux/iputils/open-max.patch30
-rw-r--r--pkgs/os-specific/linux/iwlwifi/default.nix37
-rw-r--r--pkgs/os-specific/linux/kernel-headers/2.6.23.8.nix (renamed from pkgs/os-specific/linux/kernel-headers/2.6.23.1.nix)6
-rw-r--r--pkgs/os-specific/linux/kernel-headers/builder.sh23
-rw-r--r--pkgs/os-specific/linux/kernel-headers/default.nix21
-rw-r--r--pkgs/os-specific/linux/kernel/2.6.22-paravirt-nvidia.patch14
-rw-r--r--pkgs/os-specific/linux/kernel/acerhk/default.nix12
-rw-r--r--pkgs/os-specific/linux/kernel/config-2.6.23-i686-smp2
-rw-r--r--pkgs/os-specific/linux/kernel/linux-2.6.21_ck.nix84
-rw-r--r--pkgs/os-specific/linux/kernel/linux-2.6.22.nix4
-rw-r--r--pkgs/os-specific/linux/kernel/linux-2.6.23.nix4
-rw-r--r--pkgs/os-specific/linux/kernel/patch-2.6.21-ck15040
-rw-r--r--pkgs/os-specific/linux/kernel/patch-2.6.22-ck15167
-rw-r--r--pkgs/os-specific/linux/kqemu/1.3.0pre11.nix32
-rw-r--r--pkgs/os-specific/linux/kvm/57.nix24
-rw-r--r--pkgs/os-specific/linux/module-init-tools/aggregator.nix38
-rw-r--r--pkgs/os-specific/linux/ndiswrapper/default.nix28
-rw-r--r--pkgs/os-specific/linux/ndiswrapper/prefix.patch78
-rw-r--r--pkgs/os-specific/linux/nfs-utils/default.nix17
-rwxr-xr-xpkgs/os-specific/linux/nvidia/builder.sh170
-rw-r--r--pkgs/os-specific/linux/nvidia/default.nix42
-rw-r--r--pkgs/os-specific/linux/radeontools/default.nix8
-rw-r--r--pkgs/os-specific/linux/reiser4progs/default.nix21
-rw-r--r--pkgs/os-specific/linux/reiserfsprogs/default.nix17
-rw-r--r--pkgs/os-specific/linux/sdparm/1.02.nix22
-rw-r--r--pkgs/os-specific/linux/squashfs/default.nix6
-rw-r--r--pkgs/os-specific/linux/sysklogd/builder.sh3
-rw-r--r--pkgs/os-specific/linux/sysklogd/default.nix7
-rw-r--r--pkgs/os-specific/linux/sysklogd/sysklogd-1.4.1-asm.patch12
-rw-r--r--pkgs/os-specific/linux/sysklogd/sysklogd-1.4.1-cvs-20050525-local.diff901
-rw-r--r--pkgs/os-specific/linux/tcp-wrapper/default.nix26
-rw-r--r--pkgs/os-specific/linux/udev/default.nix24
-rw-r--r--pkgs/os-specific/linux/upstart/jobcontrol.nix15
-rw-r--r--pkgs/os-specific/linux/usbutils/default.nix10
-rw-r--r--pkgs/os-specific/linux/util-linux/default.nix6
-rw-r--r--pkgs/os-specific/linux/wis-go7007/default.nix59
-rw-r--r--pkgs/os-specific/linux/wpa_supplicant/default.nix6
-rw-r--r--pkgs/servers/fingerd/bsd-fingerd/default.nix17
-rw-r--r--pkgs/servers/fingerd/bsd-fingerd/ubuntu-0.17-9.patch67
-rw-r--r--pkgs/servers/ftp/vsftpd/default.nix20
-rw-r--r--pkgs/servers/http/apache-httpd/builder.sh29
-rw-r--r--pkgs/servers/http/apache-httpd/default.nix47
-rw-r--r--pkgs/servers/http/apache-modules/mod_python/default.nix6
-rw-r--r--pkgs/servers/http/apache-modules/tomcat-connectors/builder.sh8
-rw-r--r--pkgs/servers/http/apache-modules/tomcat-connectors/default.nix14
-rw-r--r--pkgs/servers/http/jboss/builder.sh15
-rw-r--r--pkgs/servers/http/jboss/default.nix20
-rw-r--r--pkgs/servers/http/jboss/jdbc/mysql/builder.sh5
-rw-r--r--pkgs/servers/http/jboss/jdbc/mysql/default.nix9
-rw-r--r--pkgs/servers/http/tomcat/6.0.nix15
-rw-r--r--pkgs/servers/http/tomcat/axis2/builder.sh15
-rw-r--r--pkgs/servers/http/tomcat/axis2/default.nix15
-rw-r--r--pkgs/servers/http/tomcat/builder-6.0.sh6
-rw-r--r--pkgs/servers/irc/ircd-hybrid/default.nix12
-rw-r--r--pkgs/servers/monitoring/nagios/default.nix6
-rw-r--r--pkgs/servers/monitoring/nagios/plugins/official/default.nix2
-rw-r--r--pkgs/servers/samba/default.nix21
-rw-r--r--pkgs/servers/samba/smb.conf271
-rw-r--r--pkgs/servers/sql/mysql5/default.nix7
-rw-r--r--pkgs/servers/sql/postgresql/8.2.6.nix14
-rw-r--r--pkgs/servers/sql/postgresql/8.3.0.nix14
-rw-r--r--pkgs/servers/sql/postgresql/default.nix15
-rw-r--r--pkgs/servers/squid/default.nix22
-rw-r--r--pkgs/servers/x11/xorg/default.nix26
-rwxr-xr-xpkgs/servers/x11/xorg/generate-expr-from-tarballs.pl23
-rw-r--r--pkgs/servers/xmpp/ejabberd/builder.sh9
-rw-r--r--pkgs/servers/xmpp/ejabberd/default.nix11
-rw-r--r--pkgs/shells/bash/default.nix7
-rw-r--r--pkgs/shells/tcsh/default.nix6
-rw-r--r--pkgs/shells/zsh/4.3.4.nix (renamed from pkgs/shells/zsh/default.nix)2
-rw-r--r--pkgs/shells/zsh/4.3.5.nix22
-rw-r--r--pkgs/stdenv/common-path.nix1
-rw-r--r--pkgs/stdenv/cygwin/prehook.sh2
-rw-r--r--pkgs/stdenv/generic/builder.sh29
-rw-r--r--pkgs/stdenv/generic/setup-new-2.sh878
-rw-r--r--pkgs/stdenv/generic/setup-new.sh830
-rw-r--r--pkgs/stdenv/generic/setup-sh-defs.nix902
-rw-r--r--pkgs/stdenv/generic/setup.sh362
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/i686/bunzip2bin69060 -> 0 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/i686/bzip2bin0 -> 73860 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/i686/cpbin51124 -> 50964 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/i686/curl.bz2bin147746 -> 112642 bytes
-rw-r--r--pkgs/stdenv/linux/bootstrap/i686/default.nix24
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/i686/tar.bz2bin94989 -> 95513 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/powerpc/bunzip2bin86276 -> 0 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/powerpc/bzip2bin0 -> 85816 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/powerpc/cpbin64584 -> 64700 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/powerpc/curl.bz2bin151926 -> 148830 bytes
-rw-r--r--pkgs/stdenv/linux/bootstrap/powerpc/default.nix18
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/powerpc/tar.bz2bin100601 -> 102939 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/x86_64/bunzip2bin74624 -> 0 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/x86_64/bzip2bin0 -> 75744 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/x86_64/cpbin59568 -> 59472 bytes
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/x86_64/curl.bz2bin152587 -> 119172 bytes
-rw-r--r--pkgs/stdenv/linux/bootstrap/x86_64/default.nix18
-rwxr-xr-xpkgs/stdenv/linux/bootstrap/x86_64/tar.bz2bin425936 -> 431598 bytes
-rw-r--r--pkgs/stdenv/linux/default.nix4
-rw-r--r--pkgs/stdenv/linux/make-bootstrap-tools.nix11
-rw-r--r--pkgs/stdenv/linux/make-bootstrap-tools.sh26
-rw-r--r--pkgs/stdenv/linux/scripts/unpack-curl.sh2
-rw-r--r--pkgs/stdenv/linux/scripts/unpack.sh4
-rw-r--r--pkgs/test/openftd/default.nix49
-rw-r--r--pkgs/tools/X11/xlaunch/default.nix48
-rw-r--r--pkgs/tools/X11/xmacro/default.nix9
-rw-r--r--pkgs/tools/archivers/cabextract/default.nix4
-rw-r--r--pkgs/tools/archivers/cpio/default.nix7
-rw-r--r--pkgs/tools/archivers/cpio/gnulib-futimens.patch30
-rw-r--r--pkgs/tools/archivers/cpio/symlink.patch13
-rw-r--r--pkgs/tools/archivers/gnutar/default.nix15
-rw-r--r--pkgs/tools/archivers/gnutar/gnulib-futimens.patch42
-rw-r--r--pkgs/tools/archivers/p7zip/default.nix6
-rw-r--r--pkgs/tools/archivers/sharutils/4.6.3.nix13
-rw-r--r--pkgs/tools/archivers/unzip/default.nix4
-rw-r--r--pkgs/tools/archivers/zip/default.nix6
-rw-r--r--pkgs/tools/backup/rdiff-backup/default.nix8
-rw-r--r--pkgs/tools/compression/bzip2/default.nix3
-rw-r--r--pkgs/tools/compression/gzip/default.nix9
-rw-r--r--pkgs/tools/compression/lzma/default.nix18
-rw-r--r--pkgs/tools/compression/zdelta/default.nix8
-rw-r--r--pkgs/tools/graphics/exif/default.nix6
-rw-r--r--pkgs/tools/graphics/graphviz/default.nix13
-rw-r--r--pkgs/tools/hddtemp/default.nix25
-rw-r--r--pkgs/tools/misc/coreutils/default.nix13
-rw-r--r--pkgs/tools/misc/dosfstools/2.11deb.nix33
-rw-r--r--pkgs/tools/misc/file/default.nix11
-rw-r--r--pkgs/tools/misc/findutils/default.nix11
-rw-r--r--pkgs/tools/misc/grub/default.nix24
-rw-r--r--pkgs/tools/misc/less/default.nix6
-rw-r--r--pkgs/tools/misc/man-db/default.nix32
-rw-r--r--pkgs/tools/misc/man-db/share.patch110
-rw-r--r--pkgs/tools/misc/man/default.nix23
-rw-r--r--pkgs/tools/misc/man/share.patch207
-rw-r--r--pkgs/tools/misc/mc/default.nix20
-rw-r--r--pkgs/tools/misc/memtest86/default.nix26
-rw-r--r--pkgs/tools/misc/mssys/default.nix22
-rw-r--r--pkgs/tools/misc/psmisc/default.nix15
-rw-r--r--pkgs/tools/misc/relfs/cvs.2007.12.01.nix51
-rw-r--r--pkgs/tools/misc/rlwrap/0.28.nix23
-rw-r--r--pkgs/tools/misc/shebangfix/default.nix21
-rw-r--r--pkgs/tools/misc/shebangfix/shebangfix.pl35
-rw-r--r--pkgs/tools/misc/wv/default.nix11
-rw-r--r--pkgs/tools/misc/xclip/default.nix8
-rw-r--r--pkgs/tools/networking/bsd-finger/default.nix17
-rw-r--r--pkgs/tools/networking/bsd-finger/ubuntu-0.17-9.patch261
-rw-r--r--pkgs/tools/networking/curl/connect-timeout.patch156
-rw-r--r--pkgs/tools/networking/curl/default.nix17
-rw-r--r--pkgs/tools/networking/dnsmasq/default.nix8
-rw-r--r--pkgs/tools/networking/lsh/default.nix17
-rw-r--r--pkgs/tools/networking/nc6/1.0.nix25
-rw-r--r--pkgs/tools/networking/ntp/default.nix10
-rw-r--r--pkgs/tools/networking/openssh/default.nix1
-rw-r--r--pkgs/tools/networking/p2p/bit-tornado/default.nix4
-rw-r--r--pkgs/tools/networking/p2p/bittorrent/builder.sh8
-rw-r--r--pkgs/tools/networking/p2p/bittorrent/default.nix12
-rw-r--r--pkgs/tools/networking/p2p/ktorrent/default.nix14
-rw-r--r--pkgs/tools/networking/smbfs-fuse/0.8.7.nix29
-rw-r--r--pkgs/tools/networking/socat/1.6.0.0.nix34
-rw-r--r--pkgs/tools/networking/socat/2.0.0-b1.nix25
-rw-r--r--pkgs/tools/networking/sshfs-fuse/default.nix11
-rw-r--r--pkgs/tools/networking/tcpdump/default.nix6
-rw-r--r--pkgs/tools/networking/vpnc/builder.sh9
-rw-r--r--pkgs/tools/networking/vpnc/default.nix20
-rw-r--r--pkgs/tools/networking/vpnc/makefile.patch22
-rw-r--r--pkgs/tools/networking/wget/1.10.2.nix (renamed from pkgs/tools/networking/wget/default.nix)0
-rw-r--r--pkgs/tools/networking/wget/1.11.nix16
-rw-r--r--pkgs/tools/package-management/nix/custom.nix45
-rw-r--r--pkgs/tools/package-management/nix/default.nix10
-rw-r--r--pkgs/tools/package-management/nix/unstable.nix9
-rw-r--r--pkgs/tools/package-management/snix/default.nix36
-rw-r--r--pkgs/tools/security/chkrootkit/default.nix16
-rw-r--r--pkgs/tools/security/gnupg/default.nix11
-rw-r--r--pkgs/tools/security/gnupg2/default.nix16
-rw-r--r--pkgs/tools/system/cron/default.nix2
-rw-r--r--pkgs/tools/system/gdmap/0.7.5.nix22
-rw-r--r--pkgs/tools/system/pciutils/default.nix10
-rw-r--r--pkgs/tools/system/which/default.nix10
-rw-r--r--pkgs/tools/text/diffutils/default.nix7
-rw-r--r--pkgs/tools/text/gawk/default.nix12
-rw-r--r--pkgs/tools/text/gnugrep/default.nix13
-rw-r--r--pkgs/tools/text/gnused/default.nix7
-rw-r--r--pkgs/tools/text/replace/default.nix9
-rw-r--r--pkgs/tools/typesetting/lhs2tex/default.nix6
-rwxr-xr-xpkgs/tools/typesetting/lout/builder.sh42
-rw-r--r--pkgs/tools/typesetting/lout/default.nix20
-rw-r--r--pkgs/top-level/all-packages.nix2065
-rw-r--r--pkgs/top-level/build-for-release.nix11
-rw-r--r--pkgs/top-level/builder-defs.nix233
-rw-r--r--pkgs/top-level/template-composing+config.nix23
-rw-r--r--pkgs/top-level/template-composing-builder.nix12
-rw-r--r--pkgs/top-level/template.nix45
-rw-r--r--pkgs/top-level/version-stub.nix2
742 files changed, 23049 insertions, 8771 deletions
diff --git a/maintainers/docs/coding-conventions.txt b/maintainers/docs/coding-conventions.txt
new file mode 100644
index 00000000000..c95dc3c3600
--- /dev/null
+++ b/maintainers/docs/coding-conventions.txt
@@ -0,0 +1,97 @@
+Some conventions:
+
+* Don't use TABs.  Everybody has different TAB settings so it's asking
+  for trouble.
+
+* Use 2 spaces of indentation per indentation level in Nix
+  expressions, 4 spaces in shell scripts.  (Maybe 2 is too low, but
+  for consistency's sake it should be the same.  Certainly indentation
+  should be consistent within a single file.)
+
+* Use lowerCamelCase for variable names, not UpperCamelCase.
+
+* Function calls with attribute set arguments are written as
+
+    foo {
+      arg = ...;
+    }
+
+  not
+
+    foo
+    {
+      arg = ...;
+    }
+
+  Also fine is
+
+    foo { arg = ...; }
+
+  if it's a short call.
+
+* In attribute sets or lists that span multiple lines, the attribute
+  names or list elements should be aligned:
+
+    # A long list.
+    list = [
+      elem1
+      elem2
+      elem3
+    ];
+
+    # A long attribute set.
+    attrs = {
+      attr1 = short_expr;
+      attr2 =
+        if true then big_expr else big_expr;
+    };
+    
+* Short lists or attribute sets can be written on one line:
+    
+    # A short list.
+    list = [ elem1 elem2 elem3 ];
+
+    # A short set.
+    attrs = { x = 1280; y = 1024; };
+
+* Breaking in the middle of a function argument can give hard-to-read
+  code, like
+
+    someFunction { x = 1280;
+      y = 1024; } otherArg
+      yetAnotherArg
+
+  (especially if the argument is very large, spanning multiple lines).
+
+  Better:
+
+    someFunction
+      { x = 1280; y = 1024; }
+      otherArg
+      yetAnotherArg
+
+  or
+    
+    let res = { x = 1280; y = 1024; };
+    in someFunction res otherArg yetAnotherArg
+
+* The bodies of functions, asserts, and withs are not indented, so
+
+    assert system == "i686-linux";
+    stdenv.mkDerivation { ...
+
+  not
+
+    assert system == "i686-linux";
+      stdenv.mkDerivation { ...
+
+* Function formal arguments are written as:
+
+    {arg1, arg2, arg3}:
+
+  but if they don't fit on one line they're written as:
+
+    { arg1, arg2, arg3
+    , arg4, ...
+    , argN
+    }:
diff --git a/pkgs/applications/audio/audacity/default.nix b/pkgs/applications/audio/audacity/default.nix
index 56ee6a56ccb..159c99c4999 100644
--- a/pkgs/applications/audio/audacity/default.nix
+++ b/pkgs/applications/audio/audacity/default.nix
@@ -1,5 +1,5 @@
 args: with args;
-	with (builderDefs { 
+	let localDefs = builderDefs { 
 	  src = 
 		fetchurl {
 			url = mirror://sourceforge/audacity/audacity-src-1.3.3.tar.gz;
@@ -8,7 +8,8 @@ args: with args;
 
   	buildInputs =[(wxGTK null) libogg libvorbis libsndfile libmad pkgconfig gtk 
 		gettext glib];
-	} null);
+	} null;
+	in with localDefs;
 let 
 	postInstall = FullDepEntry ("
 		old_rpath=$(patchelf --print-rpath \$out/bin/audacity);
@@ -25,11 +26,10 @@ stdenv.mkDerivation {
   name = "audacity-1.3.3";
 
   builder = writeScript "audacity-1.3.3-builder"
-		(textClosure [addInputs (doDump "0") (noDepEntry "echo \$PATH; ar --version") doConfigure preBuild doMakeInstall postInstall doForceShare]);
+		(textClosure localDefs [addInputs (doDump "0") (noDepEntry "echo \$PATH; ar --version") doConfigure preBuild doMakeInstall postInstall doForceShare]);
 
   meta = {
-    description = "
-	Audacity sound editor.
-";
+    description = "Audacity sound editor.";
+    homepage = http://audacity.sourceforge.net;
   };
 }
diff --git a/pkgs/applications/audio/aumix/default.nix b/pkgs/applications/audio/aumix/default.nix
new file mode 100644
index 00000000000..57c690fee9b
--- /dev/null
+++ b/pkgs/applications/audio/aumix/default.nix
@@ -0,0 +1,24 @@
+{stdenv, fetchurl, gettext, ncurses
+, gtkGUI ? false
+, pkgconfig ? null
+, gtk ? null}:
+
+assert gtkGUI -> pkgconfig != null && gtk != null;
+
+stdenv.mkDerivation {
+  name = "aumix-2.8";
+  src = fetchurl {
+    url = http://www.jpj.net/~trevor/aumix/aumix-2.8.tar.bz2;
+    sha256 = "636eef7f400c2f3df489c0d2fa21507e88692113561e75a40a26c52bc422d7fc";
+  };
+
+  buildInputs = [ gettext ncurses ]
+    ++ (if gtkGUI then [pkgconfig gtk] else []);
+
+  meta = {
+    description = ''Aumix adjusts an audio mixer from X, the console,
+    		    a terminal, the command line or a script.'';
+    homepage = http://www.jpj.net/~trevor/aumix.html;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/applications/audio/cdparanoia/default.nix b/pkgs/applications/audio/cdparanoia/default.nix
index e8d31772611..6fa69beee20 100644
--- a/pkgs/applications/audio/cdparanoia/default.nix
+++ b/pkgs/applications/audio/cdparanoia/default.nix
@@ -8,4 +8,8 @@ stdenv.mkDerivation {
   };
   
   patches = [./fix.patch];
+
+  meta = {
+    homepage = http://xiph.org/paranoia;
+  };
 }
diff --git a/pkgs/applications/audio/flac/default.nix b/pkgs/applications/audio/flac/default.nix
index 58c11aaa0f8..6095e59fa07 100644
--- a/pkgs/applications/audio/flac/default.nix
+++ b/pkgs/applications/audio/flac/default.nix
@@ -1,11 +1,19 @@
-{stdenv, fetchurl, libogg}:
-
-stdenv.mkDerivation {
-  name = "flac-1.1.2";
-  src = fetchurl {
-    url = http://downloads.xiph.org/releases/flac/flac-1.1.2.tar.gz;
-    md5 = "2bfc127cdda02834d0491ab531a20960";
-  };
-
-  buildInputs = [libogg] ;
-}
+args: with args;
+let
+	flacFun = version: hash:
+	stdenv.mkDerivation rec {
+		name = "flac-${version}";
+		src = fetchurl ({
+			url = "http://downloads.xiph.org/releases/flac/${name}.tar.gz";
+		} // hash);
+		buildInputs = [libogg];
+    meta = {
+      homepage = http://flac.sourceforge.net;
+    };
+	};
+in
+stdenv.lib.listOfListsToAttrs [
+	[ "default" (flacFun "1.2.1" { sha256 = "1pry5lgzfg57pga1zbazzdd55fkgk3v5qy4axvrbny5lrr5s8dcn"; }) ]
+	[ "1.2.1" (flacFun "1.2.1" { sha256 = "1pry5lgzfg57pga1zbazzdd55fkgk3v5qy4axvrbny5lrr5s8dcn"; }) ]
+	[ "1.1.2" (flacFun "1.1.2" { md5 = "2bfc127cdda02834d0491ab531a20960"; }) ]
+]
diff --git a/pkgs/applications/audio/ladspa-plugins/default.nix b/pkgs/applications/audio/ladspa-plugins/default.nix
index 9a033a42b87..9f2fcbc0ed0 100644
--- a/pkgs/applications/audio/ladspa-plugins/default.nix
+++ b/pkgs/applications/audio/ladspa-plugins/default.nix
@@ -1,5 +1,5 @@
 args: with args;
-	with (builderDefs {
+	let localDefs = builderDefs {
 		src = 
 		fetchurl {
 			url = http://plugin.org.uk/releases/0.4.15/swh-plugins-0.4.15.tar.gz;
@@ -7,7 +7,8 @@ args: with args;
 		};
 		buildInputs = [fftw ladspaH pkgconfig];
 		configureFlags = [];
-	} null);
+	} null;
+	in with localDefs;
 let
 	postInstall = FullDepEntry ("
 		ensureDir \$out/share/ladspa/
@@ -17,7 +18,8 @@ in
 stdenv.mkDerivation {
 	name = "swh-plugins-0.4.15";
 	builder = writeScript "swh-plugins-0.4.15-builder"
-		(textClosure [doConfigure doMakeInstall postInstall doForceShare]);
+		(textClosure localDefs [doConfigure doMakeInstall 
+			postInstall doForceShare]);
 	meta = {
 		description = "
 	LADSPA format audio plugins.
diff --git a/pkgs/applications/audio/ladspa-plugins/ladspah.nix b/pkgs/applications/audio/ladspa-plugins/ladspah.nix
index b526e48b10e..65647cf0a22 100644
--- a/pkgs/applications/audio/ladspa-plugins/ladspah.nix
+++ b/pkgs/applications/audio/ladspa-plugins/ladspah.nix
@@ -6,10 +6,11 @@ let
 		sha256 = "1b908csn85ng9sz5s5d1mqk711cmawain2z8px2ajngihdrynb67";
 	};
 in
-	with builderDefs {
+	let localDefs = builderDefs {
 		buildInputs = [];
 		inherit src;
 	} null;
+	in with localDefs;
 let
 	copyFile = FullDepEntry ("
 		ensureDir \$out/include
@@ -19,7 +20,7 @@ in
 stdenv.mkDerivation {
 	name = "ladspa.h";
 	builder = writeScript "ladspa.h-builder"
-		(textClosure [copyFile]);
+		(textClosure localDefs [copyFile]);
 	meta = {
 		description = "
 	LADSPA format audio plugins.
diff --git a/pkgs/applications/audio/lame/default.nix b/pkgs/applications/audio/lame/default.nix
index 503c0c39595..4a97b25cd60 100644
--- a/pkgs/applications/audio/lame/default.nix
+++ b/pkgs/applications/audio/lame/default.nix
@@ -1,9 +1,9 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "lame-3.96.1";
+  name = "lame-3.97";
   src = fetchurl {
-    url = mirror://sourceforge/lame/lame-3.96.1.tar.gz ;
-    md5 = "e1206c46a5e276feca11a7149e2fc6ac" ;
+    url = mirror://sourceforge/lame/lame-3.97.tar.gz ;
+    sha256 = "05xy9lv6m9s013lzlvhxwvr1586c239xaiiwka52k18hs6k388qa";
   };
 }
diff --git a/pkgs/applications/audio/mpg321/default.nix b/pkgs/applications/audio/mpg321/default.nix
new file mode 100644
index 00000000000..23cc92132b9
--- /dev/null
+++ b/pkgs/applications/audio/mpg321/default.nix
@@ -0,0 +1,17 @@
+{stdenv, fetchurl, libao, libmad, libid3tag, zlib}:
+
+stdenv.mkDerivation {
+  name = "mpg321-0.2.10";
+  src = fetchurl {
+    url = mirror://sourceforge/mpg321/mpg321-0.2.10.tar.gz;
+    sha256 = "db0c299592b8f1f704f41bd3fc3a2bf138658108588d51af61638c551af1b0d4";
+  };
+
+  buildInputs = [libao libid3tag libmad zlib];
+
+  meta = {
+    description = "Command-line MP3 player.";
+    homepage = http://mpg321.sourceforge.net/;
+    license = "GPLv2";
+  };
+}
diff --git a/pkgs/applications/audio/snd/default.nix b/pkgs/applications/audio/snd/default.nix
index 9a650570a6d..38bebb12fd3 100644
--- a/pkgs/applications/audio/snd/default.nix
+++ b/pkgs/applications/audio/snd/default.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = 
 	fetchurl {
 		url = ftp://ccrma-ftp.stanford.edu/pub/Lisp/snd-9.4.tar.gz;
@@ -20,6 +20,7 @@ args : with args;
 			++ (lib.optional (args ? sndlib) "--with-midi" )
 			;
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 	let preBuild = FullDepEntry ("
 		cp config.log /tmp/snd-config.log
 	") [minInit doUnpack];
@@ -27,10 +28,9 @@ in
 stdenv.mkDerivation rec {
 	name = "Snd-9.4";
 	builder = writeScript (name + "-builder")
-		(textClosure [doConfigure preBuild doMakeInstall doForceShare]);
+		(textClosure localDefs [doConfigure preBuild doMakeInstall doForceShare]);
 	meta = {
-		description = "
-		Snd sound editor.
-";
+		description = "Snd sound editor.";
+    homepage = http://ccrma.stanford.edu/software/snd;
 	};
 }
diff --git a/pkgs/applications/audio/vorbis-tools/default.nix b/pkgs/applications/audio/vorbis-tools/default.nix
new file mode 100644
index 00000000000..626dc1c9d96
--- /dev/null
+++ b/pkgs/applications/audio/vorbis-tools/default.nix
@@ -0,0 +1,24 @@
+{stdenv, fetchurl, libogg, libvorbis, libao, pkgconfig, curl, glibc
+, speex, flac}:
+
+stdenv.mkDerivation {
+  name = "vorbis-tools-1.1.1";
+  src = fetchurl {
+    url = http://downloads.xiph.org/releases/vorbis/vorbis-tools-1.1.1.tar.gz;
+    sha256 = "617b4aa69e600c215b34fa3fd5764bc1d9d205d9d7d9fe7812bde7ec956fcaad";
+  };
+
+  # FIXME: Vorbis-tools expects `libOggFLAC', but this library was
+  # merged with `libFLAC' as of FLAC 1.1.3.
+  buildInputs = [ libogg libvorbis libao pkgconfig curl speex glibc flac ];
+
+  patches = [ ./ogg123-curlopt-mute.patch ];
+
+  meta = {
+    description = ''A set of command-line tools to manipulate Ogg Vorbis
+                    audio files, notably the `ogg123' player and the
+		    `oggenc' encoder.'';
+    homepage = http://xiph.org/vorbis/;
+    license = "GPLv2";
+  };
+}
diff --git a/pkgs/applications/audio/vorbis-tools/ogg123-curlopt-mute.patch b/pkgs/applications/audio/vorbis-tools/ogg123-curlopt-mute.patch
new file mode 100644
index 00000000000..6437909411e
--- /dev/null
+++ b/pkgs/applications/audio/vorbis-tools/ogg123-curlopt-mute.patch
@@ -0,0 +1,13 @@
+--- vorbis-tools-1.1.1/ogg123/http_transport.c	2005-06-13 15:11:44.000000000 +0200
++++ vorbis-tools-1.1.1/ogg123/http_transport.c	2008-02-12 18:38:41.000000000 +0100
+@@ -116,7 +116,9 @@ void set_curl_opts (http_private_t *priv
+   if (inputOpts.ProxyTunnel)
+     curl_easy_setopt (handle, CURLOPT_HTTPPROXYTUNNEL, inputOpts.ProxyTunnel);
+   */
++#ifdef CURLOPT_MUTE
+   curl_easy_setopt(handle, CURLOPT_MUTE, 1);
++#endif
+   curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, private->error);
+   curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, progress_callback);
+   curl_easy_setopt(handle, CURLOPT_PROGRESSDATA, private);
+
diff --git a/pkgs/applications/audio/xmms/default.nix b/pkgs/applications/audio/xmms/default.nix
index bd5bb53414e..8e2650fd7c0 100644
--- a/pkgs/applications/audio/xmms/default.nix
+++ b/pkgs/applications/audio/xmms/default.nix
@@ -14,5 +14,6 @@ stdenv.mkDerivation {
 
   meta = {
     description = "A music player very similar to Winamp";
+    homepage = http://www.xmms.org;
   };
 }
diff --git a/pkgs/applications/display-managers/slim/default.nix b/pkgs/applications/display-managers/slim/default.nix
index c16582fc388..5b711111c91 100644
--- a/pkgs/applications/display-managers/slim/default.nix
+++ b/pkgs/applications/display-managers/slim/default.nix
@@ -20,4 +20,8 @@ stdenv.mkDerivation {
     substituteInPlace Makefile --replace /usr /no-such-path
     makeFlagsArray=(CC=gcc CXX=g++ PREFIX=$out MANDIR=$out/share/man CFGDIR=$out/etc)
   ";
+
+  meta = {
+    homepage = http://slim.berlios.de;
+  };
 }
diff --git a/pkgs/applications/editors/bvi/default.nix b/pkgs/applications/editors/bvi/default.nix
new file mode 100644
index 00000000000..223aabcdf82
--- /dev/null
+++ b/pkgs/applications/editors/bvi/default.nix
@@ -0,0 +1,17 @@
+args : with args;
+stdenv.mkDerivation {
+  name = "bvi-1.3.2";
+
+  src = fetchurl {
+    url = http://prdownloads.sourceforge.net/bvi/bvi-1.3.2.src.tar.gz;
+    sha256 = "110wxqnyianqamxq4y53drqqxb9vp4k2fcvic45qggvlqkqhlfgz";
+  };
+
+  buildInputs = [ncurses];
+
+  meta = { 
+      description = "hex editor with vim style keybindings";
+      homepage = http://bvi.sourceforge.net/download.html;
+      license = "GPL2";
+  };
+}
diff --git a/pkgs/applications/editors/eclipse/builder.sh b/pkgs/applications/editors/eclipse/builder.sh
index b38befee41a..6e064e1fa9b 100755
--- a/pkgs/applications/editors/eclipse/builder.sh
+++ b/pkgs/applications/editors/eclipse/builder.sh
@@ -1,5 +1,4 @@
 source $stdenv/setup
-source $makeWrapper
 
 unpackFile $src 
 ensureDir $out
diff --git a/pkgs/applications/editors/eclipse/default.nix b/pkgs/applications/editors/eclipse/default.nix
index 9051293f489..23199bdcc12 100644
--- a/pkgs/applications/editors/eclipse/default.nix
+++ b/pkgs/applications/editors/eclipse/default.nix
@@ -6,15 +6,17 @@ let {
       name = "eclipse-sdk-3.3.3.1";
       builder = ./builder.sh;
       src = bindist;
-      inherit makeWrapper jdk plugins;
+      buildInputs = [makeWrapper];
+      inherit jdk plugins;
       libraries = [gtk glib libXtst];
    };
 
   bindist = 
-    fetchurl {
+    if (stdenv.system == "x86_64-linux") then fetchurl {
+      url = "http://ftp-stud.fht-esslingen.de/pub/Mirrors/eclipse/eclipse/downloads/drops/R-3.3.1.1-200710231652/eclipse-SDK-3.3.1.1-linux-gtk-x86_64.tar.gz";
+      sha256 = "3fec49e95c45b56ad77b2bd15616af9d1fa6c3b338d4c70b497ecdc974c0b030";
+    } else fetchurl {
       url = http://ftp-stud.fht-esslingen.de/pub/Mirrors/eclipse/eclipse/downloads/drops/R-3.3.1.1-200710231652/eclipse-SDK-3.3.1.1-linux-gtk.tar.gz;
       sha256 = "409e47745c92ff8ea8b2037104ec90c2f8ce3edb3563fdb312d55e1bbd2ada01";
     };
 }
-
-
diff --git a/pkgs/applications/editors/emacs-22/default.nix b/pkgs/applications/editors/emacs-22/default.nix
index 0af6f95a344..d527e305154 100644
--- a/pkgs/applications/editors/emacs-22/default.nix
+++ b/pkgs/applications/editors/emacs-22/default.nix
@@ -14,12 +14,13 @@ assert gtkGUI -> pkgconfig != null && gtk != null;
 
 stdenv.mkDerivation {
   name = "emacs-22.1";
+
   builder = ./builder.sh;
   src = fetchurl {
     url = mirror://gnu/emacs/emacs-22.1.tar.gz;
     sha256 = "1l1y3il98pq3cz464p244wz2d3nga5lq8fkw5pwp5r97f7pkpi0y";
   };
-  patches = [./crt.patch];
+  patches = [./crt.patch ./makefile-pwd.patch];
   buildInputs = [
     ncurses x11
     (if xawSupport then if xaw3dSupport then Xaw3d else libXaw else null)
diff --git a/pkgs/applications/editors/emacs-22/makefile-pwd.patch b/pkgs/applications/editors/emacs-22/makefile-pwd.patch
new file mode 100644
index 00000000000..232b881c9a6
--- /dev/null
+++ b/pkgs/applications/editors/emacs-22/makefile-pwd.patch
@@ -0,0 +1,129 @@
+--- emacs-22.1/Makefile.in	2008-02-10 23:56:29.000000000 +0100
++++ emacs-22.1/Makefile.in	2008-02-10 23:55:55.000000000 +0100
+@@ -420,7 +420,7 @@
+ 	-set ${COPYDESTS} ; \
+ 	unset CDPATH; \
+ 	for dir in ${COPYDIR} ; do \
+-	  if [ `(cd $$1 && /bin/pwd)` != `(cd $${dir} && /bin/pwd)` ] ; then \
++	  if [ `(cd $$1 && pwd)` != `(cd $${dir} && pwd)` ] ; then \
+ 	    rm -rf $$1 ; \
+ 	  fi ; \
+ 	  shift ; \
+@@ -432,7 +432,7 @@
+ 	for dir in ${COPYDIR} ; do \
+ 	  dest=$$1 ; shift ; \
+ 	  [ -d $${dir} ] \
+-	  && [ `(cd $${dir} && /bin/pwd)` != `(cd $${dest} && /bin/pwd)` ] \
++	  && [ `(cd $${dir} && pwd)` != `(cd $${dest} && pwd)` ] \
+ 	  && (echo "Copying $${dir} to $${dest}..." ; \
+ 	      (cd $${dir}; tar -chf - . ) \
+ 		| (cd $${dest}; umask 022; \
+@@ -472,7 +472,7 @@
+ 	fi
+ 	-chmod a+r $(DESTDIR)${datadir}/emacs/site-lisp/subdirs.el
+ 	-unset CDPATH; \
+-	if [ `(cd ./etc; /bin/pwd)` != `(cd $(DESTDIR)${docdir}; /bin/pwd)` ]; \
++	if [ `(cd ./etc; pwd)` != `(cd $(DESTDIR)${docdir}; pwd)` ]; \
+ 	then \
+ 	   echo "Copying etc/DOC-* to $(DESTDIR)${docdir} ..." ; \
+ 	   (cd ./etc; tar -chf - DOC*) \
+@@ -483,8 +483,8 @@
+ 	-unset CDPATH; \
+ 	if [ -r ./lisp ] \
+ 	   && [ -r ./lisp/simple.el ] \
+-	   && [ x`(cd ./lisp; /bin/pwd)` != x`(cd $(DESTDIR)${lispdir}; /bin/pwd)` ] \
+-	   && [ x`(cd ${srcdir}/lisp; /bin/pwd)` != x`(cd ./lisp; /bin/pwd)` ]; \
++	   && [ x`(cd ./lisp; pwd)` != x`(cd $(DESTDIR)${lispdir}; pwd)` ] \
++	   && [ x`(cd ${srcdir}/lisp; pwd)` != x`(cd ./lisp; pwd)` ]; \
+ 	then \
+ 	   echo "Copying lisp/*.el and lisp/*.elc to $(DESTDIR)${lispdir} ..." ; \
+ 	   (cd lisp; tar -chf - *.el *.elc) \
+@@ -500,8 +500,8 @@
+ 	    done) \
+ 	else true; fi
+ 	-unset CDPATH; \
+-	thisdir=`/bin/pwd`; \
+-	if [ `(cd ${srcdir}/info && /bin/pwd)` != `(cd $(DESTDIR)${infodir} && /bin/pwd)` ]; \
++	thisdir=`pwd`; \
++	if [ `(cd ${srcdir}/info && pwd)` != `(cd $(DESTDIR)${infodir} && pwd)` ]; \
+ 	then \
+ 	  (cd $(DESTDIR)${infodir};  \
+ 	   if [ -f dir ]; then true; \
+@@ -519,8 +519,8 @@
+ 	   done); \
+ 	else true; fi
+ 	-unset CDPATH; \
+-	thisdir=`/bin/pwd`; \
+-	if [ `(cd ${srcdir}/info && /bin/pwd)` != `(cd $(DESTDIR)${infodir} && /bin/pwd)` ]; \
++	thisdir=`pwd`; \
++	if [ `(cd ${srcdir}/info && pwd)` != `(cd $(DESTDIR)${infodir} && pwd)` ]; \
+ 	then \
+ 	  for elt in $(INFO_FILES); do \
+ 	    (cd $${thisdir}; \
+@@ -528,7 +528,7 @@
+ 	  done; \
+ 	else true; fi
+ 	-chmod -R a+r $(DESTDIR)${datadir}/emacs/${version} $(DESTDIR)${datadir}/emacs/site-lisp ${COPYDESTS} $(DESTDIR)${infodir}
+-	thisdir=`/bin/pwd`; \
++	thisdir=`pwd`; \
+ 	cd ${srcdir}/etc; \
+ 	for page in emacs emacsclient etags ctags ; do \
+ 	  (cd $${thisdir}; \
+@@ -575,8 +575,8 @@
+ 	-unset CDPATH; \
+ 	for dir in $(DESTDIR)${lispdir} $(DESTDIR)${etcdir} ; do 	\
+ 	  if [ -d $${dir} ]; then			\
+-	    case `(cd $${dir} ; /bin/pwd)` in		\
+-	      `(cd ${srcdir} ; /bin/pwd)`* ) ;;		\
++	    case `(cd $${dir} ; pwd)` in		\
++	      `(cd ${srcdir} ; pwd)`* ) ;;		\
+ 	      * ) rm -rf $${dir} ;;			\
+ 	    esac ;					\
+ 	    case $${dir} in				\
+--- emacs-22.1/leim/Makefile.in	2008-02-10 23:55:31.000000000 +0100
++++ emacs-22.1/leim/Makefile.in	2008-02-10 23:55:41.000000000 +0100
+@@ -207,7 +207,7 @@
+ leim-list.el: ${SUBDIRS} ${TIT-MISC} changed.tit changed.misc ${srcdir}/leim-ext.el
+ 	${RUN-EMACS}  -l ${buildlisppath}/international/quail \
+ 	  -f batch-byte-compile-if-not-done ${TIT-MISC:.elc=.el}
+-	if [ x`(cd ${srcdir} && /bin/pwd)` = x`(/bin/pwd)` ] ; then \
++	if [ x`(cd ${srcdir} && pwd)` = x`(pwd)` ] ; then \
+ 	  ${RUN-EMACS} -l ${buildlisppath}/international/quail \
+ 	    --eval "(update-leim-list-file \".\")" ; \
+ 	else \
+@@ -220,11 +220,11 @@
+ 	if [ ! -d ${INSTALLDIR} ] ; then \
+           ${srcdir}/${dot}${dot}/mkinstalldirs ${INSTALLDIR}; \
+ 	else true; fi
+-	if [ x`(cd ${INSTALLDIR} && /bin/pwd)` != x`(/bin/pwd)` ] ; then \
++	if [ x`(cd ${INSTALLDIR} && pwd)` != x`(pwd)` ] ; then \
+ 	  rm -rf ${INSTALLDIR}/leim-list.el; \
+ 	  rm -rf ${INSTALLDIR}/quail ${INSTALLDIR}/ja-dic ; \
+ 	  echo "Copying leim files to ${INSTALLDIR} ..." ; \
+-	  if [ x`(cd ${srcdir} && /bin/pwd)` = x`(/bin/pwd)` ] ; then \
++	  if [ x`(cd ${srcdir} && pwd)` = x`(pwd)` ] ; then \
+ 	    tar -chf - leim-list.el quail ja-dic \
+ 		| (cd ${INSTALLDIR}; umask 0; tar -xvf - && cat > /dev/null) ;\
+ 	  else \
+--- emacs-22.1/lib-src/Makefile.in	2008-02-10 23:59:08.000000000 +0100
++++ emacs-22.1/lib-src/Makefile.in	2008-02-10 23:59:13.000000000 +0100
+@@ -306,7 +306,7 @@
+ 	@echo
+ 	@echo "Installing utilities run internally by Emacs."
+ 	$(top_srcdir)/mkinstalldirs $(DESTDIR)${archlibdir}
+-	if [ `(cd $(DESTDIR)${archlibdir} && /bin/pwd)` != `/bin/pwd` ]; then \
++	if [ `(cd $(DESTDIR)${archlibdir} && pwd)` != `pwd` ]; then \
+ 	  for file in ${UTILITIES}; do \
+ 	    $(INSTALL_PROGRAM) $(INSTALL_STRIP) $$file $(DESTDIR)${archlibdir}/$$file ; \
+ 	  done ; \
+@@ -321,8 +321,8 @@
+ 	  chown ${gameuser} $(DESTDIR)${gamedir}; \
+ 	  chmod u=rwx,g=rwx,o=rx $(DESTDIR)${gamedir}; \
+ 	fi
+-        if [ `(cd $(DESTDIR)${archlibdir} && /bin/pwd)` \
+-             != `(cd ${srcdir} && /bin/pwd)` ]; then \
++        if [ `(cd $(DESTDIR)${archlibdir} && pwd)` \
++             != `(cd ${srcdir} && pwd)` ]; then \
+ 	  for file in ${SCRIPTS}; do \
+ 	    $(INSTALL_SCRIPT) ${srcdir}/$$file $(DESTDIR)${archlibdir}/$$file; \
+ 	  done ; \
diff --git a/pkgs/applications/editors/emacs-modes/bbdb/builder.sh b/pkgs/applications/editors/emacs-modes/bbdb/builder.sh
new file mode 100644
index 00000000000..b860adbb745
--- /dev/null
+++ b/pkgs/applications/editors/emacs-modes/bbdb/builder.sh
@@ -0,0 +1,12 @@
+source "$stdenv/setup" || exit 1
+
+unpackPhase &&							\
+cd bbdb-*.* && patchPhase &&					\
+./configure --prefix="$out"					\
+            --with-package-dir="$out/share/emacs/site-lisp" &&	\
+make && make install-pkg &&					\
+mkdir -p "$out/info" &&						\
+make -C texinfo install-pkg &&					\
+mv "$out/share/emacs/site-lisp/lisp/bbdb/"*			\
+   "$out/share/emacs/site-lisp" &&				\
+rm -rf "$out/share/emacs/site-lisp/lisp"
diff --git a/pkgs/applications/editors/emacs-modes/bbdb/default.nix b/pkgs/applications/editors/emacs-modes/bbdb/default.nix
new file mode 100644
index 00000000000..3799d0a0f1b
--- /dev/null
+++ b/pkgs/applications/editors/emacs-modes/bbdb/default.nix
@@ -0,0 +1,22 @@
+{stdenv, fetchurl, emacs, texinfo, ctags}:
+
+stdenv.mkDerivation {
+  name = "bbdb-2.35";
+
+  src = fetchurl {
+    url = http://bbdb.sourceforge.net/bbdb-2.35.tar.gz;
+    sha256 = "3fb1316e2ed74d47ca61187fada550e58797467bd9e8ad67343ed16da769f916";
+  };
+
+  patches = [ ./install-infodir.patch ];
+
+  buildInputs = [emacs texinfo ctags];
+  builder = ./builder.sh;
+
+  meta = {
+    description = ''The Insidious Big Brother Database (BBDB), a
+                    contact management utility for Emacs.'';
+    homepage = http://bbdb.sourceforge.net/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/applications/editors/emacs-modes/bbdb/install-infodir.patch b/pkgs/applications/editors/emacs-modes/bbdb/install-infodir.patch
new file mode 100644
index 00000000000..31ae6b26698
--- /dev/null
+++ b/pkgs/applications/editors/emacs-modes/bbdb/install-infodir.patch
@@ -0,0 +1,28 @@
+--- bbdb-2.35/texinfo/Makefile.in	2001-11-20 09:00:12.000000000 +0100
++++ bbdb-2.35/texinfo/Makefile.in	2008-02-20 12:07:36.000000000 +0100
+@@ -27,22 +27,22 @@ all: info bbdb.dvi
+ install-pkg: uninstall-pkg info
+ 	@if test "x$(SYMLINKS)" = "xno" ; then                         \
+           for i in `ls bbdb.info* ` ; do                               \
+-            $(INSTALL_DATA) $$i $(PACKAGEDIR)/info/ ;                  \
++            $(INSTALL_DATA) $$i $(infodir)/ ;                  \
+           done ;                                                       \
+         else                                                           \
+           if test "x$(LINKPATH)" = "x" ; then                          \
+             for i in `ls bbdb.info* ` ; do                             \
+-              $(LN_S) `pwd`/$$i $(PACKAGEDIR)/info/$$i ;               \
++              $(LN_S) `pwd`/$$i $(infodir)/$$i ;               \
+             done ;                                                     \
+           else                                                         \
+             for i in `ls bbdb.info* ` ; do                             \
+-              $(LN_S) $(LINKPATH)/texinfo/$$i $(PACKAGEDIR)/info/$$i ; \
++              $(LN_S) $(LINKPATH)/texinfo/$$i $(infodir)/$$i ; \
+             done ;                                                     \
+           fi ;                                                         \
+         fi
+ 
+ uninstall-pkg:
+-	-$(RM) $(PACKAGEDIR)/info/bbdb.info*
++	-$(RM) $(infodir)/bbdb.info*
+ 
+ info: bbdb.info
diff --git a/pkgs/applications/editors/joe/default.nix b/pkgs/applications/editors/joe/default.nix
index 0228beb78d6..b6324e5879c 100644
--- a/pkgs/applications/editors/joe/default.nix
+++ b/pkgs/applications/editors/joe/default.nix
@@ -1,9 +1,13 @@
 {stdenv, fetchurl} :
 
 stdenv.mkDerivation {
-name = "joe-3.3";
-src = fetchurl {
-         url = mirror://sourceforge/joe-editor/joe-3.3.tar.gz;
-         md5 = "02221716679c039c5da00c275d61dbf4";
-   };
+  name = "joe-3.3";
+  src = fetchurl {
+    url = mirror://sourceforge/joe-editor/joe-3.3.tar.gz;
+    md5 = "02221716679c039c5da00c275d61dbf4";
+  };
+
+  meta = {
+    homepage = http://joe-editor.sourceforge.net;
+  };
 }
diff --git a/pkgs/applications/editors/nano/default.nix b/pkgs/applications/editors/nano/default.nix
index 28bc07141a3..5e89d8a5bcd 100644
--- a/pkgs/applications/editors/nano/default.nix
+++ b/pkgs/applications/editors/nano/default.nix
@@ -1,11 +1,29 @@
-{stdenv, fetchurl, ncurses, gettext}:
+args: with args;
+stdenv.mkDerivation (rec {
+  pname = "nano";
+  version = "2.0.7";
+
+  name = "${pname}-${version}";
 
-stdenv.mkDerivation {
-  name = "nano-2.0.6";
   src = fetchurl {
-    url = mirror://gnu/nano/nano-2.0.6.tar.gz;
-    sha256 = "0p2xfs4jzj7dvp208qdrxij7x8gbwxgnrdm7zafgpbbg1bvxh40d";
+    url = "mirror://gnu/nano/${name}.tar.gz";
+    sha256 = "5dc783c412c4d1ff463c450d2a2f9e1ea53a43d9ba1dda92bbf5182f60db532f";
   };
   buildInputs = [ncurses gettext];
-  configureFlags = "--enable-tiny";
-}
+#  configureFlags = "--enable-tiny";
+  configureFlags = "
+    --disable-browser 
+    --disable-help 
+    --disable-justify 
+    --disable-mouse 
+    --disable-operatingdir
+    --disable-speller
+    --disable-tabcomp
+    --disable-wrapping
+  ";
+
+  meta = {
+    homepage = http://www.nano-editor.org/;
+    description = "A small, user-friendly console text editor";
+  };
+})
diff --git a/pkgs/applications/editors/nedit/default.nix b/pkgs/applications/editors/nedit/default.nix
index 345eccb0ff9..41028601da7 100644
--- a/pkgs/applications/editors/nedit/default.nix
+++ b/pkgs/applications/editors/nedit/default.nix
@@ -16,4 +16,8 @@ stdenv.mkDerivation {
   buildInputs = [x11 motif libXpm];
 
   buildFlags = if stdenv.system == "i686-linux" then "linux" else "";
+
+  meta = {
+    homepage = http://www.nedit.org;
+  };
 }
diff --git a/pkgs/applications/editors/vim-diet/default.nix b/pkgs/applications/editors/vim-diet/default.nix
index 76c022896fe..7e56d902282 100644
--- a/pkgs/applications/editors/vim-diet/default.nix
+++ b/pkgs/applications/editors/vim-diet/default.nix
@@ -12,4 +12,8 @@ stdenv.mkDerivation {
   buildInputs = [ncurses];
 
   NIX_CFLAGS_COMPILE="-D_BSD_SOURCE=1";
+
+  meta = {
+    homepage = http://www.vim.org;
+  };
 }
diff --git a/pkgs/applications/editors/vim/configurable.nix b/pkgs/applications/editors/vim/configurable.nix
new file mode 100644
index 00000000000..b27bb157f75
--- /dev/null
+++ b/pkgs/applications/editors/vim/configurable.nix
@@ -0,0 +1,72 @@
+# TODO tidy up eg The patchelf code is patching gvim even if you don't build it..
+# but I have gvim with python support now :) - Marc
+args:
+let edf = args.lib.enableDisableFeature; in
+( args.mkDerivationByConfiguration {
+    # most interpreters aren't tested yet.. (see python for example how to do it)
+    flagConfig = { 
+      mandatory = { cfgOption = "--enable-gui=auto --with-features=${args.features}"; 
+                    buildInputs = ["ncurses" "pkgconfig"];
+                  };
+      X11 = { buildInputs = [ "libX11" "libXext" "libSM" "libXpm" "libXt" "libXaw" "libXau" "libXmu" ]; };
+
+    } // edf "darwin" "darwin" { } #Disable Darwin (Mac OS X) support.
+      // edf "xsmp" "xsmp" { } #Disable XSMP session management
+      // edf "xsmp_interact" "xsmp_interact" {  } #Disable XSMP interaction
+      // edf "mzscheme" "mzschemeinterp" { } #Include MzScheme interpreter.
+      // edf "perl" "perlinterp" { } #Include Perl interpreter.
+      // edf "python" "pythoninterp" { pass = "python"; } #Include Python interpreter.
+      // edf "tcl" "tclinterp" { } #Include Tcl interpreter.
+      // edf "ruby" "rubyinterp" { } #Include Ruby interpreter.
+      // edf "cscope" "cscope" { } #Include cscope interface.
+      // edf "workshop" "workshop" { } #Include Sun Visual Workshop support.
+      // edf "netbeans" "netbeans" { } #Disable NetBeans integration support.
+      // edf "sniff" "sniff" { } #Include Sniff interface.
+      // edf "multibyte" "multibyte" { } #Include multibyte editing support.
+      // edf "hangulinput" "hangulinput" { } #Include Hangul input support.
+      // edf "xim" "xim" { pass = "xim"; } #Include XIM input support.
+      // edf "fontset" "fontset" { } #Include X fontset output support.
+
+  #--enable-gui=OPTS     X11 GUI default=auto OPTS=auto/no/gtk/gtk2/gnome/gnome2/motif/athena/neXtaw/photon/carbon
+    /*
+      // edf "gtk_check" "gtk_check" { } #If auto-select GUI, check for GTK default=yes
+      // edf "gtk2_check" "gtk2_check" { } #If GTK GUI, check for GTK+ 2 default=yes
+      // edf "gnome_check" "gnome_check" { } #If GTK GUI, check for GNOME default=no
+      // edf "motif_check" "motif_check" { } #If auto-select GUI, check for Motif default=yes
+      // edf "athena_check" "athena_check" { } #If auto-select GUI, check for Athena default=yes
+      // edf "nextaw_check" "nextaw_check" { } #If auto-select GUI, check for neXtaw default=yes
+      // edf "carbon_check" "carbon_check" { } #If auto-select GUI, check for Carbon default=yes
+      // edf "gtktest" "gtktest" { } #Do not try to compile and run a test GTK program
+    */
+      // edf "acl" "acl" { } #Don't check for ACL support.
+      // edf "gpm" "gpm" { } #Don't use gpm (Linux mouse daemon).
+      // edf "nls" "nls" { } #Don't support NLS (gettext()).
+    ; 
+
+  optionals = ["python"];
+
+  extraAttrs = co : {
+    name = "vim_configurable-7.1";
+
+  src = args.fetchurl {
+    url = ftp://ftp.nluug.nl/pub/editors/vim/unix/vim-7.1.tar.bz2;
+    sha256 = "0w6gy49gdbw7hby5rjkjpa7cdvc0z5iajsm4j1h8108rvfam22kz";
+  };
+
+  postInstall = "
+    rpath=`patchelf --print-rpath \$out/bin/vim`;
+    for i in $\buildInputs; do
+      echo adding \$i/lib
+      rpath=\$rpath:\$i/lib
+    done
+    echo \$buildInputs
+    echo \$rpath
+    patchelf --set-rpath \$rpath \$out/bin/{vim,gvim}
+  ";
+
+  meta = {
+    description = "The most popular clone of the VI editor";
+    homepage = "www.vim.org";
+  };
+};
+} ) args
diff --git a/pkgs/applications/editors/vim/default.nix b/pkgs/applications/editors/vim/default.nix
index a08808a4756..2f1677622a9 100644
--- a/pkgs/applications/editors/vim/default.nix
+++ b/pkgs/applications/editors/vim/default.nix
@@ -9,17 +9,28 @@ let
 	["athenaGUI" "libXau" "libXt" "libXaw" "libXpm" "libXext" "x11Support"]
 	["x11Support" "libX11"]
 	["hugeFeatures"]
+	["pythonSupport" "python"]
+	["perlSupport" "perl"]
+	["tclSupport" "tcl"]
 	["true" "ncurses"]
 	["false" "libSM"]
 	];
 	nameSuffixes = [
 	"hugeFeatures" "-huge"
 	"x11Support" "-X11"
+	"pythonSupport" "-python"
+	"perlSupport" "-perl"
+	"tclSupport" "-tcl"
+	"ximSupport" "-xim"
 	];
 	configFlags = [
-	"true" " --disable-xim "
+	"true" " "
 	"x11Support" " --enable-gui=auto "
-	"hugeFeatures" "--with-features=huge --enable-cscope --enable-multibyte --enable-xsmp"
+	"hugeFeatures" "--with-features=huge --enable-cscope --enable-multibyte --enable-xsmp "
+	"pythonSupport" " --enable-pythoninterp "
+	"perlSupport" " --enable-perlinterp "
+	"tclSupport" " --enable-tclinterp "
+	"ximSupport" " --enable-xim "
 	];
 	buildInputsNames = args.lib.filter (x: (null!=getVal x)) 
 		(args.lib.uniqList {inputList = 
@@ -44,7 +55,10 @@ args.stdenv.mkDerivation {
   preBuild="touch src/auto/link.sed";
   configureFlags = args.lib.condConcat "" configFlags check;
 
+  NIX_LDFLAGS = "-lpthread -lutil";
+
   meta = {
     description = "The most popular clone of the VI editor";
+    homepage = http://www.vim.org;
   };
 }
diff --git a/pkgs/applications/graphics/ImageMagick/6.3.8-5.nix b/pkgs/applications/graphics/ImageMagick/6.3.8-5.nix
new file mode 100644
index 00000000000..83c7075f8e5
--- /dev/null
+++ b/pkgs/applications/graphics/ImageMagick/6.3.8-5.nix
@@ -0,0 +1,26 @@
+args: with args;
+stdenv.mkDerivation (rec {
+  name = "ImageMagick-6.3.8-5";
+
+  src = fetchurl {
+    url = "ftp://ftp.imagemagick.org/pub/ImageMagick/${name}.tar.bz2";
+    sha256 = "0lsvi2z5b5zam6yvjzsyjpa36rg1c0kczifz73k9b4v8zz9a9vfl";
+  };
+
+  configureFlags = " --with-dots --with-gs-font-dir="+ ghostscript +
+		"/share/ghostscript/fonts --with-gslib " +(
+		if args ? tetex then " --with-frozenpaths " else ""
+		);
+
+  buildInputs = [bzip2 freetype ghostscript graphviz libjpeg libpng 
+		libtiff libX11 libxml2 zlib libtool] ++ (if args ? tetex then [args.tetex] else [])
+		 ++ (if args ? librsvg then [args.librsvg] else []);
+
+  meta = {
+    homepage = http://www.imagemagick.org;
+  };
+} // (if args ? tetex then {
+	preConfigure = "
+		export DVIDecodeDelegate=${args.tetex}/bin/dvips
+	";
+} else {}))
diff --git a/pkgs/applications/graphics/ImageMagick/default.nix b/pkgs/applications/graphics/ImageMagick/default.nix
deleted file mode 100644
index 0f814bd3829..00000000000
--- a/pkgs/applications/graphics/ImageMagick/default.nix
+++ /dev/null
@@ -1,23 +0,0 @@
-args: with args;
-(stdenv.mkDerivation ({
-  name = "ImageMagick-6.3.5";
-
-  src = fetchurl {
-    url = ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick-6.3.5-5.tar.bz2;
-    sha256 = "0avq6kllxw552krxgsa72c1b44zwyhwi38dk4a4ij3fqy0svy9zh";
-  };
-
-  configureFlags = " --with-dots --with-gs-font-dir="+ ghostscript +
-		"/share/ghostscript/fonts --with-gslib " +(
-		if args ? tetex then " --with-frozenpaths " else ""
-		);
-
-  buildInputs = [bzip2 freetype ghostscript graphviz libjpeg libpng 
-		libtiff libX11 libxml2 zlib ] ++ (if args ? tetex then [args.tetex] else [])
-		 ++ (if args ? librsvg then [args.librsvg] else [])
-		;
-} // (if args ? tetex then {
-	preConfigure = "
-		export DVIDecodeDelegate=${args.tetex}/bin/dvips
-	";
-} else {})))
diff --git a/pkgs/applications/graphics/PythonMagick/default.nix b/pkgs/applications/graphics/PythonMagick/default.nix
index 9096de6baa1..3e01dc7b2db 100644
--- a/pkgs/applications/graphics/PythonMagick/default.nix
+++ b/pkgs/applications/graphics/PythonMagick/default.nix
@@ -10,4 +10,7 @@ stdenv.mkDerivation {
 
   buildInputs = [python boost pkgconfig imagemagick];
 
+  meta = {
+    homepage = http://www.imagemagick.org/script/api.php;
+  };
 }
diff --git a/pkgs/applications/graphics/dia/default.nix b/pkgs/applications/graphics/dia/default.nix
index 606d58865b8..92bc477036a 100644
--- a/pkgs/applications/graphics/dia/default.nix
+++ b/pkgs/applications/graphics/dia/default.nix
@@ -11,5 +11,6 @@ stdenv.mkDerivation {
 
   meta = {
     description = "Gnome Diagram drawing software.";
+    homepage = http://www.gnome.org/projects/dia;
   };
 }
diff --git a/pkgs/applications/graphics/exrdisplay/default.nix b/pkgs/applications/graphics/exrdisplay/default.nix
new file mode 100644
index 00000000000..f82f07602f8
--- /dev/null
+++ b/pkgs/applications/graphics/exrdisplay/default.nix
@@ -0,0 +1,27 @@
+args: with args;
+
+assert fltk.flag_set_gl;
+stdenv.mkDerivation {
+
+  name ="openexr_viewers-1.0.1";
+
+  src = fetchurl {
+    url =  "http://download.savannah.nongnu.org/releases/openexr/openexr_viewers-1.0.1.tar.gz";
+    sha256 = "1w5qbcdp7sw48z1wk2v07f7p14vqqb1m2ncxyxnbkm9f4ab0ymg6";
+  };
+
+  inherit fltk mesa;
+
+  configurePhase = "
+    # don't know why.. adding these flags it works
+    #export CXXFLAGS=`fltk-config --use-gl --cxxflags --ldflags`
+    ./configure --prefix=\$out --with-fltk-config=\$fltk/bin/fltk-config";
+
+  buildInputs = [openexr fltk pkgconfig mesa which openexr_ctl];
+
+  meta = { 
+      description = "tool to view OpenEXR images";
+      homepage = http://openexr.com;
+      license = "BSD-like";
+  };
+}
diff --git a/pkgs/applications/graphics/f-spot/default.nix b/pkgs/applications/graphics/f-spot/default.nix
index 0da1d4fe473..40329412449 100644
--- a/pkgs/applications/graphics/f-spot/default.nix
+++ b/pkgs/applications/graphics/f-spot/default.nix
@@ -23,4 +23,8 @@ stdenv.mkDerivation {
   ];
 
   inherit monoDLLFixer gtksharp sqlite libgnomeui;
+
+  meta = {
+    homepage = http://f-spot.org;
+  };
 }
diff --git a/pkgs/applications/graphics/gimp/default.nix b/pkgs/applications/graphics/gimp/default.nix
index cda94032511..5ba3c11184d 100644
--- a/pkgs/applications/graphics/gimp/default.nix
+++ b/pkgs/applications/graphics/gimp/default.nix
@@ -4,10 +4,10 @@
 }:
 
 stdenv.mkDerivation {
-  name = "gimp-2.4.0";
+  name = "gimp-2.4.4";
   src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gimp/v2.4/gimp-2.4.0.tar.bz2;
-    sha256 = "1p594r45hxk14469ma8g5j96nw5q9j6a3i0n6hbakfsh41izpsnx";
+    url = ftp://ftp.gtk.org/pub/gimp/v2.4/gimp-2.4.4.tar.bz2;
+    sha256 = "1mnl30b4p7c2lxi68z3fhwmganhwppyiw7r0m3r90vnakcawfnfh";
   };
   
   buildInputs = [
diff --git a/pkgs/applications/graphics/gocr/0.44.nix b/pkgs/applications/graphics/gocr/0.44.nix
index 4bf7bda50cb..b415fd6fb12 100644
--- a/pkgs/applications/graphics/gocr/0.44.nix
+++ b/pkgs/applications/graphics/gocr/0.44.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 fetchurl {
 		url = http://prdownloads.sourceforge.net/jocr/gocr-0.44.tar.gz;
@@ -9,10 +9,11 @@ fetchurl {
 		buildInputs = [];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 stdenv.mkDerivation rec {
 	name = "gocr";
 	builder = writeScript (name + "-builder")
-		(textClosure [doConfigure doMakeInstall doForceShare doPropagate]);
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare doPropagate]);
 	meta = {
 		description = "
 		GPL Optical Character Recognition
diff --git a/pkgs/applications/graphics/gocr/default.nix b/pkgs/applications/graphics/gocr/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/graphics/gocr/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/graphics/gqview/default.nix b/pkgs/applications/graphics/gqview/default.nix
index 292c3b29bdd..a8132e30c72 100644
--- a/pkgs/applications/graphics/gqview/default.nix
+++ b/pkgs/applications/graphics/gqview/default.nix
@@ -17,5 +17,6 @@ stdenv.mkDerivation {
 
   meta = {
     description = "A fast image viewer";
+    homepage = http://gqview.sourceforge.net;
   };
 }
diff --git a/pkgs/applications/graphics/inkscape/default.nix b/pkgs/applications/graphics/inkscape/default.nix
index d09263576e5..b8ff2486330 100644
--- a/pkgs/applications/graphics/inkscape/default.nix
+++ b/pkgs/applications/graphics/inkscape/default.nix
@@ -1,36 +1,19 @@
-{ stdenv, fetchurl, pkgconfig,
-  perl, perlXMLParser,
-  gtk, libXft, fontconfig,
-  libpng, lcms,
-  zlib, popt,
-  boehmgc,
-  libxml2, libxslt,
-  glib,
-  gtkmm, glibmm, libsigcxx,
-  boost,
-  gettext
-}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "inkscape-0.45";
+stdenv.mkDerivation rec {
+  name = "inkscape-0.45.1";
 
   src = fetchurl {
-    url = mirror://sourceforge/inkscape/inkscape-0.45.1.tar.gz;
+    url = "mirror://sf/inkscape/${name}.tar.gz";
     sha256 = "1y0b9bm8chn6a2ip99dj4dhg0188yn67v571ha0x38wrlmvn4k0d";
   };
 
   buildInputs = [
-    pkgconfig
-    perl perlXMLParser
-    gtk libXft fontconfig
-    libpng
-    zlib popt
-    boehmgc
-    libxml2 libxslt
-    glib
-    gtkmm glibmm libsigcxx
-    lcms
-    boost
-    gettext
+    pkgconfig perl perlXMLParser gtk libXft fontconfig libpng zlib popt boehmgc
+    libxml2 libxslt glib gtkmm glibmm libsigcxx lcms boost gettext
   ];
+
+  meta = {
+    homepage = http://www.inkscape.org;
+  };
 }
diff --git a/pkgs/applications/graphics/xara/default.nix b/pkgs/applications/graphics/xara/default.nix
index 495e1f93076..89ba789524f 100644
--- a/pkgs/applications/graphics/xara/default.nix
+++ b/pkgs/applications/graphics/xara/default.nix
@@ -1,5 +1,5 @@
 {stdenv, fetchurl, autoconf, automake, gettext, libtool, cvs, wxGTK, gtk,
-pkgconfig, libxml2, zip, libpng, libjpeg}:
+pkgconfig, libxml2, zip, libpng, libjpeg, shebangfix, perl, freetype}:
 
 stdenv.mkDerivation {
   name = "xaralx-0.7r1766";
@@ -7,9 +7,29 @@ stdenv.mkDerivation {
     url = http://downloads2.xara.com/opensource/XaraLX-0.7r1766.tar.bz2;
     sha256 = "1rcl7hqvcai586jky7hvzxhnq8q0ka2rsmgiq5ijwclgr5d4ah7n";
   };
-  
-  buildInputs = [automake autoconf gettext libtool cvs wxGTK gtk pkgconfig libxml2 zip libpng libjpeg];
+    
+  buildInputs = [automake autoconf gettext libtool cvs wxGTK gtk pkgconfig libxml2 zip libpng libjpeg shebangfix perl];
+
+  inherit freetype libpng libjpeg libxml2;
   configureFlags = "--with-wx-config --disable-svnversion --disable-international";
 
   patches = [./gtk_cflags.patch];
+
+  # Why do I need to add library path for freetype ? 
+  installPhase = "
+    make install
+    ensureDir \$out/lib
+    mv \$out/{bin,lib}/XaraLX
+cat >> \$out/bin/XaraLX << EOF
+#!/bin/sh
+LD_LIBRARY_PATH=\$freetype/lib:\$libpng/lib:\$libjpeg/lib:\$libxml2/lib:
+\$out/lib/XaraLX \"\\$@\"
+EOF
+chmod +x \$out/bin/XaraLX
+";
+ 
+  patchPhase = "
+    find . -iname \"*.pl\" | xargs shebangfix;
+    unset patchPhase; patchPhase
+   "; 
 }
diff --git a/pkgs/applications/graphics/xfig/builder.sh b/pkgs/applications/graphics/xfig/builder.sh
index de64fbce78f..dc943180508 100644
--- a/pkgs/applications/graphics/xfig/builder.sh
+++ b/pkgs/applications/graphics/xfig/builder.sh
@@ -1,5 +1,4 @@
 source $stdenv/setup
-source $makeWrapper
 
 makeFlags="XAWLIB=-lXaw3d BINDIR=$out/bin XAPPLOADDIR=$out/etc/X11/app-defaults LIBDIR=$out/lib/X11 XFIGDOCDIR=$out/share/doc/xfig MANPATH=$out/man"
 
@@ -16,9 +15,7 @@ installCommand=myInstall
 myInstall() {
     make install.all $makeFlags
 
-    mv $out/bin/xfig $out/bin/.xfig
-
-    makeWrapper $out/bin/.xfig $out/bin/xfig \
+    wrapProgram $out/bin/xfig \
         --set XAPPLRESDIR $out/etc/X11/app-defaults
 }
 
diff --git a/pkgs/applications/graphics/xfig/default.nix b/pkgs/applications/graphics/xfig/default.nix
index 0d94d4a655d..9b0d009e417 100644
--- a/pkgs/applications/graphics/xfig/default.nix
+++ b/pkgs/applications/graphics/xfig/default.nix
@@ -11,13 +11,12 @@ stdenv.mkDerivation {
 
   builder = ./builder.sh;
 
-  buildInputs = [imake x11 libXpm libXmu libXi libXp Xaw3d libpng libjpeg];
-
-  inherit makeWrapper;
+  buildInputs = [imake x11 libXpm libXmu libXi libXp Xaw3d libpng libjpeg makeWrapper];
 
   NIX_CFLAGS_COMPILE = "-I${libXpm}/include/X11";
 
   meta = {
     description = "An interactive drawing tool for X11";
+    homepage = http://xfig.org;
   };
 }
diff --git a/pkgs/applications/graphics/xscreensaver/5.04.nix b/pkgs/applications/graphics/xscreensaver/5.04.nix
new file mode 100644
index 00000000000..afdab99999f
--- /dev/null
+++ b/pkgs/applications/graphics/xscreensaver/5.04.nix
@@ -0,0 +1,39 @@
+args : with args; let localDefs = builderDefs (args // {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://www.jwz.org/xscreensaver/xscreensaver-5.04.tar.gz;
+			sha256 = "1mx6zc6rvb6pr9wb6mv4ljiii9ybw0dshd74aclf7rlmfx4hn86i";
+		};
+		useConfig = true;
+		reqsList = [
+			["true" "libX11" "gtk" "pkgconfig" "bc" "perl" "intltool" "libXmu"]
+			["GL" "mesa"]
+			["GUI" "gtk" "libxml2" "libglade"]
+			["jpeg" "libjpeg"]
+			["false"]
+		];
+		configFlags = [
+			"GL" " --with-gl "
+			"gdkpixbuf" " --with-pixbuf "
+			"DPMS" " --with-dpms "
+			"true" (" --with-x-app-defaults=\$out/share/xscreensaver/app-defaults "+
+				" --with-hackdir=\$out/share/xscreensaver-hacks ")
+		];
+	}) null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+	preConfigure = FullDepEntry ("
+		sed -e 's%@GTK_DATADIR@%@datadir@% ; s%@PO_DATADIR@%@datadir@%' "+
+		"-i driver/Makefile.in po/Makefile.in.in;
+	") [minInit doUnpack];
+in
+stdenv.mkDerivation rec {
+	name = "xscreensaver-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [preConfigure doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	The X screensaver daemon. Run xscreensaver-demo to configure.
+";
+	};
+}
diff --git a/pkgs/applications/jedit/default.nix b/pkgs/applications/jedit/default.nix
new file mode 100644
index 00000000000..c43b7f86914
--- /dev/null
+++ b/pkgs/applications/jedit/default.nix
@@ -0,0 +1,28 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "jedit-4.2";
+
+  src = fetchurl {
+    url = mirror://sf/jedit/jedit42source.tar.gz;
+    sha256 = "1ckqghsw2r30kfkqfgjl4k47gdwpz8c1h85haw0y0ymq4rqh798j";
+  };
+
+  phases = "unpackPhase buildPhase";
+
+  buildPhase = "
+     sed -i 's/\\<SplashScreen\\>/org.gjt.sp.jedit.gui.SplashScreen/g' org/gjt/sp/jedit/GUIUtilities.java
+    ant dist
+    ensureDir $out/lib
+    cp jedit.jar $out/lib
+    ensureDir \$out/lib/modes
+    cp modes/catalog \$out/lib/modes
+  ";
+
+  buildInputs = [ant];
+
+  meta = { 
+      description = "really nice programmers editor written in Java. Give it a try";
+      homepage = http://www.jedit.org;
+      license = "GPL";
+  };
+}
diff --git a/pkgs/applications/jedit/wrapper.nix b/pkgs/applications/jedit/wrapper.nix
new file mode 100644
index 00000000000..8af3d96918d
--- /dev/null
+++ b/pkgs/applications/jedit/wrapper.nix
@@ -0,0 +1,18 @@
+args: with args;
+stdenv.mkDerivation {
+    name = jedit.name+"_startscript";
+
+    java = jre+"/bin/java";
+    jeditjar = jedit+"/lib/jedit.jar";
+
+    phases = "buildPhase";
+
+    buildPhase = "
+ensureDir \$out/bin
+cat > \$out/bin/${jedit.name} << EOF
+#!/bin/sh
+exec $java -jar $jeditjar \\$*
+EOF
+  chmod +x \$out/bin/${jedit.name}
+";
+}
diff --git a/pkgs/applications/misc/acrobat-reader/default.nix b/pkgs/applications/misc/acrobat-reader/default.nix
index 1cbdd09bc58..3c2e5bafeb2 100644
--- a/pkgs/applications/misc/acrobat-reader/default.nix
+++ b/pkgs/applications/misc/acrobat-reader/default.nix
@@ -18,4 +18,8 @@ stdenv.mkDerivation {
     (if xineramaSupport then libXinerama else null)
   ];
   inherit fastStart;
+
+  meta = {
+    homepage = http://www.adobe.com/products/reader;
+  };
 }
diff --git a/pkgs/applications/misc/audio/sox/default.nix b/pkgs/applications/misc/audio/sox/default.nix
index 91bd5be0788..c0cf9d91b73 100644
--- a/pkgs/applications/misc/audio/sox/default.nix
+++ b/pkgs/applications/misc/audio/sox/default.nix
@@ -1,5 +1,5 @@
 args:
-( args.mkDerivationByConfigruation {
+( args.mkDerivationByConfiguration {
     flagConfig = {
     mandatory = { implies = [ "no_oss" "no_sun_audio" ]; };
     # are these options of interest? We'll see
diff --git a/pkgs/applications/misc/blender/default.nix b/pkgs/applications/misc/blender/default.nix
new file mode 100644
index 00000000000..aa50f67719c
--- /dev/null
+++ b/pkgs/applications/misc/blender/default.nix
@@ -0,0 +1,41 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "blender-2.45";
+
+  src = fetchurl {
+    url = http://download.blender.org/source/blender-2.45.tar.gz;
+    sha256 = "1bi7j1fcvrpb96sjpcbm4sldf359sgskfhv7a8pgcxj0bnhp47wj";
+  };
+
+  phases="unpackPhase buildPhase";
+
+  inherit scons SDL freetype openal python openexr mesa;
+
+  buildInputs = [python scons
+         gettext libjpeg libpng zlib freetype /* fmod smpeg */ freealut openal x11 mesa inputproto libtiff libXi ];
+
+  # patch SConstruct so that we can pass on additional include.  Either blender
+  # or openEXR is broken. I think OpenEXR should use include "" isntead of <> to
+  # include files beeing in the same directory
+  buildPhase = "
+    sed -i -e \"s=##### END SETUP ##########=env['CPPFLAGS'].append(os.getenv('CPPFLAGS').split(':'))\\n##### END SETUP ##########=\" SConstruct\n"
+    + " CPPFLAGS=-I$openexr/include/OpenEXR"
+    + " scons PREFIX=\$out/nix-support"
+    + " BF_SDL=\$SDL"
+    + " BF_SDL_LIBPATH=\$SDL/lib"
+    + " BF_FREETYPE=\$freetype"
+    + " BF_OPENAL=\$openal"
+    + " BF_PYTHON=\$python"
+    + " BF_OPENEXR_INC=\$openexr/include"
+    + " BF_OPENEXR_LIBPATH=\$openexr/lib"
+    + " BF_INSTALLDIR=\$out/nix-support/dontLinkThatMuch \n"
+    + " ensureDir \$out/bin\n"
+    + " ln -s \$out/nix-support/dontLinkThatMuch/blender \$out/bin/blender"
+    ;
+
+  meta = { 
+      description = "3D Creation/Animation/Publishing System";
+      homepage = http://www.blender.org;
+      license = "GPL-2 BL";
+    };
+}
diff --git a/pkgs/applications/misc/bluez-firmware/default.nix b/pkgs/applications/misc/bluez-firmware/default.nix
index 91b8dbdf8f4..f38a269408d 100644
--- a/pkgs/applications/misc/bluez-firmware/default.nix
+++ b/pkgs/applications/misc/bluez-firmware/default.nix
@@ -6,4 +6,8 @@ stdenv.mkDerivation {
     url = http://bluez.sf.net/download/bluez-firmware-1.1.tar.gz;
     md5 = "2f1c2d939108c865dd07bae3e819c573";
   };
+
+  meta = {
+    homepage = http://www.bluez.org;
+  };
 }
diff --git a/pkgs/applications/misc/bluez-utils/default.nix b/pkgs/applications/misc/bluez-utils/default.nix
index 7cf88851fc3..06bc2b2555f 100644
--- a/pkgs/applications/misc/bluez-utils/default.nix
+++ b/pkgs/applications/misc/bluez-utils/default.nix
@@ -7,4 +7,8 @@ stdenv.mkDerivation {
     md5 = "ae3729ab5592be06ed01b973d4b3e9fe";
   };
   buildInputs = [bluezLibs];
+
+  meta = {
+    homepage = http://www.bluez.org;
+  };
 }
diff --git a/pkgs/applications/misc/d4x/default.nix b/pkgs/applications/misc/d4x/default.nix
index 5a20893e9f3..f4ad3cc8421 100644
--- a/pkgs/applications/misc/d4x/default.nix
+++ b/pkgs/applications/misc/d4x/default.nix
@@ -1,10 +1,10 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "d4x-2.5.7.1";
   
-  inherit (args) boost;
+  inherit boost;
 
-  src = args.fetchurl {
+  src = fetchurl {
     url =  http://d4x.krasu.ru/files/d4x-2.5.7.1.tar.bz2;
     sha256 = "1i1jj02bxynisqapv31481sz9jpfp3f023ky47spz1v1wlwbs13m";
   };
@@ -12,7 +12,7 @@ args.stdenv.mkDerivation {
   configurePhase = "./configure --prefix=\$out "
     + " --with-boost-libdir=\$boost/lib"
     + " --with-boost-includedir=\$boost/include";
-  buildInputs =(with args; [gtk glib pkgconfig openssl boost]);
+  buildInputs = [gtk glib pkgconfig openssl boost];
 
   meta = { 
       description = "graphical download manager";
diff --git a/pkgs/applications/misc/djvulibre/default.nix b/pkgs/applications/misc/djvulibre/default.nix
index 611f6f08909..81aa12e59f6 100644
--- a/pkgs/applications/misc/djvulibre/default.nix
+++ b/pkgs/applications/misc/djvulibre/default.nix
@@ -1,7 +1,4 @@
-{stdenv, fetchurl,
-qt, libX11, libjpeg, libtiff, libpng, ghostscript, zlib, libungif,
-x11, mesa
-}:
+args: with args;
 stdenv.mkDerivation {
   name = "djvulibre-3.5.19";
 
@@ -18,6 +15,7 @@ stdenv.mkDerivation {
 	DjVu libre - a library and a viewer for djvu format - compression for
 	scanned images.
 ";
+    homepage = http://djvu.sourceforge.net;
   };
 }
 
diff --git a/pkgs/applications/misc/fetchmail/default.nix b/pkgs/applications/misc/fetchmail/default.nix
index 95fc61668fc..9639ff19fb0 100644
--- a/pkgs/applications/misc/fetchmail/default.nix
+++ b/pkgs/applications/misc/fetchmail/default.nix
@@ -1,7 +1,14 @@
-args: with args; stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name="fetchmail-6.3.8";
   src = fetchurl {
     url = http://download.berlios.de/fetchmail/fetchmail-6.3.8.tar.bz2;
     sha256 = "5612f9af367f641e0efd084f44fcf1889669e711dbd8c60f6b7953e494d1b09b";
   };
+
+  patches = [ ./security-fix.patch ];
+
+  meta = {
+    homepage = http://www.fetchmail.info;
+  };
 }
diff --git a/pkgs/applications/misc/fetchmail/security-fix.patch b/pkgs/applications/misc/fetchmail/security-fix.patch
new file mode 100644
index 00000000000..4d48c7aa055
--- /dev/null
+++ b/pkgs/applications/misc/fetchmail/security-fix.patch
@@ -0,0 +1,11 @@
+--- old/sink.c	(revision 5118)
++++ new/sink.c	(revision 5119)
+@@ -262,7 +262,7 @@
+     const char *md1 = "MAILER-DAEMON", *md2 = "MAILER-DAEMON@";
+ 
+     /* don't bounce in reply to undeliverable bounces */
+-    if (!msg->return_path[0] ||
++    if (!msg || !msg->return_path[0] ||
+ 	strcmp(msg->return_path, "<>") == 0 ||
+ 	strcasecmp(msg->return_path, md1) == 0 ||
+ 	strncasecmp(msg->return_path, md2, strlen(md2)) == 0)
diff --git a/pkgs/applications/misc/flite/default.nix b/pkgs/applications/misc/flite/default.nix
index 291cce6c1f9..ad3b9df164d 100644
--- a/pkgs/applications/misc/flite/default.nix
+++ b/pkgs/applications/misc/flite/default.nix
@@ -1,8 +1,8 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "flite-1.3-release";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://www.speech.cs.cmu.edu/flite/packed/flite-1.3/flite-1.3-release.tar.gz;
     sha256 = "12wanxx57bbqgkag54dlqzv6h2kr9053p0z8mkxs0mqy03vja8lj";
   };
@@ -18,8 +18,6 @@ args.stdenv.mkDerivation {
     cp -r bin \$out
   ";
 
-  buildInputs = (with args; []);
-
   meta = { 
       description = "Flite text to speech engine";
       homepage = http://www.speech.cs.cmu.edu/flite/download.html;
diff --git a/pkgs/applications/misc/freemind/default.nix b/pkgs/applications/misc/freemind/default.nix
new file mode 100644
index 00000000000..b7bc3f3c8dd
--- /dev/null
+++ b/pkgs/applications/misc/freemind/default.nix
@@ -0,0 +1,45 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "freemind-0.9.0_Beta_13";
+
+  src = fetchurl {
+    url = http://downloads.sourceforge.net/freemind/freemind-src-0.9.0_Beta_13_icon_butterfly.tar.gz;
+    sha256 = "00389bhg73qknydrq0f3bskb5lyrdg2p58mnnp19wdvzzmfbic4w";
+  };
+
+  buildInputs = [jdk ant];
+
+  inherit jre;
+
+  phases="buildPhase installPhase";
+
+  buildPhase="ant dist";
+# LIBXCB_ALLOW_SLOPPY_LOCK=true :
+# don't know yet what this option really means but I'm no longer getting
+#   Checking Java Version...
+#   Locking assertion failure.  Backtrace:
+#   java: xcb_xlib.c:82: xcb_xlib_unlock: Assertion `c->xlib.lock' failed
+# this way
+# reference and more info https://bugs.launchpad.net/ubuntu/+source/sun-java5/+bug/86103
+# JDK 7 beta seems to have fixed this (bug ?)
+
+  installPhase="
+    ensureDir \$out/{bin,nix-support}
+    cp -r ../bin/dist \$out/nix-support
+    sed -i 's/which/type -p/' \$out/nix-support/dist/freemind.sh
+    cat > \$out/bin/freemind << EOF
+#!/bin/sh
+export LIBXCB_ALLOW_SLOPPY_LOCK=true
+export JAVA_HOME=\$jre
+\$out/nix-support/dist/freemind.sh
+EOF
+
+    chmod +x \$out/{bin/freemind,nix-support/dist/freemind.sh}
+    ";
+
+  meta = {
+      description = "mind mapping software";
+      homepage = http://freemind.sourceforge.net/wiki/index.php/Main_Page;
+      license = "GPL";
+  }; 
+}
diff --git a/pkgs/applications/misc/gkrellm/default.nix b/pkgs/applications/misc/gkrellm/default.nix
new file mode 100644
index 00000000000..ae5386dcd1e
--- /dev/null
+++ b/pkgs/applications/misc/gkrellm/default.nix
@@ -0,0 +1,33 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "gkrellm-2.3.1";
+  src = fetchurl {
+    url = http://members.dslextreme.com/users/billw/gkrellm/gkrellm-2.3.1.tar.bz2;
+    sha256 = "1a2a7e3ee9d1f2d7305da0d33d9be71ffe5d1903ed6a9c69cf77ffe10fc95b4d";
+  };
+
+  buildInputs = [gettext pkgconfig glib gtk libX11 libSM libICE];
+
+  # Makefiles are patched to fix references to `/usr/X11R6' and to add
+  # `-lX11' to make sure libX11's store path is in the RPATH.
+  patchPhase = ''
+     echo "patching makefiles..."
+     for i in Makefile src/Makefile server/Makefile
+     do
+       cat "$i" | sed -e "s|/usr/X11R6|${libX11}|g ;
+                          s|-lICE|-lX11 -lICE|g" > ",,tmp" &&	\
+       mv ",,tmp" "$i"
+     done '';
+
+  buildPhase = ''
+     make PREFIX="$out" '';
+  installPhase = ''
+     make install PREFIX="$out" '';
+
+  meta = {
+    description = "GKrellM, a themeable process stack of system monitors.";
+    homepage = http://members.dslextreme.com/users/billw/gkrellm/gkrellm.html;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/applications/misc/gphoto2/default.nix b/pkgs/applications/misc/gphoto2/default.nix
index caab251edd9..e6dad337eb3 100644
--- a/pkgs/applications/misc/gphoto2/default.nix
+++ b/pkgs/applications/misc/gphoto2/default.nix
@@ -1,10 +1,16 @@
-{stdenv, fetchurl, pkgconfig, libgphoto2, libexif, popt}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "gphoto2-2.2.0";
+stdenv.mkDerivation rec {
+  name = "gphoto2-2.4.0";
   src = fetchurl {
-    url = mirror://sourceforge/gphoto/gphoto2-2.2.0.tar.bz2;
-    md5 = "f5c1f83185db598b4ca52889964a5e84";
+    url = "mirror://sourceforge/gphoto/${name}.tar.bz2";
+    sha256 = "1rf4w5m35dsi8dkwwnh4wg70xivdi9j79f2dy3rq90p1v8sar9ca";
+  };
+  buildInputs = [pkgconfig libgphoto2 libexif popt gettext];
+# There is a bug in 2.4.0 configure.ac (in their m4 macroses)
+  patchPhase = "sed -e 's@_tmp=true@_tmp=false@' -i configure configure.ac";
+
+  meta = {
+    homepage = http://www.gphoto.org;
   };
-  buildInputs = [pkgconfig libgphoto2 libexif popt];
 }
diff --git a/pkgs/applications/misc/gv/default.nix b/pkgs/applications/misc/gv/default.nix
index 2a0603e27c9..4566761e690 100644
--- a/pkgs/applications/misc/gv/default.nix
+++ b/pkgs/applications/misc/gv/default.nix
@@ -13,4 +13,8 @@ stdenv.mkDerivation {
   postConfigure = [ "sed 's|\\<gs\\>|${ghostscriptX}/bin/gs|g' -i src/*.am src/*.ad" ];
 
   inherit ghostscriptX;
+
+  meta = {
+    homepage = http://wwwthep.physik.uni-mainz.de/~plass/gv;
+  };
 }
diff --git a/pkgs/applications/misc/hello/ex-1/default.nix b/pkgs/applications/misc/hello/ex-1/default.nix
index 6411e1a845e..51b2ccb58ed 100644
--- a/pkgs/applications/misc/hello/ex-1/default.nix
+++ b/pkgs/applications/misc/hello/ex-1/default.nix
@@ -11,5 +11,6 @@ stdenv.mkDerivation {
 
   meta = {
     description = "GNU Hello, a classic computer science tool";
+    homepage = http://www.gnu.org/software/hello/;
   };
 }
diff --git a/pkgs/applications/misc/lyx/default.nix b/pkgs/applications/misc/lyx/default.nix
new file mode 100644
index 00000000000..246b8caa3ca
--- /dev/null
+++ b/pkgs/applications/misc/lyx/default.nix
@@ -0,0 +1,18 @@
+# I haven't put much effort into this expressions .. so some optional depencencies may be missing - Marc
+args:
+args.stdenv.mkDerivation {
+  name = "lyx-1.5.3";
+
+  src = args.fetchurl {
+    url = http://lyx.cybermirror.org/stable/lyx-1.5.3.tar.bz2;
+    sha256 = "1q0xlhrvj87iw9rk9z2vfka4jw5pw7n5fsmmiyzram9y4hghavav";
+  };
+
+  buildInputs =(with args; [tetex qt python]);
+
+  meta = { 
+      description = "WYSIWYM frontend for LaTeX, DocBook, etc.";
+      homepage = "http://www.lyx.org";
+      license = "GPL2";
+  };
+}
diff --git a/pkgs/applications/misc/maxima/default.nix b/pkgs/applications/misc/maxima/default.nix
index 9b2fe291310..72770c9a918 100644
--- a/pkgs/applications/misc/maxima/default.nix
+++ b/pkgs/applications/misc/maxima/default.nix
@@ -4,15 +4,14 @@ stdenv.mkDerivation {
 
   src =	fetchurl {
 		name = "maxima-5.13.0.tar.gz";
-		url = http://downloads.sourceforge.net/maxima/maxima-5.13.0.tar.gz?modtime=1188046120&big_mirror=1;
+		url = mirror://sf/maxima/maxima-5.13.0.tar.gz;
 		sha256 = "11zidbbp4cbgsmdfyf9w0j7345ydka469ba0my7p73zqhnby09cn";
 	};
 
   buildInputs =[clisp];
 
   meta = {
-    description = "
-	Maxima computer algebra system
-";
+    description = "Maxima computer algebra system";
+    homepage = http://maxima.sourceforge.net;
   };
 }
diff --git a/pkgs/applications/misc/mrxvt/default.nix b/pkgs/applications/misc/mrxvt/default.nix
index aaabef2b6b8..f58fff56bc0 100644
--- a/pkgs/applications/misc/mrxvt/default.nix
+++ b/pkgs/applications/misc/mrxvt/default.nix
@@ -10,11 +10,11 @@ let
     };
 };
 
-in args.stdenv.mkDerivation {
+in stdenv.mkDerivation {
 
   inherit (co) buildInputs configureFlags;
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = mirror://sourceforge/materm/mrxvt-0.5.3.tar.gz;
     sha256 = "04flnn58hp4qvvk6jzyipsj13v1qyrjabgbw5laz5cqxvxzpncp2";
   };
diff --git a/pkgs/applications/misc/pgadmin/default.nix b/pkgs/applications/misc/pgadmin/default.nix
new file mode 100644
index 00000000000..624c1dfcb61
--- /dev/null
+++ b/pkgs/applications/misc/pgadmin/default.nix
@@ -0,0 +1,18 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "pgadmin3-1.8.1";
+
+  src = fetchurl {
+    name = "pgadmin3-v1.8.1.tar.gz";
+    url = "http://ftp3.de.postgresql.org/pub/Mirrors/ftp.postgresql.org//pgadmin3/release/v1.8.1/src/pgadmin3-1.8.1.tar.gz";
+    sha256 = "1vnpbgb2ksvcgbzab4jjspwvs5cvam53azinfavjad4kpjczdywb";
+  };
+
+  buildInputs = [postgresql wxGTK libxml2 libxslt openssl];
+
+  meta = { 
+      description = "postgresql admin gui tool";
+      homepage = http://www.pgadmin.org;
+      license = "GPL2";
+    };
+}
diff --git a/pkgs/applications/misc/pinfo/default.nix b/pkgs/applications/misc/pinfo/default.nix
index b44cca5ff2c..d8dba39ccb5 100644
--- a/pkgs/applications/misc/pinfo/default.nix
+++ b/pkgs/applications/misc/pinfo/default.nix
@@ -1,10 +1,12 @@
-{stdenv, fetchurl, ncurses}:
+{stdenv, fetchurl, ncurses, readline}:
 
 stdenv.mkDerivation {
-  name = "pinfo-0.6.8";
+  name = "pinfo-0.6.9";
   src = fetchurl {
-    url = http://dione.cc/~pborys/software/pinfo/pinfo-0.6.8.tar.gz;
-    md5 = "55feb4ebaa709b52bd00a15ed0fb52fb";
+    url = https://alioth.debian.org/frs/download.php/1498/pinfo-0.6.9.tar.bz2;
+    sha256 = "1rbsz1y7nyz6ax9xfkw5wk6pnrhvwz2xcm0wnfnk4sb2wwq760q3";
   };
-  buildInputs = [ncurses];
+  buildInputs = [ncurses readline];
+
+  configureFlags = "--with-curses=${ncurses} --with-readline=${readline}";
 }
diff --git a/pkgs/applications/misc/procmail/default.nix b/pkgs/applications/misc/procmail/default.nix
index b1d54ef5fc9..50767a7dde8 100644
--- a/pkgs/applications/misc/procmail/default.nix
+++ b/pkgs/applications/misc/procmail/default.nix
@@ -1,4 +1,5 @@
-args: with args; stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name="procmail-3.22";
   buildInputs = [stdenv.gcc.libc];
   installPhase = "
diff --git a/pkgs/applications/misc/pstree/default.nix b/pkgs/applications/misc/pstree/default.nix
index c59148e854e..c26876f2fcb 100644
--- a/pkgs/applications/misc/pstree/default.nix
+++ b/pkgs/applications/misc/pstree/default.nix
@@ -1,14 +1,13 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "pstree-2.31";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://fresh.t-systems-sfr.com/unix/src/misc/pstree-2.31.tar.gz;
     sha256 = "1zzz29gsyra8csk54cyq0pcdxxg3l4gmksq8q1skv2z84g2yxdhh";
   };
 
   unpackPhase="unpackFile \$src; sourceRoot=.";
-  #buildInputs =(with args; []);
   
   buildPhase="pwd; gcc -o pstree pstree.c";
   installPhase="ensureDir \$out/bin; cp pstree \$out/bin";
diff --git a/pkgs/applications/misc/qgis_svn/default.nix b/pkgs/applications/misc/qgis_svn/default.nix
new file mode 100644
index 00000000000..547e941ecac
--- /dev/null
+++ b/pkgs/applications/misc/qgis_svn/default.nix
@@ -0,0 +1,74 @@
+args:
+let optionIncLib = name : attr : " -D${name}_INCLUDE_DIR=${__getAttr attr args}/inc"
+                               + " -D${name}_LIBRARY=${__getAttr attr args}/lib "; # lib 64?
+in
+( args.mkDerivationByConfiguration {
+
+    flagConfig = {
+      mandatory = { 
+        buildInputs = [ "gdal" "cmake" "qt" "flex" "bison" "proj" "geos" "x11" "sqlite" "gsl"]; 
+        cfgOption = [ (optionIncLib "GEOS" "geos") 
+                         (optionIncLib "PROJ" "proj")
+                         (optionIncLib "QT_X11_X11" "qt")
+                         (optionIncLib "QT_X11_Xext" "qt")
+                         (optionIncLib "QT_X11_m" "glibc")
+                         (optionIncLib "SQLITE3" "sqlite")
+
+"-DQT_FONTCONFIG_LIBRARY=${args.fontconfig}/lib"
+"-DQT_FREETYPE_LIBRARY=${args.freetype}/lib"
+"-DQT_PNG_LIBRARY=${args.libpng}/lib"
+"-DQT_X11_ICE_LIBRARY=${args.libICE}/lib"
+"-DQT_X11_SM_LIBRARY=${args.libSM}/lib"
+"-DQT_XCURSOR_LIBRARY=${args.libXcursor}/lib"
+"-DQT_XINERAMA_LIBRARY=${args.libXinerama}/lib"
+"-DQT_XRANDR_LIBRARY=${args.libXrandr}/lib"
+"-DQT_XRENDER_LIBRARY=${args.libXrender}/lib"
+"-DQT_ZLIB_LIBRARY=${args.zlib}/lib"
+                         ];
+
+/* advanced options - feel free to add them if you have time to
+"-DPROJ_INCLUDE_DIR"
+"-DPROJ_LIBRARY"
+"-DQT_X11_X11_LIBRARY"
+"-DQT_X11_Xext_LIBRARY"
+"-DQT_X11_m_LIBRARY"
+"-DSQLITE3_INCLUDE_DIR"
+"-DSQLITE3_LIBRARY"
+-DQT_FONTCONFIG_LIBRARY (ADVANCED)
+-DQT_FREETYPE_LIBRARY (ADVANCED)
+-DQT_PNG_LIBRARY (ADVANCED)
+-DQT_X11_ICE_LIBRARY (ADVANCED)
+-DQT_X11_SM_LIBRARY (ADVANCED)
+-DQT_XCURSOR_LIBRARY (ADVANCED)
+-DQT_XINERAMA_LIBRARY (ADVANCED)
+-DQT_XRANDR_LIBRARY (ADVANCED)
+-DQT_XRENDER_LIBRARY (ADVANCED)
+-DQT_ZLIB_LIBRARY (ADVANCED)
+*/
+      };
+    }; 
+
+    #inherit geos proj x11 libXext;
+
+    extraAttrs = co : {
+
+    name = "qgis-svn";
+
+    src = args.fetchsvn { url=https://svn.qgis.org/repos/qgis/trunk/qgis; 
+                    md5="ac0560e0a2d4e6258c8639f1e9b56df3"; rev="7704"; };
+
+    meta = { 
+      description = "user friendly Open Source Geographic Information System";
+      homepage = http://www.qgis.org;
+      # you can choose one of the following licenses: 
+      license = [ "GPL" ];
+    };
+
+    phases = "unpackPhase buildPhase installPhase";
+    buildPhase = "cmake -DCMAKE_INSTALL_PREFIX=\$out ${co.configureFlags} .";
+
+    #configurePhase="./autogen.sh --prefix=\$out --with-gdal=\$gdal/bin/gdal-config --with-qtdir=\$qt";
+    # buildPhases="unpackPhase buildPhase";
+  };
+
+} ) args
diff --git a/pkgs/applications/misc/rxvt/default.nix b/pkgs/applications/misc/rxvt/default.nix
index c875e55a8cb..58366c6aa04 100644
--- a/pkgs/applications/misc/rxvt/default.nix
+++ b/pkgs/applications/misc/rxvt/default.nix
@@ -1,13 +1,13 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "rxvt-2.6.4";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://downloads.sourceforge.net/rxvt/rxvt-2.6.4.tar.gz;
     sha256 = "0hi29whjv8v11nkjbq1i6ms411v6csykghmlpkmayfjn9nxr02xg";
   };
 
-  buildInputs =(with args; [ libX11 libXt ]);
+  buildInputs = [ libX11 libXt ];
 
   meta = { 
       description = "colour vt102 terminal emulator with less features and lower memory consumption";
diff --git a/pkgs/applications/misc/rxvt_unicode/default.nix b/pkgs/applications/misc/rxvt_unicode/default.nix
index b43b3c275e8..6dc6e30b815 100644
--- a/pkgs/applications/misc/rxvt_unicode/default.nix
+++ b/pkgs/applications/misc/rxvt_unicode/default.nix
@@ -1,15 +1,20 @@
-args: with args; stdenv.mkDerivation {
-  name = "rxvt-unicode-8.4";
+args: with args;
+stdenv.mkDerivation (rec {
+  pname = "rxvt-unicode";
+  version = "9.02";
 
-  buildInputs = [ libX11 libXt libXft perl ];
+  name = "${pname}-${version}";
 
-  src = fetchurl {
-    url = http://dist.schmorp.de/rxvt-unicode/rxvt-unicode-8.4.tar.bz2;
-    sha256 = "ff8d904a815151edde72bb3e51d1561125813569cb3d487cbac428ec23facdbb";
+ src = fetchurl {
+    url = "http://dist.schmorp.de/rxvt-unicode/Attic/${name}.tar.bz2";
+    sha256 = "234b9a3e3f88c4984b1e909f8028638fc3b61d801d8afaa9cd08154b1a480a31";
   };
 
+  buildInputs = [ libX11 libXt libXft ];
+  configureFlags = "--disable-perl";
+
   meta = {
     description = "rxvt-unicode is a clone of the well known terminal emulator rxvt.";
     homepage = "http://software.schmorp.de/pkg/rxvt-unicode.html";
   };
-}
+})
diff --git a/pkgs/applications/misc/sbagen/default.nix b/pkgs/applications/misc/sbagen/default.nix
index d78742bfc5b..6bf28580b35 100644
--- a/pkgs/applications/misc/sbagen/default.nix
+++ b/pkgs/applications/misc/sbagen/default.nix
@@ -1,5 +1,5 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "sbagen-1.4.4";
 
   buildPhases="buildPhase installPhase";
@@ -14,7 +14,7 @@ args.stdenv.mkDerivation {
   
    ";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://uazu.net/sbagen/sbagen-1.4.4.tgz;
     sha256 = "0w62yk1b0hq79kl0angma897yqa8p1ww0dwydf3zlwav333prkd2";
   };
diff --git a/pkgs/applications/misc/synergy/default.nix b/pkgs/applications/misc/synergy/default.nix
index b2b7af6f014..ea3fb6e7a91 100644
--- a/pkgs/applications/misc/synergy/default.nix
+++ b/pkgs/applications/misc/synergy/default.nix
@@ -1,19 +1,19 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "synergy-cvs";
 
-  src = args.fetchcvs {
+  src = fetchcvs {
     url = ":pserver:anonymous@synergy2.cvs.sourceforge.net:/cvsroot/synergy2";
     module = "synergy";
-    tag = "-DNOW";
+    date = "NOW";
     sha256 = "ef8e2ebfda6e43240051a7af9417092b2af50ece8b5c6c3fbd908ba91c4fe068";
   };
 
-  buildInputs =(with args; [x11 xextproto libXtst inputproto]);
+  buildInputs = [x11 xextproto libXtst inputproto];
 
   meta= { 
       description = "share mouse keyboard and clipboard between computers";
-      homepage = http://synergy2;
+      homepage = http://synergy2.sourceforge.net;
       license = "GPL";
   };
 }
diff --git a/pkgs/applications/misc/wordnet/default.nix b/pkgs/applications/misc/wordnet/default.nix
new file mode 100644
index 00000000000..7300959fde7
--- /dev/null
+++ b/pkgs/applications/misc/wordnet/default.nix
@@ -0,0 +1,25 @@
+{stdenv, fetchurl, tcl, tk, x11, makeWrapper}:
+
+stdenv.mkDerivation {
+  name = "wordnet-3.0";
+  src = fetchurl {
+    url = http://wordnet.princeton.edu/3.0/WordNet-3.0.tar.bz2;
+    sha256 = "6c492d0c7b4a40e7674d088191d3aa11f373bb1da60762e098b8ee2dda96ef22";
+  };
+
+  buildInputs = [tcl tk x11 makeWrapper];
+
+  # Needs the path to `tclConfig.sh' and `tkConfig.sh'.
+  configureFlags = "--with-tcl=" + tcl + "/lib " +
+                   "--with-tk="  + tk  + "/lib";
+
+  postInstall = ''
+    wrapProgram $out/bin/wishwn --set TK_LIBRARY "${tk}/lib/tk8.4"
+    wrapProgram $out/bin/wnb    --prefix PATH : "$out/bin"
+  '';
+
+  meta = {
+    description = "WordNet, a lexical database for the English language.";
+    homepage = http://wordnet.princeton.edu/;
+  };
+}
diff --git a/pkgs/applications/misc/xchm/default.nix b/pkgs/applications/misc/xchm/default.nix
index ccd14b1f652..d9ffe8515db 100644
--- a/pkgs/applications/misc/xchm/default.nix
+++ b/pkgs/applications/misc/xchm/default.nix
@@ -10,5 +10,6 @@ stdenv.mkDerivation {
 
   meta = {
     description = "A viewer for Microsoft HTML Help files";
+    homepage = http://xchm.sourceforge.net;
   };
 }
diff --git a/pkgs/applications/misc/xpdf/default.nix b/pkgs/applications/misc/xpdf/default.nix
index bdaad1851dd..fc79703d877 100644
--- a/pkgs/applications/misc/xpdf/default.nix
+++ b/pkgs/applications/misc/xpdf/default.nix
@@ -24,6 +24,7 @@ stdenv.mkDerivation {
       url = ftp://ftp.foolabs.com/pub/xpdf/xpdf-3.02pl1.patch;
       sha256 = "1wxv9l0d2kkwi961ihpdwi75whdvk7cgqxkbfym8cjj11fq17xjq";
     })
+    ./xpdf-3.02-protection.patch
   ];
     
   configureFlags =
diff --git a/pkgs/applications/misc/xpdf/xpdf-3.02-protection.patch b/pkgs/applications/misc/xpdf/xpdf-3.02-protection.patch
new file mode 100644
index 00000000000..598fc6dbd07
--- /dev/null
+++ b/pkgs/applications/misc/xpdf/xpdf-3.02-protection.patch
@@ -0,0 +1,74 @@
+diff -C 3 -r orig/xpdf/pdfimages.cc xpdf-3.02/xpdf/pdfimages.cc
+*** orig/xpdf/pdfimages.cc	2007-02-27 23:05:52.000000000 +0100
+--- xpdf-3.02/xpdf/pdfimages.cc	2007-10-31 20:17:22.601449943 +0100
+***************
+*** 118,130 ****
+      goto err1;
+    }
+  
+-   // check for copy permission
+-   if (!doc->okToCopy()) {
+-     error(-1, "Copying of images from this document is not allowed.");
+-     exitCode = 3;
+-     goto err1;
+-   }
+- 
+    // get page range
+    if (firstPage < 1)
+      firstPage = 1;
+--- 118,123 ----
+diff -C 3 -r orig/xpdf/pdftotext.cc xpdf-3.02/xpdf/pdftotext.cc
+*** orig/xpdf/pdftotext.cc	2007-02-27 23:05:52.000000000 +0100
+--- xpdf-3.02/xpdf/pdftotext.cc	2007-10-31 20:17:34.392224196 +0100
+***************
+*** 160,172 ****
+      goto err2;
+    }
+  
+-   // check for copy permission
+-   if (!doc->okToCopy()) {
+-     error(-1, "Copying of text from this document is not allowed.");
+-     exitCode = 3;
+-     goto err2;
+-   }
+- 
+    // construct text file name
+    if (argc == 3) {
+      textFileName = new GString(argv[2]);
+--- 160,165 ----
+diff -C 3 -r orig/xpdf/XPDFCore.cc xpdf-3.02/xpdf/XPDFCore.cc
+*** orig/xpdf/XPDFCore.cc	2007-02-27 23:05:52.000000000 +0100
+--- xpdf-3.02/xpdf/XPDFCore.cc	2007-10-31 20:18:05.370494431 +0100
+***************
+*** 384,394 ****
+  #ifndef NO_TEXT_SELECT
+        if (selectULX != selectLRX &&
+  	  selectULY != selectLRY) {
+! 	if (doc->okToCopy()) {
+! 	  copySelection();
+! 	} else {
+! 	  error(-1, "Copying of text from this document is not allowed.");
+! 	}
+        }
+  #endif
+      }
+--- 384,390 ----
+  #ifndef NO_TEXT_SELECT
+        if (selectULX != selectLRX &&
+  	  selectULY != selectLRY) {
+! 	copySelection();
+        }
+  #endif
+      }
+***************
+*** 407,415 ****
+    int pg;
+    double ulx, uly, lrx, lry;
+  
+-   if (!doc->okToCopy()) {
+-     return;
+-   }
+    if (getSelection(&pg, &ulx, &uly, &lrx, &lry)) {
+      //~ for multithreading: need a mutex here
+      if (currentSelection) {
+--- 403,408 ----
diff --git a/pkgs/applications/misc/xterm/default.nix b/pkgs/applications/misc/xterm/default.nix
index c14ceb84e87..30b3e6cbda8 100644
--- a/pkgs/applications/misc/xterm/default.nix
+++ b/pkgs/applications/misc/xterm/default.nix
@@ -1,10 +1,16 @@
 {stdenv, fetchurl, libXaw, xproto, libXt, libX11, libSM, libICE, ncurses}:
 
-stdenv.mkDerivation {
-  name = "xterm-208";
+stdenv.mkDerivation rec {
+  name = "xterm-231";
   src = fetchurl {
-    url = ftp://invisible-island.net/xterm/xterm.tar.gz;
-    md5 = "a062d0b398918015d07c31ecdcc5111a";
+    url = "ftp://invisible-island.net/xterm/${name}.tgz";
+    sha256 = "0qlz5nkdqkahdg9kbd1ni96n69srj1pd9yggwrw3z0kghaajb2sr";
   };
   buildInputs = [libXaw xproto libXt libX11 libSM libICE ncurses];
+  configureFlags = ["--enable-wide-chars"];
+
+  meta = {
+    homepage = http://invisible-island.net/xterm;
+  };
 }
+
diff --git a/pkgs/applications/networking/browsers/elinks/default.nix b/pkgs/applications/networking/browsers/elinks/default.nix
index 9804f758ba7..1e786848133 100644
--- a/pkgs/applications/networking/browsers/elinks/default.nix
+++ b/pkgs/applications/networking/browsers/elinks/default.nix
@@ -8,11 +8,7 @@ stdenv.mkDerivation {
     sha256 = "c10e657fbd884eae4f01b91b32407bbfcbcae0ad5017fb24ea365aebc71d2af1";
   };
 
-  preConfigure = "
-  	touch config.log ; rm /tmp/elinks.config.log; ln -f config.log /tmp/elinks.config.log";
-
-  buildInputs = [python perl ncurses x11 bzip2 zlib openssl spidermonkey guile
-  	libtool];
+  buildInputs = [python perl ncurses x11 bzip2 zlib openssl spidermonkey guile];
   configureFlags = "--enable-finger --enable-html-highlight --with-guile
   --with-perl --with-python --enable-gopher --enable-cgi --enable-bittorrent
   --enable-nntp --with-openssl=${openssl}";
diff --git a/pkgs/applications/networking/browsers/firefox-3/binary.nix b/pkgs/applications/networking/browsers/firefox-3/binary.nix
new file mode 100644
index 00000000000..73e002435b8
--- /dev/null
+++ b/pkgs/applications/networking/browsers/firefox-3/binary.nix
@@ -0,0 +1,55 @@
+args: with args;
+
+assert stdenv.system == "i686-linux";
+
+stdenv.mkDerivation {
+  name = "firefox-3b1";
+
+  src = 
+	fetchurl {
+		url = ftp://ftp.mozilla.org/pub/firefox/releases/3.0b1/linux-i686/en-US/firefox-3.0b1.tar.bz2;
+		sha256 = "1cpcc5b07zdqyd5kiwhb4dqhy2mzbf97plsglcp6bc9054cmsylk";
+	};
+  buildInputs = [
+    pkgconfig gtk perl zip libIDL libXi libjpeg libpng zlib cairo
+    python curl coreutils atk pango glib libX11 libXrender 
+    freetype fontconfig libXft libXt
+  ];
+
+  buildPhase = "
+    additionalRpath='';
+    for i in \$buildInputs ${stdenv.glibc} ${stdenv.gcc.gcc}; do 
+      additionalRpath=\$additionalRpath:\$i/lib;  
+    done
+    for i in firefox-bin ; do
+      oldrpath=$(patchelf --print-rpath \$i)
+      patchelf --set-rpath \$oldrpath\$additionalRpath \$i
+      patchelf --set-interpreter ${stdenv.glibc}/lib/ld-linux.so.2 \$i
+    done
+  ";
+
+  installPhase = "
+    export dontPatchELF=1;
+    mkdir -p \$out
+    cp -r . \$out/firefox
+    mkdir -p \$out/bin
+    ln -s \$out/firefox/firefox \$out/bin/firefox
+
+    sed -e 's@moz_libdir=.*@moz_libdir='\$out'/firefox/@' -i \$out/bin/firefox 
+    sed -e 's@moz_libdir=.*@&\\nexport PATH=\$PATH:${coreutils}/bin@' -i \$out/bin/firefox 
+    sed -e 's@`/bin/pwd@`${coreutils}/bin/pwd@' -i \$out/bin/firefox 
+    sed -e 's@`/bin/ls@`${coreutils}/bin/ls@' -i \$out/bin/firefox 
+
+    strip -S \$out/firefox/*.so || true
+
+    echo \"running firefox -register...\"
+    \$out/firefox/firefox-bin -register || false
+  ";
+
+  meta = {
+    description = "Mozilla Firefox - the browser, reloaded";
+  };
+
+  passthru = {inherit gtk;};
+}
+
diff --git a/pkgs/applications/networking/browsers/firefox-3/builder.sh b/pkgs/applications/networking/browsers/firefox-3/builder.sh
new file mode 100644
index 00000000000..66f1059d657
--- /dev/null
+++ b/pkgs/applications/networking/browsers/firefox-3/builder.sh
@@ -0,0 +1,30 @@
+source $stdenv/setup
+
+postInstall=postInstall
+postInstall() {
+
+    # Strip some more stuff
+    strip -S $out/lib/*/* || true
+
+    # This fixes starting Firefox when there already is a running
+    # instance.  The `firefox' wrapper script actually expects to be
+    # in the same directory as `run-mozilla.sh', apparently.
+    libDir=$(cd $out/lib && ls -d firefox-*)
+    test -n "$libDir"
+    cd $out/bin
+    mv firefox ../lib/$libDir/
+    ln -s ../lib/$libDir/firefox .
+
+    # Register extensions etc.
+    echo "running firefox -register..."
+    (cd $out/lib/$libDir && LD_LIBRARY_PATH=. ./firefox-bin -register) || false
+
+    echo "running regxpcom..."
+    (cd $out/lib/$libDir && LD_LIBRARY_PATH=. ./regxpcom) || false
+
+    # Put the Firefox icon in the right place.
+    ensureDir $out/lib/$libDir/chrome/icons/default
+    ln -s ../../../icons/default.xpm  $out/lib/$libDir/chrome/icons/default/
+}
+
+genericBuild
diff --git a/pkgs/applications/networking/browsers/firefox-3/default.nix b/pkgs/applications/networking/browsers/firefox-3/default.nix
new file mode 100644
index 00000000000..88315aa0c31
--- /dev/null
+++ b/pkgs/applications/networking/browsers/firefox-3/default.nix
@@ -0,0 +1,64 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "firefox-3.0-beta-3";
+
+  src = fetchurl {
+    url = ftp://ftp.mozilla.org/pub/firefox/releases/3.0b3/source/firefox-3.0b3-source.tar.bz2;
+    sha1 = "142f28a41077e77d61423a5ca6585a45737ff999";
+  };
+
+  buildInputs = [
+    pkgconfig gtk perl zip libIDL libXi libjpeg libpng zlib cairo
+    python curl coreutils dbus dbus_glib pango freetype fontconfig 
+    libX11 libXrender libXft libXt
+  ];
+
+  configureFlags = [
+    "--enable-application=browser"
+    "--enable-optimize"
+    "--disable-debug"
+    "--enable-strip"
+    "--with-system-jpeg"
+    "--with-system-zlib"
+    #"--with-system-png" <-- "--with-system-png won't work because the system's libpng doesn't have APNG support"
+    #"--enable-system-cairo" <-- disabled for now because Firefox needs a alpha version of Cairo
+  ];
+
+  postInstall = ''
+    export dontPatchELF=1;
+
+    # Strip some more stuff
+    strip -S $out/lib/*/* || true
+
+    # Fix some references to /bin paths in the Firefox shell script.
+    substituteInPlace $out/bin/firefox \
+        --replace /bin/pwd "$(type -tP pwd)" \
+        --replace /bin/ls "$(type -tP ls)"
+    
+    # This fixes starting Firefox when there already is a running
+    # instance.  The `firefox' wrapper script actually expects to be
+    # in the same directory as `run-mozilla.sh', apparently.
+    libDir=$(cd $out/lib && ls -d firefox-[0-9]*)
+    test -n "$libDir"
+    cd $out/bin
+    mv firefox ../lib/$libDir/
+    ln -s ../lib/$libDir/firefox .
+
+    # Register extensions etc.
+    echo "running firefox -register..."
+    (cd $out/lib/$libDir && LD_LIBRARY_PATH=. ./firefox-bin -register) || false
+
+    # Put the Firefox icon in the right place.
+    ensureDir $out/lib/$libDir/chrome/icons/default
+    ln -s ../../../icons/default.xpm  $out/lib/$libDir/chrome/icons/default/
+  ''; # */
+
+  meta = {
+    description = "Mozilla Firefox - the browser, reloaded";
+    homepage = http://www.mozilla.com/en-US/firefox/;
+  };
+
+  passthru = {inherit gtk;};
+}
+
diff --git a/pkgs/applications/networking/browsers/firefox-wrapper/builder.sh b/pkgs/applications/networking/browsers/firefox-wrapper/builder.sh
index 6abbf1a760b..4e2f1c5e8f1 100644
--- a/pkgs/applications/networking/browsers/firefox-wrapper/builder.sh
+++ b/pkgs/applications/networking/browsers/firefox-wrapper/builder.sh
@@ -1,7 +1,7 @@
 source $stdenv/setup
 source $makeWrapper
 
-makeWrapper "$firefox/bin/firefox" "$out/bin/firefox" \
+makeWrapper "$firefox/bin/firefox" "$out/bin/firefox$nameSuffix" \
     --suffix-each MOZ_PLUGIN_PATH ':' "$plugins" \
     --suffix-contents LD_LIBRARY_PATH ':' "$(filterExisting $(addSuffix /extra-library-path $plugins))" \
     --suffix-contents PATH ':' "$(filterExisting $(addSuffix /extra-bin-path $plugins))"
diff --git a/pkgs/applications/networking/browsers/firefox-wrapper/default.nix b/pkgs/applications/networking/browsers/firefox-wrapper/default.nix
index 7229f510829..0b1756f21f2 100644
--- a/pkgs/applications/networking/browsers/firefox-wrapper/default.nix
+++ b/pkgs/applications/networking/browsers/firefox-wrapper/default.nix
@@ -1,4 +1,4 @@
-{stdenv, firefox, plugins}:
+args: with args;
 
 stdenv.mkDerivation {
   name = firefox.name + "-with-plugins";
@@ -8,6 +8,8 @@ stdenv.mkDerivation {
 
   inherit firefox;
 
+  nameSuffix = (if args ? nameSuffix then args.nameSuffix else "");
+
   # Let each plugin tell us (through its `mozillaPlugin') attribute
   # where to find the plugin in its tree.
   plugins = map (x: x + x.mozillaPlugin) plugins;
diff --git a/pkgs/applications/networking/browsers/firefox/default.nix b/pkgs/applications/networking/browsers/firefox/default.nix
index 4cb9debf06a..81545bc5bd1 100644
--- a/pkgs/applications/networking/browsers/firefox/default.nix
+++ b/pkgs/applications/networking/browsers/firefox/default.nix
@@ -10,12 +10,12 @@
 }:
 
 stdenv.mkDerivation {
-  name = "firefox-2.0.0.9";
+  name = "firefox-2.0.0.12";
 
   builder = ./builder.sh;
   src = fetchurl {
-    url = http://releases.mozilla.org/pub/mozilla.org/firefox/releases/2.0.0.9/source/firefox-2.0.0.9-source.tar.bz2;
-    sha1 = "3b39d4128534d18f7e2c4d76a14561c18556eff0";
+    url = http://releases.mozilla.org/pub/mozilla.org/firefox/releases/2.0.0.12/source/firefox-2.0.0.12-source.tar.bz2;
+    sha1 = "766f3e945145d9e4d36d5eb3e551b5eb44a1d862";
   };
 
   buildInputs = [
@@ -49,6 +49,7 @@ stdenv.mkDerivation {
 
   meta = {
     description = "Mozilla Firefox - the browser, reloaded";
+    homepage = http://www.mozilla.com/en-US/firefox/;
   };
 
   passthru = {inherit gtk;};
diff --git a/pkgs/applications/networking/browsers/mozilla-plugins/flashplayer-9/default.nix b/pkgs/applications/networking/browsers/mozilla-plugins/flashplayer-9/default.nix
index d6972ac2f79..e14cfe2bea7 100644
--- a/pkgs/applications/networking/browsers/mozilla-plugins/flashplayer-9/default.nix
+++ b/pkgs/applications/networking/browsers/mozilla-plugins/flashplayer-9/default.nix
@@ -2,14 +2,24 @@
 
 assert stdenv.system == "i686-linux";
 
-(stdenv.mkDerivation {
-  name = "flashplayer-9.0.31.0";
+stdenv.mkDerivation {
+  name = "flashplayer-9.0.115.0";
 
   builder = ./builder.sh;
   src = fetchurl {
     url = http://fpdownload.macromedia.com/get/flashplayer/current/install_flash_player_9_linux.tar.gz;
-    sha256 = "ad2f9eb98e976a82b62e97e7cf3a555464e43b80507b87ed7c469706faa4d897";
+    sha256 = "0yr2n7barlbvqxxzbvgp0pmbwwf7bvjksravqa47yra689jvynr7";
   };
 
   inherit zlib alsaLib;
-}) // {mozillaPlugin = "/lib/mozilla/plugins";}
+
+  passthru = {
+    mozillaPlugin = "/lib/mozilla/plugins";
+  };
+
+  meta = {
+    description = "Adobe Flash Player browser plugin";
+    homepage = http://www.adobe.com/products/flashplayer/;
+  };
+
+}
diff --git a/pkgs/applications/networking/browsers/mozilla-plugins/mplayerplug-in/default.nix b/pkgs/applications/networking/browsers/mozilla-plugins/mplayerplug-in/default.nix
index 12eef1c8859..1e681ade776 100644
--- a/pkgs/applications/networking/browsers/mozilla-plugins/mplayerplug-in/default.nix
+++ b/pkgs/applications/networking/browsers/mozilla-plugins/mplayerplug-in/default.nix
@@ -5,12 +5,12 @@
 # think).
 
 stdenv.mkDerivation {
-  name = "mplayerplug-in-3.45";
+  name = "mplayerplug-in-3.50";
 
   builder = ./builder.sh;
   src = fetchurl {
-    url = mirror://sourceforge/mplayerplug-in/mplayerplug-in-3.45.tar.gz;
-    sha256 = "0cfl0s7v1bgdak39x7s2hnx968qs3vlv09gmwms27czimn8vijiz";
+    url = mirror://sourceforge/mplayerplug-in/mplayerplug-in-3.50.tar.gz;
+    sha256 = "00jcbwl3wa6s4784c3wrz718f6jj1zkdfjbp7d2nhiafxrjqwsq4";
   };
 
   buildInputs = [pkgconfig firefox (firefox.gtk) libXpm gettext];
diff --git a/pkgs/applications/networking/browsers/mozilla/default.nix b/pkgs/applications/networking/browsers/mozilla/default.nix
index cb7573eb8a1..a2c667fa968 100644
--- a/pkgs/applications/networking/browsers/mozilla/default.nix
+++ b/pkgs/applications/networking/browsers/mozilla/default.nix
@@ -15,4 +15,7 @@ stdenv.mkDerivation {
   inherit gtk;
 
   #patches = [./writable-copies.patch];
+  meta = {
+    homepage = http://www.mozilla.org;
+  };
 }
diff --git a/pkgs/applications/networking/browsers/opera/builder.sh b/pkgs/applications/networking/browsers/opera/builder.sh
index 26d5df1cc4d..1de82fdfa72 100644
--- a/pkgs/applications/networking/browsers/opera/builder.sh
+++ b/pkgs/applications/networking/browsers/opera/builder.sh
@@ -7,6 +7,7 @@ buildPhase() {
 
 installPhase=installPhase
 installPhase() {
+    sed -i 's=/bin/pwd=pwd=' opera install.sh 
     # Note: the "no" is because the install scripts asks whether we
     # want to install icons in some system-wide directories.
     echo no | ./install.sh --prefix=$out
@@ -16,20 +17,18 @@ installPhase() {
         rpath="$rpath:$i/lib"
     done
 
+    [ -z ${system##*64*} ] && suf=64
+
     # !!! ugh, should fix this eventually; just make a normal gcc dependency
     gcc=$(cat $NIX_GCC/nix-support/orig-gcc)
-    rpath="$rpath:$gcc/lib"
+    rpath="$rpath:$libstdcpp5/lib$suf"
     
-    for i in $out/lib/opera/*/opera $out/lib/opera/plugins/opera*; do
+    for i in $out/lib/opera/*/opera $out/lib/opera/*/operaplugin{wrapper,cleaner}; do
         patchelf \
             --set-interpreter "$(cat $NIX_GCC/nix-support/dynamic-linker)" \
             --set-rpath "$rpath" \
             "$i"
     done
-
-    # opera seems to need libnpp.so in the same path ?
-    # (search the opera help for libnpp..
-    cp $out/lib/opera/plugins/libnpp.so $out/lib/opera/9*
 }
 
 genericBuild
diff --git a/pkgs/applications/networking/browsers/opera/default.nix b/pkgs/applications/networking/browsers/opera/default.nix
index 754a018c328..2adcf92540f 100644
--- a/pkgs/applications/networking/browsers/opera/default.nix
+++ b/pkgs/applications/networking/browsers/opera/default.nix
@@ -1,7 +1,6 @@
-{ stdenv, fetchurl, qt, zlib, libX11, libXext, libSM, libICE, libstdcpp5
+{ stdenv, fetchurl, qt, zlib, libX11, libXext, libSM, libICE, libstdcpp5, glibc
 , motif ? null, libXt ? null}:
 
-assert stdenv.system == "i686-linux";
 assert motif != null -> libXt != null;
 
 # !!! Add Xinerama and Xrandr dependencies?  Or should those be in Qt?
@@ -12,13 +11,31 @@ stdenv.mkDerivation rec {
   version = "9.24-20071015.5";
   name = "opera-${version}";
 
+  inherit libstdcpp5;
+
   builder = ./builder.sh;
-  src = fetchurl {
-    url = ftp://ftp.task.gda.pl/pub/opera/linux/924/final/en/i386/shared/opera-9.24-20071015.5-shared-qt.i386-en.tar.bz2;
-    sha256 = "1frhnrp63k4lz29a8z9c99h383xrsrby432xp20hxrylh0zypzb5";
-  };
+    src = if (stdenv.system == "i686-linux") then
+      fetchurl {
+        url = ftp://ftp.task.gda.pl/pub/opera/linux/950b/final/en/i386/shared/opera-9.50b-20071024.5-shared-qt.i386-en.tar.bz2;
+        sha256 = "0vv1q86is9x6vw8fx92wrnvlyn4x29zgk9zjn66rcx37n6grqqah";
+      } else if (stdenv.system == "x86_64-linux") then
+      fetchurl {
+        url = http://snapshot.opera.com/unix/snapshot-1754/x86_64-linux/opera-9.50-20080110.2-shared-qt.x86_64-1754.tar.bz2;
+        sha256 = "08y1ajjncdvbhvcq2izmpgc4fi37bwn43zsw7rz41jf8qhvb5ywv";
+        #url = ftp://ftp.task.gda.pl/pub/opera/linux/950b/final/en/x86_64/opera-9.50-20071024.2-shared-qt.x86_64-1643.tar.bz2;
+        #sha256 = "1gv1r18ar3vz1l24nf8qixjlba1yb5d3xvg3by41i4dy0vlznqn6";
+        #name = opera-9.25-20071214.6-shared-qt.i386-en.tar.gz;
+        #url = http://www.opera.com/download/get.pl?id=30462&location=225&nothanks=yes&sub=marine;
+        #sha256 = "1wnc1s4r5gz73mxs8pgsi9a1msz7x8a8pb1ykb1xgdfn21h69p2p";
+      } else throw "unsupported platform ${stdenv.system} (only i686-linux and x86_64 linux supported yet)";
 
+  # operapluginwrapper seems to require libXt ?
+  # Adding it makes startup faster and omits error messages (on x68)
   libPath =
-    [qt motif zlib libX11 libXext libSM libICE libstdcpp5]
-    ++ (if motif != null then [motif libXt ] else []);
+    [glibc qt motif zlib libX11 libXt libXext libSM libICE libstdcpp5]
+    ++ (if motif != null then [motif ] else []);
+
+  meta = {
+    homepage = http://www.opera.com;
+  };
 }
diff --git a/pkgs/applications/networking/browsers/w3m/default.nix b/pkgs/applications/networking/browsers/w3m/default.nix
index 640dffd0baa..1cda828cf53 100644
--- a/pkgs/applications/networking/browsers/w3m/default.nix
+++ b/pkgs/applications/networking/browsers/w3m/default.nix
@@ -21,4 +21,8 @@ stdenv.mkDerivation {
     (if graphicsSupport then gdkpixbuf else null)
   ];
   #patches = [./bsd.patch];
+
+  meta = {
+    homepage = http://w3m.sourceforge.net;
+  };
 }
diff --git a/pkgs/applications/networking/instant-messengers/amsn/default.nix b/pkgs/applications/networking/instant-messengers/amsn/default.nix
index 0f357c16514..330d7e9d281 100644
--- a/pkgs/applications/networking/instant-messengers/amsn/default.nix
+++ b/pkgs/applications/networking/instant-messengers/amsn/default.nix
@@ -10,4 +10,8 @@ stdenv.mkDerivation {
 
   inherit tcl tk libstdcpp;
   buildInputs = [which tcl tk x11 ];
+
+  meta = {
+    homepage = http://amsn-project.net;
+  };
 }
diff --git a/pkgs/applications/networking/instant-messengers/bitlbee/default.nix b/pkgs/applications/networking/instant-messengers/bitlbee/default.nix
new file mode 100644
index 00000000000..ed36ca779b6
--- /dev/null
+++ b/pkgs/applications/networking/instant-messengers/bitlbee/default.nix
@@ -0,0 +1,17 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "bitlbee-1.0.4";
+  src = fetchurl {
+    url = "mirror://bitlbee/src/" + name + ".tar.gz";
+    sha256 = "072vdpz4z3bmskm04crrkj946hj0gnnd6w0vqrb7xmj1lrzg68vg";
+  };
+
+  buildInputs = [ gnutls glib pkgconfig ];
+
+  meta = {
+    description = ''BitlBee, an IRC to other chat networks gateway.'';
+    homepage = http://www.bitlbee.org/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/applications/networking/instant-messengers/pidgin-plugins/otr/default.nix b/pkgs/applications/networking/instant-messengers/pidgin-plugins/otr/default.nix
index cde1cb2534b..2d70c583cab 100644
--- a/pkgs/applications/networking/instant-messengers/pidgin-plugins/otr/default.nix
+++ b/pkgs/applications/networking/instant-messengers/pidgin-plugins/otr/default.nix
@@ -9,6 +9,7 @@ stdenv.mkDerivation {
 
   meta = {
     description = "OTR plugin for Pidgin IM.";
+    homepage = http://www.cypherpunks.ca/otr;
   };
 
   postInstall = "ln -s \$out/lib/pidgin \$out/share/pidgin-otr";
diff --git a/pkgs/applications/networking/instant-messengers/pidgin-plugins/pidgin-latex/default.nix b/pkgs/applications/networking/instant-messengers/pidgin-plugins/pidgin-latex/default.nix
index 894da72b38f..95664d0fbeb 100644
--- a/pkgs/applications/networking/instant-messengers/pidgin-plugins/pidgin-latex/default.nix
+++ b/pkgs/applications/networking/instant-messengers/pidgin-plugins/pidgin-latex/default.nix
@@ -37,5 +37,6 @@ stdenv.mkDerivation {
 	Enable it for user by linking to ~/.purple/plugins - from 
 	sw/share/pidgin-latex , not from store of course.
 ";
+		homepage = http://tapas.affenbande.org/wordpress/?page_id=70;
   };
 }
diff --git a/pkgs/applications/networking/instant-messengers/pidgin/default.nix b/pkgs/applications/networking/instant-messengers/pidgin/default.nix
index 73b351bf9fe..bc49144565c 100644
--- a/pkgs/applications/networking/instant-messengers/pidgin/default.nix
+++ b/pkgs/applications/networking/instant-messengers/pidgin/default.nix
@@ -17,10 +17,10 @@
 } :
 
 stdenv.mkDerivation {
-  name = "pidgin-2.2.1";
+  name = "pidgin-2.3.1";
   src = fetchurl {
-    url = mirror://sourceforge/pidgin/pidgin-2.2.1.tar.bz2;
-    sha256 = "08sq0yc8vz6c24pdv64clv6s91a5idslpp7vll8vgspn4piyzyvf";
+    url = mirror://sourceforge/pidgin/pidgin-2.3.1.tar.bz2;
+    sha256 = "17mpirkfrv48jqn86l23b2ia2nzz9hqhll6lp4c2q8sbff3kc21d";
   };
 
   inherit nss ncurses;
@@ -38,5 +38,6 @@ stdenv.mkDerivation {
   configureFlags="--with-nspr-includes=${nss}/include/nspr --with-nspr-libs=${nss}/lib --with-nss-includes=${nss}/include/nss --with-nss-libs=${nss}/lib --with-ncurses-headers=${ncurses}/include";
   meta = {
     description = "Pidgin IM - XMPP(Jabber), AIM/ICQ, IRC, SIP etc client.";
+    homepage = http://pidgin.im;
   };
 }
diff --git a/pkgs/applications/networking/instant-messengers/teamspeak/client.nix b/pkgs/applications/networking/instant-messengers/teamspeak/client.nix
new file mode 100644
index 00000000000..2763969ddec
--- /dev/null
+++ b/pkgs/applications/networking/instant-messengers/teamspeak/client.nix
@@ -0,0 +1,71 @@
+/*
+License issues:
+Date: Mon, 10 Dec 2007 19:55:16 -0500
+From: TeamSpeak Sales <sales@tritoncia.com>
+To: 'Marc Weber' <marco-oweber@gmx.de>
+Subject: RE: teamspeak on nix?
+
+Yes, that would be fine.  As long as you are not renting servers or selling
+TeamSpeak then you are more than welcome to distribute it.
+
+Thank you,
+
+TeamSpeak Sales Team
+________________________________
+e-Mail: sales@tritoncia.com
+TeamSpeak: http://www.TeamSpeak.com
+Account Login: https://sales.TritonCIA.com/users
+
+
+
+-----Original Message-----
+From: Marc Weber [mailto:marco-oweber@gmx.de]
+Sent: Monday, December 10, 2007 5:03 PM
+To: sales@tritoncia.com
+Subject: teamspeak on nix?
+
+Hello,
+
+nix is very young software distribution system (http://nix.cs.uu.nl/)
+I'd like to ask wether you permit us to add teamspeak (server/ client?)
+
+Sincerly
+Marc Weber (small nix contributor)
+*/
+
+args: with args;
+stdenv.mkDerivation {
+  name = "teamspeak-client-rc2-2032";
+
+  src = fetchurl {
+    url = ftp://213.202.254.114/teamspeak/releases/ts2_client_rc2_2032.tar.bz2;
+    md5 = "e93d17a25e07b1cbe400e4eb028ca8f8";
+  };
+
+  phases="installPhase";
+
+  rpathInputs = [ glibc x11 ];
+
+  installPhase="
+    set -x
+    i=\$out/nix-support
+    ensureDir \$out/{bin,nix-support}
+    mv setup.data/image \$i
+    cp \$out/{nix-support/image/TeamSpeak,bin}
+    echo sed
+    sed -i \"s=%installdir%=\$i/image=\" \$out/bin/TeamSpeak
+      
+    echo for
+    for p in $\rpathInputs; do
+      rpath=\$rpath:\$p/lib
+    done
+    echo patchelf
+    patchelf --set-rpath \$rpath \$i/image/TeamSpeak.bin
+  ";
+
+  meta = { 
+      description = "The TeamSpeak voice communication tool";
+      homepage = http://www.goteamspeak.com;
+      license = "TODO"; # non commercial use see email above 
+  };
+}
diff --git a/pkgs/applications/networking/irc/chatzilla/default.nix b/pkgs/applications/networking/irc/chatzilla/default.nix
index de34588a924..ff979d39393 100644
--- a/pkgs/applications/networking/irc/chatzilla/default.nix
+++ b/pkgs/applications/networking/irc/chatzilla/default.nix
@@ -1,14 +1,14 @@
 {stdenv, fetchurl, unzip}:
 
 stdenv.mkDerivation {
-  name = "chatzilla-0.9.78.1";
+  name = "chatzilla-0.9.79";
   
   builder = ./builder.sh;
   
   src = fetchurl {
     # Obtained from http://chatzilla.rdmsoft.com/xulrunner/.
-    url = http://chatzilla.rdmsoft.com/xulrunner/download/chatzilla-0.9.78.1-xr.zip;
-    sha256 = "1f7fgi1dvpzjsiai0vc986vd481i77hcafvnzm73bc2q8pa5g5mb";
+    url = http://chatzilla.rdmsoft.com/xulrunner/download/chatzilla-0.9.79-xr.zip;
+    sha256 = "0irbi8y4y2nlbwvhmmln5h5f4wv7spd1rqg7dxg7pc93s09p5i09";
   };
 
   buildInputs = [unzip];
diff --git a/pkgs/applications/networking/irc/irssi/default.nix b/pkgs/applications/networking/irc/irssi/default.nix
index 91c75a007c6..e5d60ef7dfe 100644
--- a/pkgs/applications/networking/irc/irssi/default.nix
+++ b/pkgs/applications/networking/irc/irssi/default.nix
@@ -1,12 +1,16 @@
 {stdenv, fetchurl, pkgconfig, ncurses, glib, openssl}:
 
 stdenv.mkDerivation {
-  name = "irssi-0.8.11";
+  name = "irssi-0.8.12";
   src = fetchurl {
-    url = http://irssi.org/files/irssi-0.8.11.tar.bz2;
-    sha256 = "425cf24f13bfda05c6a468523cd2874d05675ea1bc4e37a8c284f2f78c2dd6b2";
+    url = http://irssi.org/files/irssi-0.8.12.tar.bz2;
+    sha256 = "1w7zkfs6j7xdcbqh8x0vf9rk2ps9d6rcgr8fapfjpk09nm5n6ba6";
   };
   buildInputs = [pkgconfig ncurses glib openssl];
   NIX_LDFLAGS = "-lncurses";
   configureFlags = "--with-proxy --with-ncurses --enable-ssl";
+
+  meta = {
+    homepage = http://irssi.org;
+  };
 }
diff --git a/pkgs/applications/networking/irc/xchat/default.nix b/pkgs/applications/networking/irc/xchat/default.nix
index 5d12667e307..f7e4395e530 100644
--- a/pkgs/applications/networking/irc/xchat/default.nix
+++ b/pkgs/applications/networking/irc/xchat/default.nix
@@ -1,11 +1,15 @@
 {stdenv, fetchurl, pkgconfig, tcl, gtk}:
 
 stdenv.mkDerivation {
-  name = "xchat-2.8.2";
+  name = "xchat-2.8.4";
   src = fetchurl {
-    url = http://www.xchat.org/files/source/2.8/xchat-2.8.2.tar.bz2;
-    sha256 = "1zjhjwr03nj52lpsvl78jwhir7q6482nnd4h1p0a9zka27kj4v4z";
+    url = http://www.xchat.org/files/source/2.8/xchat-2.8.4.tar.bz2;
+    sha256 = "0qyx6rdvnjwy52amcmkjj134sysfkzbyv7b66vjsla3i8yg9lnpr";
   };
   buildInputs = [pkgconfig tcl gtk];
   configureFlags = "--disable-nls";
+
+  meta = {
+    homepage = http://www.xchat.org;
+  };
 }
diff --git a/pkgs/applications/networking/mailreaders/mutt/default.nix b/pkgs/applications/networking/mailreaders/mutt/default.nix
index 6b10cfc04a2..c3b4fe54d02 100644
--- a/pkgs/applications/networking/mailreaders/mutt/default.nix
+++ b/pkgs/applications/networking/mailreaders/mutt/default.nix
@@ -21,4 +21,8 @@ stdenv.mkDerivation {
     (if sslSupport then "--with-ssl" else "--without-ssl")
     (if imapSupport then "--enable-imap" else "--disable-imap")
   ];
+
+  meta = {
+    homepage = http://www.mutt.org;
+  };
 }
diff --git a/pkgs/applications/networking/mailreaders/sylpheed/default.nix b/pkgs/applications/networking/mailreaders/sylpheed/default.nix
index 1c52661e89b..63e41e542e6 100644
--- a/pkgs/applications/networking/mailreaders/sylpheed/default.nix
+++ b/pkgs/applications/networking/mailreaders/sylpheed/default.nix
@@ -9,11 +9,11 @@ assert sslSupport -> openssl != null;
 assert gpgSupport -> gpgme != null;
 
 stdenv.mkDerivation {
-  name = "sylpheed-2.4.1";
+  name = "sylpheed-2.4.8";
 
   src = fetchurl {
-    url = http://sylpheed.sraoss.jp/sylpheed/v2.4/sylpheed-2.4.1.tar.bz2;
-    sha256 = "1hmia3lnh7yr2ca8bgxzn311waxfs0rhk0psck3dcjfhzxzp72zj";
+    url = http://sylpheed.sraoss.jp/sylpheed/v2.4/sylpheed-2.4.8.tar.bz2;
+    sha256 = "0r4bfkyz39pj02rzn38ss10dhhhv93z1azlbbwdgbkjii3k760fc";
   };
 
   buildInputs = [
diff --git a/pkgs/applications/networking/mailreaders/thunderbird-1.x/builder.sh b/pkgs/applications/networking/mailreaders/thunderbird-1.x/builder.sh
deleted file mode 100644
index 7635910ae9f..00000000000
--- a/pkgs/applications/networking/mailreaders/thunderbird-1.x/builder.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-source $stdenv/setup
-
-postInstall=postInstall
-postInstall() {
-
-    # Strip some more stuff
-    strip -S $out/lib/*/* || true
-
-    # This fixes starting Thunderbird when there already is a running
-    # instance.  The `thunderbird' wrapper script actually expects to
-    # be in the same directory as `run-mozilla.sh', apparently.
-    libDir=$(cd $out/lib && ls -d thunderbird-*)
-    test -n "$libDir"
-    cd $out/bin
-    mv thunderbird ../lib/$libDir/
-    ln -s ../lib/$libDir/thunderbird .
-
-    # Register extensions etc.
-    echo "running thunderbird -register..."
-    (cd $out/lib/$libDir && LD_LIBRARY_PATH=. ./thunderbird-bin -register) || false
-
-    echo "running regxpcom..."
-    (cd $out/lib/$libDir && LD_LIBRARY_PATH=. ./regxpcom) || false
-
-    # Put the Thunderbird icon in the right place.
-    ensureDir $out/lib/$libDir/chrome/icons/default
-    ln -s ../../../icons/default.xpm  $out/lib/$libDir/chrome/icons/default/
-}
-
-genericBuild
diff --git a/pkgs/applications/networking/mailreaders/thunderbird-1.x/default.nix b/pkgs/applications/networking/mailreaders/thunderbird-1.x/default.nix
deleted file mode 100644
index 2e969d20507..00000000000
--- a/pkgs/applications/networking/mailreaders/thunderbird-1.x/default.nix
+++ /dev/null
@@ -1,47 +0,0 @@
-{ stdenv, fetchurl, pkgconfig, gtk, perl, zip, libIDL, libXi
-, libjpeg, libpng, zlib, cairo
-
-, # If you want the resulting program to call itself "Thunderbird"
-  # instead of "Mail", enable this option.  However, those
-  # binaries may not be distributed without permission from the
-  # Mozilla Foundation, see
-  # http://www.mozilla.org/foundation/trademarks/.
-  enableOfficialBranding ? false
-    
-}:
-
-stdenv.mkDerivation {
-  name = "thunderbird-1.5.0.10";
-
-  builder = ./builder.sh;
-  src = fetchurl {
-    url = http://releases.mozilla.org/pub/mozilla.org/thunderbird/releases/1.5.0.10/source/thunderbird-1.5.0.10-source.tar.bz2;
-    sha1 = "a6467c946f9e668bcf7b3a06dcaeceb601b98fce";
-  };
-
-  buildInputs = [
-    pkgconfig gtk perl zip libIDL libXi libjpeg libpng zlib cairo
-  ];
-
-  configureFlags = [
-    "--enable-application=mail"
-    "--enable-optimize"
-    "--disable-debug"
-    "--enable-xft"
-    "--disable-freetype2"
-    "--enable-svg"
-    "--enable-canvas"
-    "--enable-strip"
-    "--enable-default-toolkit=gtk2"
-    "--with-system-jpeg"
-    "--with-system-png"
-    "--with-system-zlib"
-    "--enable-system-cairo"
-    "--enable-extensions=default"
-  ]
-  ++ (if enableOfficialBranding then ["--enable-official-branding"] else []);
-
-  meta = {
-    description = "Mozilla Thunderbird, a full-featured email client";
-  };
-}
diff --git a/pkgs/applications/networking/mailreaders/thunderbird-2.x/default.nix b/pkgs/applications/networking/mailreaders/thunderbird-2.x/default.nix
index bde5f6364c4..d90d28b373c 100644
--- a/pkgs/applications/networking/mailreaders/thunderbird-2.x/default.nix
+++ b/pkgs/applications/networking/mailreaders/thunderbird-2.x/default.nix
@@ -11,12 +11,12 @@
 }:
 
 stdenv.mkDerivation {
-  name = "thunderbird-2.0.0.6";
+  name = "thunderbird-2.0.0.9";
 
   builder = ./builder.sh;
   src = fetchurl {
-    url = http://releases.mozilla.org/pub/mozilla.org/thunderbird/releases/2.0.0.6/source/thunderbird-2.0.0.6-source.tar.bz2;
-    sha1 = "c38b17ad0fc51aed96bacafe3ffe7ed0edd0738c";
+    url = http://releases.mozilla.org/pub/mozilla.org/thunderbird/releases/2.0.0.9/source/thunderbird-2.0.0.9-source.tar.bz2;
+    sha1 = "fede9db98f25adb978b84129a6d15a4dbe6bbb3e";
   };
 
   buildInputs = [
diff --git a/pkgs/applications/networking/msmtp/default.nix b/pkgs/applications/networking/msmtp/default.nix
index 523620a403e..67839833c31 100644
--- a/pkgs/applications/networking/msmtp/default.nix
+++ b/pkgs/applications/networking/msmtp/default.nix
@@ -1,14 +1,12 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "msmtp-1.4.13";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://dfn.dl.sourceforge.net/sourceforge/msmtp/msmtp-1.4.13.tar.bz2;
     sha256 = "1x8q8dhcpnjym3icz6070l13hz98fvdvgc5j5psj4pmxbswx0r4p";
   };
 
-  buildInputs =(with args; []);
-
   meta = { 
       description = "a MUA";
       homepage = http://msmtp.sourceforge.net/;
diff --git a/pkgs/applications/networking/remote/rdesktop/default.nix b/pkgs/applications/networking/remote/rdesktop/default.nix
new file mode 100644
index 00000000000..c81160ae57c
--- /dev/null
+++ b/pkgs/applications/networking/remote/rdesktop/default.nix
@@ -0,0 +1,20 @@
+{stdenv, fetchurl, openssl, libX11} :
+
+stdenv.mkDerivation (rec {
+  pname = "rdesktop";
+  version = "1.5.0";
+  name = "${pname}-${version}";
+
+  src = fetchurl {
+    url = "mirror://sourceforge/${pname}/${name}.tar.gz";
+    sha256 = "5ead17c3d29cb1028aeca485ee7a8c65694c1b02a1b7014c3da920b265a438aa";
+  };
+
+  buildInputs = [openssl libX11];
+
+  configureFlags = [ "--with-openssl=${openssl}" ];
+
+  meta = {
+    description = "rdesktop is an open source client for Windows Terminal Services";
+  };
+})
diff --git a/pkgs/applications/networking/skype/default.nix b/pkgs/applications/networking/skype/default.nix
index 443c92527f2..285cba82a3f 100644
--- a/pkgs/applications/networking/skype/default.nix
+++ b/pkgs/applications/networking/skype/default.nix
@@ -1,16 +1,16 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "skype-1.4";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://www.skype.com/go/getskype-linux-static;
     sha256 = "0k71byzaipmw8lb92aad4qyh9rk0fnn3za74v1h268h09gkkd8mz";
     name = "skype_static-1.4.0.99.tar.bz2";
   };
 
-  buildInputs =(with args; [alsaLib glibc libSM libICE libXi libXrender libXrandr libXfixes 
+  buildInputs = [alsaLib glibc libSM libICE libXi libXrender libXrandr libXfixes 
       libXcursor libXinerama freetype fontconfig libXext libX11 
-    fontconfig libXinerama libsigcxx gcc41.gcc ]);
+    fontconfig libXinerama libsigcxx gcc41.gcc ];
 
   phases = "installPhase";
   installPhase ="
diff --git a/pkgs/applications/networking/sniffers/wireshark/default.nix b/pkgs/applications/networking/sniffers/wireshark/default.nix
index f0b4038faba..67318531371 100644
--- a/pkgs/applications/networking/sniffers/wireshark/default.nix
+++ b/pkgs/applications/networking/sniffers/wireshark/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, perl, pkgconfig, gtk, libpcap}:
 
 stdenv.mkDerivation {
-  name = "wireshark-0.99.6";
+  name = "wireshark-0.99.7";
   src = fetchurl {
-    url = http://www.wireshark.org/download/src/wireshark-0.99.6.tar.gz;
-    sha256 = "1f2i84dk4nw05nh78b2j4n9pbwdngcqx0grrja5831r6paj35x1y";
+    url = http://www.wireshark.org/download/src/wireshark-0.99.7.tar.bz2;
+    sha256 = "10pb2mn6p40gsq2nbnqdzihrpa078jdgxqh8l4zs33bxa1h37frc";
   };
   buildInputs = [perl pkgconfig gtk libpcap];
 }
diff --git a/pkgs/applications/networking/sync/unison/default.nix b/pkgs/applications/networking/sync/unison/default.nix
index 75c976a4329..0883c236d01 100644
--- a/pkgs/applications/networking/sync/unison/default.nix
+++ b/pkgs/applications/networking/sync/unison/default.nix
@@ -7,21 +7,15 @@ stdenv.mkDerivation {
     sha256 = "808400a933aeb67654edc770822cd186d1b2adc92e7cb5836996c71c69ffe656";
   };
 
-  buildInputs = [ocaml];
+  buildInputs = [ocaml makeWrapper];
 
-  addInputsHook = "source $makeWrapper";
-  preBuild = "sed -i \"s|\\(OCAMLOPT=.*\\)$|\\1 -I $lablgtk/lib/ocaml/lablgtk2|\" Makefile.OCaml";
+  preBuild = "sed -i \"s|\\(OCAMLOPT=.*\\)$|\\1 -I ${lablgtk}/lib/ocaml/lablgtk2|\" Makefile.OCaml";
   makeFlags = "UISTYLE=gtk2 INSTALLDIR=$(out)/bin/";
   preInstall = "ensureDir $out/bin";
-  postInstall = [
-    "for i in $(cd $out/bin && ls); do"
-    "   mv $out/bin/$i $out/bin/.orig-$i;"
-    "   echo \"#! $SHELL\" > $out/bin/$i;"
-    "   echo \"$xset/bin/xset q | grep -q \\\"$fontschumachermisc\\\" || $xset/bin/xset +fp \\\"$fontschumachermisc/lib/X11/fonts/misc\\\"\" >> $out/bin/$i;"
-    "   echo \"exec \\\"$out/bin/.orig-$i\\\" \\\"\\\$@\\\"\" >> $out/bin/$i;"
-    "   chmod +x $out/bin/$i;"
-    "done"
-  ];
-
-  inherit lablgtk fontschumachermisc xset makeWrapper;
+  postInstall = ''
+    for i in $(cd $out/bin && ls); do
+      wrapProgram $out/bin/$i \
+        --run "${xset}/bin/xset q | grep -q \"${fontschumachermisc}\" || ${xset}/bin/xset +fp \"${fontschumachermisc}/lib/X11/fonts/misc\""
+    done
+  '';
 }
diff --git a/pkgs/applications/office/openoffice/builder.sh b/pkgs/applications/office/openoffice/builder.sh
index 124b64ffc2b..2a651a30058 100644
--- a/pkgs/applications/office/openoffice/builder.sh
+++ b/pkgs/applications/office/openoffice/builder.sh
@@ -13,6 +13,8 @@ preConfigure() {
 
     SRCDIR=
 
+    sed -e '/CURL_NO_OLDIES/d' -i ucb/source/ucp/ftp/makefile.mk
+
     cd config_office/
 }
 
diff --git a/pkgs/applications/office/openoffice/default.nix b/pkgs/applications/office/openoffice/default.nix
index 789bc5a53da..c7cedc69dee 100644
--- a/pkgs/applications/office/openoffice/default.nix
+++ b/pkgs/applications/office/openoffice/default.nix
@@ -10,11 +10,21 @@ stdenv.mkDerivation rec {
   name = "openoffice.org-2.3.0";
   builder = ./builder.sh;
 
-  src = fetchurl {
-	url = http://openoffice.bouncer.osuosl.org/?product=OpenOffice.org&os=src_bzip&lang=core&version=2.3.0;
-	name = "OOo_2.3.0_src_core.tar.bz2";
-    sha256 = "0mkxn9qj3f03rjkmxc4937gr2w429hnxzb9j5j2grdknfga5a1c3";
-  };
+  src =
+    #if (stdenv.system == "i686-linux") then
+      #fetchurl {
+        # stable 2.3.0 is failing - got the tip on the mailinglist to have look
+        # at http://www.openoffice.org/issues/show_bug.cgi?id=74751
+        # now I'm trying snapshot because it should already have this patch
+        #url = http://ftp.ussg.iu.edu/openoffice/contrib/rc/2.3.1rc1/OOo_2.3.1rc1_src_core.tar.bz2;
+        #name = "OOo_2.3.1_src_core.tar.bz2";
+        #sha256 = "";
+    #} else 
+    fetchurl {
+        url = http://openoffice.bouncer.osuosl.org/?product=OpenOffice.org&os=src_bzip&lang=core&version=2.3.0;
+        name = "OOo_2.3.0_src_core.tar.bz2";
+        sha256 = "0mkxn9qj3f03rjkmxc4937gr2w429hnxzb9j5j2grdknfga5a1c3";
+    };
 
   configureFlags = "
     --with-package-format=native
@@ -63,7 +73,14 @@ stdenv.mkDerivation rec {
 
   inherit icu fontconfig libjpeg jdk cups;
 
-  patches = [./ooo-libtextcat.patch];
+  # libawt_problem see http://www.openoffice.org/issues/show_bug.cgi?id=74751 
+  # Can be removed in newer releases than 2.3.0
+  patch_file = ./libawt_problem;
+  patches = [./ooo-libtextcat.patch ];
+  patchPhase = " 
+  patch config_office/set_soenv.in \$patch_file
+  unset patchPhase; patchPhase;
+  ";
 
   meta = {
     description = "OpenOffice.org is a multiplatform and multilingual office suite";
diff --git a/pkgs/applications/office/openoffice/libawt_problem b/pkgs/applications/office/openoffice/libawt_problem
new file mode 100644
index 00000000000..edfb72cd8d2
--- /dev/null
+++ b/pkgs/applications/office/openoffice/libawt_problem
@@ -0,0 +1,10 @@
+--- config_office/set_soenv.in  2007-02-21 16:31:51.000000000 +0100
++++ config_office/set_soenv.in.new      2007-02-21 20:37:17.000000000 +0100
+@@ -426,6 +426,7 @@
+       $OUTPATH        = "unxlngx6";
+       # Blackdown.org JDK porting project uses `amd64' and `server' in JDK 1.4.2 RC1
+       $JRELIBDIR      = '$JAVA_HOME'.$ds."jre".$ds."lib".$ds."amd64";
++      $JREEXTRALIBDIR = '$JAVA_HOME'.$ds."jre".$ds."lib".$ds."amd64".$ds."xawt";
+       $JRETOOLKITDIR  = '$JAVA_HOME'.$ds."jre".$ds."lib".$ds."amd64".$ds."server";
+       $JRETHREADDIR   = '$JAVA_HOME'.$ds."jre".$ds."lib".$ds."amd64".$ds."native_threads";
+    }
diff --git a/pkgs/applications/version-management/arch/configure-tmpdir.patch b/pkgs/applications/version-management/arch/configure-tmpdir.patch
new file mode 100644
index 00000000000..2b39322ca22
--- /dev/null
+++ b/pkgs/applications/version-management/arch/configure-tmpdir.patch
@@ -0,0 +1,11 @@
+--- tla-1.3.5/src/build-tools/auto-conf-lib/gnu-patch-test	2006-07-20 08:34:28.000000000 +0200
++++ tla-1.3.5/src/build-tools/auto-conf-lib/gnu-patch-test	2008-02-17 13:00:07.000000000 +0100
+@@ -27,7 +27,7 @@ else
+ fi
+ 
+ CMP='cmp'    # we require a working 'cmp' utility
+-TMPDIR="/tmp/,patch-test.$$"
++TMPDIR="${TMPDIR:-/tmp}/,patch-test.$$"
+ 
+ ORIG_A="$TMPDIR/to-patch_a"
+ ORIG_PRISTINE_A="$TMPDIR/to-patch_a.the-original"
diff --git a/pkgs/applications/version-management/arch/default.nix b/pkgs/applications/version-management/arch/default.nix
new file mode 100644
index 00000000000..0a54eabd595
--- /dev/null
+++ b/pkgs/applications/version-management/arch/default.nix
@@ -0,0 +1,29 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "tla-1.3.5";
+  src = fetchurl {
+    url = "mirror://gnu/gnu-arch/" + name + ".tar.gz";
+    sha256 = "01mfzj1i6p4s8191cgd5850hds1zls88hkf9rb6qx1vqjv585aj0";
+  };
+
+  patches = [ ./configure-tmpdir.patch ];
+
+  buildInputs = [which];
+  propagatedBuildInputs = [diffutils gnupatch gnutar];
+
+  # Instead of GNU Autoconf, tla uses Tom Lord's now
+  # defunct `package-framework'.
+  buildPhase = ''
+    mkdir +build && cd +build &&		\
+    ../src/configure --prefix="$out" &&		\
+    make install
+  '';
+
+  meta = {
+    description = ''GNU Arch (aka. `tla'), a distributed revision
+    		    control system.'';
+    homepage = http://www.gnu.org/software/gnu-arch/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/applications/version-management/bazaar/default.nix b/pkgs/applications/version-management/bazaar/default.nix
new file mode 100644
index 00000000000..71134c0841a
--- /dev/null
+++ b/pkgs/applications/version-management/bazaar/default.nix
@@ -0,0 +1,22 @@
+{stdenv, fetchurl, python, makeWrapper}:
+
+stdenv.mkDerivation {
+  name = "bazaar-1.1";
+
+  src = fetchurl {
+    url = https://launchpad.net/bzr/1.1/1.1/+download/bzr-1.1.tar.gz;
+    sha256 = "1qpkw580r22yxybdghx2ha0kyk22brbhd1kg9wwjh209dqy2gqzc";
+  };
+
+  buildInputs = [python makeWrapper];
+
+  installPhase = ''
+    python setup.py install --prefix=$out
+    wrapProgram $out/bin/bzr --prefix PYTHONPATH : "$(toPythonPath $out)"
+  '';
+
+  meta = {
+    homepage = http://bazaar-vcs.org/;
+    description = "A distributed version control system that Just Works";
+  };
+}
diff --git a/pkgs/applications/version-management/cvs2svn/default.nix b/pkgs/applications/version-management/cvs2svn/default.nix
index e519be92733..65c2c84d0da 100644
--- a/pkgs/applications/version-management/cvs2svn/default.nix
+++ b/pkgs/applications/version-management/cvs2svn/default.nix
@@ -1,25 +1,27 @@
-{stdenv, fetchurl, python, bsddb3, makeWrapper}:
+{stdenv, fetchurl, python, makeWrapper}:
 
 stdenv.mkDerivation {
-  name = "cvs2svn-1.5.1";
+  name = "cvs2svn-2.0.1";
 
   src = fetchurl {
-    url = http://cvs2svn.tigris.org/files/documents/1462/36129/cvs2svn-1.5.1.tar.gz;
-    md5 = "d1e42ea51b373be0023f2b3f6b80ec01";
+    url = http://cvs2svn.tigris.org/files/documents/1462/39919/cvs2svn-2.0.1.tar.gz;
+    sha256 = "1pgbyxzgn22lnw3h5c2nd8z46pkk863jg3fgh9pqa1jihsx1cg1j";
   };
 
-  buildInputs = [python bsddb3];
+  buildInputs = [python makeWrapper];
 
   buildPhase = "true";
-  installPhase = "
+  installPhase = ''
     python ./setup.py install --prefix=$out
-
-    source ${makeWrapper}
-    mv $out/bin/cvs2svn $out/bin/.orig-cvs2svn
-    makeWrapper $out/bin/.orig-cvs2svn $out/bin/cvs2svn \\
-        --set PYTHONPATH \"$(toPythonPath $out):$(toPythonPath ${bsddb3}):$PYTHONPATH\"
-  ";
+    wrapProgram $out/bin/cvs2svn \
+        --set PYTHONPATH "$(toPythonPath $out):$PYTHONPATH"
+  '';
 
   /* !!! maybe we should absolutise the program names in
      $out/lib/python2.4/site-packages/cvs2svn_lib/config.py. */
-}
\ No newline at end of file
+
+  meta = {
+    description = "A tool to convert CVS repositories to Subversion repositories";
+    homepage = http://cvs2svn.tigris.org/;
+  };
+}
diff --git a/pkgs/applications/version-management/darcs_2_pre.nix b/pkgs/applications/version-management/darcs_2_pre.nix
new file mode 100644
index 00000000000..a8bd48aa336
--- /dev/null
+++ b/pkgs/applications/version-management/darcs_2_pre.nix
@@ -0,0 +1,16 @@
+{stdenv, fetchurl, ghc, zlib, ncurses, curl}:
+
+stdenv.mkDerivation {
+  name = "darcs-2.0.0pre3";
+  src = fetchurl {
+    url = http://darcs.net/darcs-2.0.0pre3.tar.gz;
+    sha256 = "";
+  };
+  buildInputs = [ghc zlib ncurses curl];
+
+  NIX_LDFLAGS = "-lz";
+
+  meta = {
+    description = "Patch-based version management system";
+  };
+}
diff --git a/pkgs/applications/version-management/git/default.nix b/pkgs/applications/version-management/git/default.nix
index 138b4d61449..9cd69bf9008 100644
--- a/pkgs/applications/version-management/git/default.nix
+++ b/pkgs/applications/version-management/git/default.nix
@@ -1,16 +1,31 @@
-{stdenv, fetchurl, curl, openssl, zlib, expat, perl}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "git-1.5.1.2";
+stdenv.mkDerivation rec {
+  name = "git-1.5.4.2";
 
   src = fetchurl {
-    url = mirror://kernel/software/scm/git/git-1.5.1.2.tar.bz2;
-    sha256 = "0a7nnw9631h6nxk7sny0cjv89qlibilvsm6947620vr2kgc6p6k2";
+    url = "mirror://kernel/software/scm/git/${name}.tar.bz2";
+    sha256 = "089n3da06k19gzhacsqgaamgx5hy5r50r2b4a626s87w44mj78sn";
   };
 
-  buildInputs = [curl openssl zlib expat];
+  buildInputs = [curl openssl zlib expat gettext emacs];
 
-  preBuild = "
-    makeFlagsArray=(prefix=$out PERL_PATH=${perl}/bin/perl SHELL_PATH=${stdenv.shell})
-  ";
+  makeFlags="prefix=\${out} PERL_PATH=${perl}/bin/perl SHELL_PATH=${stdenv.shell}";
+
+  postInstall = ''
+    # Install Emacs mode.
+    echo "installing Emacs mode..."
+    make install -C contrib/emacs prefix="$out"
+
+    # XXX: There are other things under `contrib' that people might want to
+    # install.
+  '';
+
+  meta = {
+    license = "GPLv2";
+    homepage = http://git.or.cz;
+    description = ''Git, a popular distributed version control system
+                    designed to handle very large projects with speed
+		    and efficiency.'';
+  };
 }
diff --git a/pkgs/applications/version-management/mercurial/default.nix b/pkgs/applications/version-management/mercurial/default.nix
index 253907ab4bd..408c9d8ebac 100644
--- a/pkgs/applications/version-management/mercurial/default.nix
+++ b/pkgs/applications/version-management/mercurial/default.nix
@@ -1,26 +1,23 @@
-{stdenv, fetchurl, python, makeWrapper}:
+args: with args;
 
 stdenv.mkDerivation {
-  name = "mercurial-0.9.4";
+  name = "mercurial-0.9.5";
   src = fetchurl {
-    url = http://www.selenic.com/mercurial/release/mercurial-0.9.4.tar.gz;
-    sha256 = "26996df67d508e129d2f0a264e25072764e5c2d21606e1658d77c8984e6ed64a";
+    url = http://www.selenic.com/mercurial/release/mercurial-0.9.5.tar.gz;
+    sha256 = "1n34yl4z7nc3vmsgpkmqc94hsmy846ny86xgpgv3m371ljm2pq6g";
   };
 
-  inherit makeWrapper;
-
-  buildInputs = [ python ];
-  addInputsHook = "source $makeWrapper";
+  buildInputs = [ python makeWrapper ];
   makeFlags = "PREFIX=$(out)";
-  postInstall = [
-    "for i in $(cd $out/bin && ls); do"
-    "   mv $out/bin/$i $out/bin/.orig-$i;"
-    "   makeWrapper $out/bin/.orig-$i $out/bin/$i"
-    "       --set PYTHONPATH \"$(toPythonPath $out):$PYTHONPATH\";"
-    "done"
-  ];
+  postInstall = ''
+    for i in $(cd $out/bin && ls); do
+      wrapProgram $out/bin/$i \
+        --prefix PYTHONPATH : "$(toPythonPath $out)"
+    done
+  '';
 
   meta = {
-    description = "a fast, lightweight SCM system for very large distributed projects";
+    description = "A fast, lightweight SCM system for very large distributed projects";
+    homepage = http://www.selenic.com/mercurial/;
   };
 }
diff --git a/pkgs/applications/version-management/monotone/default.nix b/pkgs/applications/version-management/monotone/default.nix
new file mode 100644
index 00000000000..fc2339af6a5
--- /dev/null
+++ b/pkgs/applications/version-management/monotone/default.nix
@@ -0,0 +1,10 @@
+{stdenv, fetchurl, boost, zlib}:
+
+stdenv.mkDerivation {
+  name = "monotone-0.38";
+  src = fetchurl {
+    url = http://monotone.ca/downloads/0.38/monotone-0.38.tar.gz;
+    md5 = "c1a0d2619f451a664289b042c104860d";
+  };
+  buildInputs = [boost zlib];
+}
diff --git a/pkgs/applications/version-management/subversion-1.4.x/builder.sh b/pkgs/applications/version-management/subversion-1.4.x/builder.sh
index e91f9f9113d..70d78b4a624 100644
--- a/pkgs/applications/version-management/subversion-1.4.x/builder.sh
+++ b/pkgs/applications/version-management/subversion-1.4.x/builder.sh
@@ -7,8 +7,16 @@ fi
 
 postInstall() {
     if test "$pythonBindings"; then
-        make swig-py
-        make install-swig-py
+        make swig-py swig_pydir=$(toPythonPath $out)/libsvn swig_pydir_extra=$(toPythonPath $out)/svn
+        make install-swig-py swig_pydir=$(toPythonPath $out)/libsvn swig_pydir_extra=$(toPythonPath $out)/svn
+    fi
+    if test "$perlBindings"; then
+        make swig-pl-lib
+        make install-swig-pl-lib
+        cd subversion/bindings/swig/perl/native
+        perl Makefile.PL PREFIX=$out
+        make install
+        cd -
     fi
     if test "$javahlBindings"; then
         mkdir -p subversion/bindings/java/javahl/classes # bug fix
diff --git a/pkgs/applications/version-management/subversion-1.4.x/default.nix b/pkgs/applications/version-management/subversion-1.4.x/default.nix
index 38333daa2f9..d09176302b8 100644
--- a/pkgs/applications/version-management/subversion-1.4.x/default.nix
+++ b/pkgs/applications/version-management/subversion-1.4.x/default.nix
@@ -3,6 +3,7 @@
 , sslSupport ? false
 , compressionSupport ? false
 , pythonBindings ? false
+, perlBindings ? false
 , javahlBindings ? false
 , stdenv, fetchurl, apr, aprutil, neon, zlib
 , httpd ? null, expat, swig ? null, jdk ? null
@@ -16,17 +17,19 @@ assert sslSupport -> neon.sslSupport;
 assert compressionSupport -> neon.compressionSupport;
 
 stdenv.mkDerivation {
-  name = "subversion-1.4.5";
+  name = "subversion-1.4.6";
 
   builder = ./builder.sh;
   src = fetchurl {
-    url = http://subversion.tigris.org/downloads/subversion-1.4.5.tar.bz2;
-    sha1 = "acc80381cb670736ad626fee1eb04f36ba7e5fc8";
+    url = http://subversion.tigris.org/downloads/subversion-1.4.6.tar.bz2;
+    sha1 = "a9c941e2309744f6a2986200698b60da057a7527";
   };
 
   buildInputs =
     [expat zlib]
-    ++ (if pythonBindings then [swig.python] else []);
+    ++ (if pythonBindings then [swig.python] else [])
+    ++ (if perlBindings then [swig.perl] else [])
+	;
 
   configureFlags = "
     --without-gdbm --disable-static
@@ -37,14 +40,17 @@ stdenv.mkDerivation {
         "--with-apxs=${httpd}/bin/apxs --with-apr=${httpd} --with-apr-util=${httpd}"
       else
         "--without-apxs"}
-    ${if pythonBindings then "--with-swig=${swig}" else "--without-swig"}
+    ${if (pythonBindings || perlBindings) then "--with-swig=${swig}" else "--without-swig"}
     ${if javahlBindings then "--enable-javahl --with-jdk=${jdk}" else ""}
     --disable-neon-version-check
   ";
 
-  inherit httpServer pythonBindings javahlBindings;
+  inherit httpServer pythonBindings javahlBindings perlBindings;
+  patches = [ ./subversion-respect_CPPFLAGS_in_perl_bindings.patch ];
 
   meta = {
     description = "A version control system intended to be a compelling replacement for CVS in the open source community";
+    homepage = http://subversion.tigris.org/;
   };
 }
+
diff --git a/pkgs/applications/version-management/subversion-1.4.x/subversion-respect_CPPFLAGS_in_perl_bindings.patch b/pkgs/applications/version-management/subversion-1.4.x/subversion-respect_CPPFLAGS_in_perl_bindings.patch
new file mode 100644
index 00000000000..86c18145c2e
--- /dev/null
+++ b/pkgs/applications/version-management/subversion-1.4.x/subversion-respect_CPPFLAGS_in_perl_bindings.patch
@@ -0,0 +1,22 @@
+Index: subversion/bindings/swig/perl/native/Makefile.PL.in
+===================================================================
+--- subversion-1.4.5/subversion/bindings/swig/perl/native/Makefile.PL.in	(revision 27184)
++++ subversion-1.4.5/subversion/bindings/swig/perl/native/Makefile.PL.in	(working copy)
+@@ -26,6 +26,7 @@
+ my @ldmodules = map {"-lsvn_$_-1"} (@modules, qw/diff subr/);
+ 
+ my $apr_shlib_path_var = '@SVN_APR_SHLIB_PATH_VAR@';
++my $cppflags = '@CPPFLAGS@';
+ my $apr_cflags = '@SVN_APR_INCLUDES@';
+ my $apu_cflags = '@SVN_APRUTIL_INCLUDES@';
+ 
+@@ -38,7 +39,7 @@
+ 
+ my %config = (
+     ABSTRACT => 'Perl bindings for Subversion',
+-    INC  => join(' ',$apr_cflags, $apu_cflags, 
++    INC  => join(' ', $cppflags, $apr_cflags, $apu_cflags, 
+                  " -I$swig_srcdir/perl/libsvn_swig_perl",
+                  " -I$svnlib_srcdir/include",
+                  " -I$svnlib_builddir",
+
diff --git a/pkgs/applications/video/kino/default.nix b/pkgs/applications/video/kino/default.nix
new file mode 100644
index 00000000000..cac769d60de
--- /dev/null
+++ b/pkgs/applications/video/kino/default.nix
@@ -0,0 +1,90 @@
+# is this configure option of interest?
+#--enable-udev-rules-dir=PATH
+#                        Where to install udev rules (/etc/udev/rules.d)
+
+#TODO shared version?
+
+
+# This is my config output.. Much TODO ?
+#source path               /tmp/nix-31998-1/kino-1.2.0/ffmpeg
+#C compiler                gcc
+#make                      make
+#.align is power-of-two    no
+#ARCH                      x86_64 (generic)
+#build suffix              -kino
+#big-endian                no
+#MMX enabled               yes
+#CMOV enabled              no
+#CMOV is fast              no
+#gprof enabled             no
+#debug symbols             yes
+#strip symbols             yes
+#optimize                  yes
+#static                    yes
+#shared                    no
+#postprocessing support    no
+#software scaler enabled   yes
+#video hooking             no
+#network support           no
+#threading support         no
+#SDL support               no
+#Sun medialib support      no
+#AVISynth enabled          no
+#liba52 support            no
+#liba52 dlopened           no
+#libdts support            no
+#libfaac enabled           no
+#libfaad enabled           no
+#faadbin enabled           no
+#libgsm enabled            no
+#libmp3lame enabled        no
+#libnut enabled            no
+#libogg enabled            no
+#libtheora enabled         no
+#libvorbis enabled         no
+#x264 enabled              no
+#XviD enabled              no
+#zlib enabled              no
+#AMR-NB float support      no
+#AMR-NB fixed support      no
+#AMR-WB float support      no
+#AMR-WB IF2 support        no
+
+
+args: with args;
+stdenv.mkDerivation {
+  name = "kino-1.2.0";
+
+  phases = "unpackPhase configurePhase buildPhase installPhase";
+
+  src = fetchurl {
+    url = http://downloads.sourceforge.net/kino/kino-1.2.0.tar.gz;
+    sha256 = "15q1qmii5a2zbrrrg8iba2d1rjzaisa75zvxjhrs86jwglpn4lp9";
+  };
+
+  buildInputs = [ gtk libglade libxml2 libraw1394 libsamplerate libdv 
+      pkgconfig perl perlXMLParser libavc1394 libiec61883 x11 libXv gettext libX11 glib cairo ]; # TODOoptional packages 
+
+  #preConfigure = "
+  #  grep 11 env-vars
+  #  ex
+  #";
+
+  postInstall = "
+    rpath=`patchelf --print-rpath \$out/bin/kino`;
+    for i in $\buildInputs; do
+      echo adding \$i/lib
+      rpath=\$rpath\${rpath:+:}\$i/lib
+    done
+    for i in \$out/bin/*; do
+      patchelf --set-rpath \"\$rpath\" \"\$i\"
+    done
+  ";
+
+
+  meta = { 
+      description = "Kino is a non-linear DV editor for GNU/Linux";
+      homepage = http://www.kinodv.org/;
+      license = "GPL2";
+  };
+}
diff --git a/pkgs/applications/video/vlc/default.nix b/pkgs/applications/video/vlc/default.nix
index d8db6d0396a..0d499008b0c 100644
--- a/pkgs/applications/video/vlc/default.nix
+++ b/pkgs/applications/video/vlc/default.nix
@@ -8,11 +8,11 @@ assert libdvdread.libdvdcss == libdvdcss;
 assert xvSupport -> libXv != null;
 
 stdenv.mkDerivation {
-  name = "vlc-0.8.6c";
+  name = "vlc-0.8.6d";
 
   src = fetchurl {
-    url = http://download.videolan.org/pub/videolan/vlc/0.8.6c/vlc-0.8.6c.tar.bz2;
-    sha256 = "1bmngn66i527vw9g5xnhlpz64xl5gch3j3l6y5d727rcpmxlvhjz";
+    url = http://download.videolan.org/pub/videolan/vlc/0.8.6d/vlc-0.8.6d.tar.bz2;
+    sha256 = "019jw9cp7fbmhbmlbwvjgpamxwx0rdajyxab2sbmh4n6v04fl266";
   };
 
   buildInputs = [
@@ -30,5 +30,6 @@ stdenv.mkDerivation {
 
   meta = {
     description = "Cross-platform media player and streaming server";
+    homepage = http://www.videolan.org/vlc/;
   };
 }
diff --git a/pkgs/applications/video/xine-ui/default.nix b/pkgs/applications/video/xine-ui/default.nix
index ff0aa091400..52a4a773607 100644
--- a/pkgs/applications/video/xine-ui/default.nix
+++ b/pkgs/applications/video/xine-ui/default.nix
@@ -1,5 +1,4 @@
-{stdenv, fetchurl, pkgconfig, x11, xineLib, libpng}:
-
+args: with args;
 stdenv.mkDerivation {
   name = "xine-ui-0.99.5";
   src = fetchurl {
@@ -7,10 +6,12 @@ stdenv.mkDerivation {
     sha256 = "07jywadk6fhk3wn1j9m0cfa0zy0i17kz0nyyxwa3shvhznfals0k";
   };
   buildInputs = [
-    pkgconfig x11 xineLib libpng
+    pkgconfig x11 xineLib libpng libXext libXv readline ncurses libXxf86vm
+	libXtst inputproto curl
     (if xineLib.xineramaSupport then xineLib.libXinerama else null)
   ];
-  configureFlags = "--without-readline --disable-xft";
+  configureFlags = "--with-readline=${readline}";
+  NIX_LDFLAGS="-L${libXext}/lib -lXext";
 
   meta = {
     description = "Xlib-based interface to Xine, a video player";
diff --git a/pkgs/applications/virtualization/qemu/0.9.0.nix b/pkgs/applications/virtualization/qemu/0.9.0.nix
new file mode 100644
index 00000000000..439ec34a8c3
--- /dev/null
+++ b/pkgs/applications/virtualization/qemu/0.9.0.nix
@@ -0,0 +1,27 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://fabrice.bellard.free.fr/qemu/qemu-0.9.0.tar.gz;
+			sha256 = "1h85njd8xvn472yhcm92rjyzqjr719ab73rxwmz9cm2n6gwsq7s9";
+		};
+
+		buildInputs = [ SDL zlib which ];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+preConfigure = FullDepEntry ("
+  gcc --version
+") [minInit];
+in
+stdenv.mkDerivation rec {
+	name = "qemu-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [ preConfigure doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		QEmu processor emulator.
+";
+	};
+}
diff --git a/pkgs/applications/virtualization/qemu/linux-img/0.2.nix b/pkgs/applications/virtualization/qemu/linux-img/0.2.nix
new file mode 100644
index 00000000000..99d222070c2
--- /dev/null
+++ b/pkgs/applications/virtualization/qemu/linux-img/0.2.nix
@@ -0,0 +1,28 @@
+
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://fabrice.bellard.free.fr/qemu/linux-0.2.img.bz2;
+			sha256 = "08xlwy1908chpc4fsqy2v13zi25dapk0ybrd43fj95v67kdj5hj1";
+		};
+		buildInputs = [];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+doCopy = FullDepEntry ("
+  ensureDir \$out/share/qemu-images
+  cp linux-${version}.img  \$out/share/qemu-images/
+") [minInit doUnpack defEnsureDir];
+in
+stdenv.mkDerivation rec {
+	name = "QEmu-Linux-Image-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doCopy doForceShare doPropagate]);
+	meta = {
+		description = "
+		${abort "Write a description"}
+";
+	};
+}
diff --git a/pkgs/applications/virtualization/virtualbox/1.5.2.nix b/pkgs/applications/virtualization/virtualbox/1.5.2.nix
new file mode 100644
index 00000000000..e8f2988ade2
--- /dev/null
+++ b/pkgs/applications/virtualization/virtualbox/1.5.2.nix
@@ -0,0 +1,22 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://www.virtualbox.org/download/1.5.2/VirtualBox-1.5.2_OSE.tar.bz2;
+			sha256 = "1g9rvkqjcsfx36gwk6i9c0bml6053xx2mdn1sn7vyyy0sgwkwk53";
+		};
+		buildInputs = [libXcursor bridge_utils umlutilities kernelHeaders 
+		      wine jre libxslt libIDL SDL qt3 openssl zlib];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "VirtualBox-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Virtual Box is just software for running virtual machines. 
+";
+	};
+}
diff --git a/pkgs/applications/window-managers/compiz-fusion/bcop/0.6.0.nix b/pkgs/applications/window-managers/compiz-fusion/bcop/0.6.0.nix
index ee6fd586dfe..6337d6a4ebe 100644
--- a/pkgs/applications/window-managers/compiz-fusion/bcop/0.6.0.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/bcop/0.6.0.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/0.6.0/compiz-bcop-0.6.0.tar.bz2;
@@ -9,6 +9,7 @@ args : with args;
 		propagatedBuildInputs = [getopt libxslt];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 let 
 	fixPkgconfig = FullDepEntry ("
 		ensureDir \$out/lib
@@ -21,8 +22,9 @@ in
 stdenv.mkDerivation rec {
 	name = "compiz-bcop-"+version;
 	builder = writeScript (name + "-builder")
-		(textClosure [doAutotools doConfigure doMakeInstall fixPkgconfig fixInterpreter doForceShare 
+		(textClosure localDefs [doAutotools doConfigure doMakeInstall fixPkgconfig fixInterpreter doForceShare 
 			doPropagate]);
+	inherit propagatedBuildInputs;
 	meta = {
 		description = "
 	Compiz BCOP.
diff --git a/pkgs/applications/window-managers/compiz-fusion/bcop/default.nix b/pkgs/applications/window-managers/compiz-fusion/bcop/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz-fusion/bcop/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz-fusion/ccsm/0.6.0.nix b/pkgs/applications/window-managers/compiz-fusion/ccsm/0.6.0.nix
index fba1c5d995f..6e3448bebf8 100644
--- a/pkgs/applications/window-managers/compiz-fusion/ccsm/0.6.0.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/ccsm/0.6.0.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/0.6.0/ccsm-0.6.0.tar.bz2;
@@ -15,10 +15,11 @@ args : with args;
 			"PYTHONPATH" "$(toPythonPath ${pygtk})/gtk-2.0"
 		];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 stdenv.mkDerivation rec {
 	name = "compizconfig-settings-"+args.version;
 	builder = writeScript (name + "-builder")
-		(textClosure [installPythonPackage (doWrap "\$out/bin/ccsm")]);
+		(textClosure localDefs [installPythonPackage (doWrap "\$out/bin/ccsm")]);
 	meta = {
 		description = "
 	Compiz Settings Manager
diff --git a/pkgs/applications/window-managers/compiz-fusion/ccsm/default.nix b/pkgs/applications/window-managers/compiz-fusion/ccsm/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz-fusion/ccsm/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz-fusion/compiz-manager/0.6.0.nix b/pkgs/applications/window-managers/compiz-fusion/compiz-manager/0.6.0.nix
index a3885507480..6033ea1663a 100644
--- a/pkgs/applications/window-managers/compiz-fusion/compiz-manager/0.6.0.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/compiz-manager/0.6.0.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/0.6.0/compiz-manager-0.6.0.tar.bz2;
@@ -20,6 +20,7 @@ args : with args;
 			"XORG_DRIVER_PATH" "/nix/store/.*"
 		]];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 let
 	install = FullDepEntry ("
 		sed -e '/Checking for texture_from_pixmap:/areturn 0' -i compiz-manager
@@ -34,7 +35,7 @@ in
 stdenv.mkDerivation rec {
 	name = "compiz-manager-"+args.version;
 	builder = writeScript (name + "-builder")
-		(textClosure [doUnpack doReplaceScripts install doPropagate doForceShare]);
+		(textClosure localDefs [doUnpack doReplaceScripts install doPropagate doForceShare]);
 	meta = {
 		description = "
 	Compiz Launch Manager
diff --git a/pkgs/applications/window-managers/compiz-fusion/compiz-manager/default.nix b/pkgs/applications/window-managers/compiz-fusion/compiz-manager/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz-fusion/compiz-manager/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz-fusion/compizconfig-python/0.6.0.nix b/pkgs/applications/window-managers/compiz-fusion/compizconfig-python/0.6.0.nix
index 73f1c653361..64247cb1b8d 100644
--- a/pkgs/applications/window-managers/compiz-fusion/compizconfig-python/0.6.0.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/compizconfig-python/0.6.0.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/0.6.0.1/compizconfig-python-0.6.0.1.tar.bz2;
@@ -9,10 +9,11 @@ args : with args;
 			[libcompizconfig bcop python pyrex configBackendGConf];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 stdenv.mkDerivation rec {
 	name = "compizconfig-python-"+args.version;
 	builder = writeScript (name + "-builder")
-		(textClosure [doAutotools doConfigure doMakeInstall doForceShare]);
+		(textClosure localDefs [doAutotools doConfigure doMakeInstall doForceShare]);
 	meta = {
 		description = "
 	Compiz configuration - Python part.
diff --git a/pkgs/applications/window-managers/compiz-fusion/compizconfig-python/default.nix b/pkgs/applications/window-managers/compiz-fusion/compizconfig-python/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz-fusion/compizconfig-python/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz-fusion/config-backend/0.6.0.nix b/pkgs/applications/window-managers/compiz-fusion/config-backend/0.6.0.nix
index 3405ae0ce97..12ef3bb58a0 100644
--- a/pkgs/applications/window-managers/compiz-fusion/config-backend/0.6.0.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/config-backend/0.6.0.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/0.6.0/compizconfig-backend-gconf-0.6.0.tar.bz2;
@@ -10,10 +10,11 @@ args : with args;
 		configureFlags = [];
 		forceShare = ["man" "doc" "info" "lib/compizconfig"];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 stdenv.mkDerivation rec {
 	name = "compizconfig-backend-GConf-"+version;
 	builder = writeScript (name + "-builder")
-		(textClosure [doAutotools doConfigure doMakeInstall doForceShare doPropagate]);
+		(textClosure localDefs [doAutotools doConfigure doMakeInstall doForceShare doPropagate]);
 	meta = {
 		description = "
 	Compiz configuration backend (GConf).
diff --git a/pkgs/applications/window-managers/compiz-fusion/config-backend/default.nix b/pkgs/applications/window-managers/compiz-fusion/config-backend/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz-fusion/config-backend/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz-fusion/default.nix b/pkgs/applications/window-managers/compiz-fusion/default.nix
index 156d3d281d7..589b77d0f23 100644
--- a/pkgs/applications/window-managers/compiz-fusion/default.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/default.nix
@@ -1,13 +1,14 @@
 args : with args;
 rec
 {
-	bcop = import ./bcop args;
-	libcompizconfig = import ./libcompizconfig (args // {inherit bcop;});
-	configBackendGConf = import ./config-backend (args // {inherit bcop libcompizconfig;});
-	compizConfigPython = import ./compizconfig-python (args // {inherit libcompizconfig 
+        selectVersion = dir: import (dir + "/${args.version}.nix");
+	bcop = selectVersion ./bcop args;
+	libcompizconfig = selectVersion ./libcompizconfig (args // {inherit bcop;});
+	configBackendGConf = selectVersion ./config-backend (args // {inherit bcop libcompizconfig;});
+	compizConfigPython = selectVersion ./compizconfig-python (args // {inherit libcompizconfig 
 		bcop pyrex configBackendGConf;});
-	ccsm = import ./ccsm (args // {inherit libcompizconfig bcop compizConfigPython configBackendGConf;});
-	pluginsMain = import ./main (args //{inherit bcop ;});
-	pluginsExtra = import ./extra (args //{inherit bcop pluginsMain;});
-	compizManager = import ./compiz-manager (args // {inherit bcop ccsm;});
+	ccsm = selectVersion ./ccsm (args // {inherit libcompizconfig bcop compizConfigPython configBackendGConf;});
+	pluginsMain = selectVersion ./main (args //{inherit bcop ;});
+	pluginsExtra = selectVersion ./extra (args //{inherit bcop pluginsMain;});
+	compizManager = selectVersion ./compiz-manager (args // {inherit bcop ccsm;});
 }
diff --git a/pkgs/applications/window-managers/compiz-fusion/extra/0.6.0.nix b/pkgs/applications/window-managers/compiz-fusion/extra/0.6.0.nix
index e304eb9d6ae..cc6b2f215ca 100644
--- a/pkgs/applications/window-managers/compiz-fusion/extra/0.6.0.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/extra/0.6.0.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/0.6.0/compiz-fusion-plugins-extra-0.6.0.tar.bz2;
@@ -9,6 +9,7 @@ args : with args;
 		[bcop libjpeg gettext pluginsMain];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 let
 	sharePlugins = FullDepEntry ("
 		ensureDir \$out/share/compiz-plugins
@@ -22,7 +23,7 @@ in
 stdenv.mkDerivation rec {
 	name = "compiz-fusion-plugins-extra-"+version;
 	builder = writeScript (name + "-builder")
-		(textClosure [fixIncludes doConfigure doMakeInstall sharePlugins doForceShare]);
+		(textClosure localDefs [fixIncludes doConfigure doMakeInstall sharePlugins doForceShare]);
 	meta = {
 		description = "
 	Extra Compiz Fusion plugins.
diff --git a/pkgs/applications/window-managers/compiz-fusion/extra/default.nix b/pkgs/applications/window-managers/compiz-fusion/extra/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz-fusion/extra/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz-fusion/general-dependencies.nix b/pkgs/applications/window-managers/compiz-fusion/general-dependencies.nix
index 1a041eaf2d6..f02857cf80a 100644
--- a/pkgs/applications/window-managers/compiz-fusion/general-dependencies.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/general-dependencies.nix
@@ -3,7 +3,7 @@ build-essential libxcomposite-dev libpng12-dev libsm-dev libxrandr-dev libxdamag
 */
 args: with args;
 [
-	libXcomposite libpng libSM libXrandr libXdamage libXinerama startupnotification 
-	GConf mesa metacity librsvg dbus dbus_glib gnomedesktop git autoconf automake
+	libpng 
+	GConf mesa metacity librsvg dbus.libs dbus_glib gnomedesktop git autoconf automake
 	libtool libxslt libwnck intltool perl perlXMLParser compiz
 ]
diff --git a/pkgs/applications/window-managers/compiz-fusion/libcompizconfig/0.6.0.nix b/pkgs/applications/window-managers/compiz-fusion/libcompizconfig/0.6.0.nix
index 8b5d729dc2d..5602c657867 100644
--- a/pkgs/applications/window-managers/compiz-fusion/libcompizconfig/0.6.0.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/libcompizconfig/0.6.0.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/0.6.0/libcompizconfig-0.6.0.tar.bz2;
@@ -9,10 +9,11 @@ args : with args;
 			[bcop];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 stdenv.mkDerivation rec {
 	name = "libcompizconfig-"+version;
 	builder = writeScript (name + "-builder")
-		(textClosure [doAutotools doConfigure doMakeInstall doForceShare]);
+		(textClosure localDefs [doAutotools doConfigure doMakeInstall doForceShare]);
 	meta = {
 		description = "
 	Compiz configuration backend library.
diff --git a/pkgs/applications/window-managers/compiz-fusion/libcompizconfig/default.nix b/pkgs/applications/window-managers/compiz-fusion/libcompizconfig/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz-fusion/libcompizconfig/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz-fusion/main/0.6.0.nix b/pkgs/applications/window-managers/compiz-fusion/main/0.6.0.nix
index 40261da5cc4..deb4b2e3a57 100644
--- a/pkgs/applications/window-managers/compiz-fusion/main/0.6.0.nix
+++ b/pkgs/applications/window-managers/compiz-fusion/main/0.6.0.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/0.6.0/compiz-fusion-plugins-main-0.6.0.tar.bz2;
@@ -9,6 +9,7 @@ args : with args;
 		[bcop libjpeg gettext];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 let
 	sharePlugins = FullDepEntry ("
 		ensureDir \$out/share/compiz-plugins
@@ -18,7 +19,7 @@ in
 stdenv.mkDerivation rec {
 	name = "compiz-fusion-plugins-main-"+version;
 	builder = writeScript (name + "-builder")
-		(textClosure [doConfigure doMakeInstall sharePlugins doForceShare]);
+		(textClosure localDefs [doConfigure doMakeInstall sharePlugins doForceShare]);
 	meta = {
 		description = "
 	Main Compiz Fusion plugins.
diff --git a/pkgs/applications/window-managers/compiz-fusion/main/default.nix b/pkgs/applications/window-managers/compiz-fusion/main/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz-fusion/main/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz/0.6.2.nix b/pkgs/applications/window-managers/compiz/0.6.2.nix
index 92f67ba6877..8827b3cb7a0 100644
--- a/pkgs/applications/window-managers/compiz/0.6.2.nix
+++ b/pkgs/applications/window-managers/compiz/0.6.2.nix
@@ -1,12 +1,12 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://releases.compiz-fusion.org/compiz/0.6.2/compiz-0.6.2.tar.bz2;
 		sha256 = "0k58bkbyqx94ch7scvn3d26296ai9nddfb6lg8v3bhbi2zj4i2n5";
 	};
 		buildInputs = [
-			    pkgconfig libXrender xextproto gtk libwnck GConf libgnome 
+			    pkgconfig gtk libwnck GConf libgnome 
 			    libgnomeui metacity gnomegtk glib pango libglade libgtkhtml 
 			    gtkhtml libgnomecanvas libgnomeprint libgnomeprintui gnomepanel 
 			    librsvg fuse 
@@ -14,13 +14,15 @@ args : with args;
 		  propagatedBuildInputs = [
 		    libpng libXcomposite libXfixes libXdamage libXrandr libXinerama
 		    libICE libSM startupnotification mesa GConf perl perlXMLParser libxslt
-		    dbus dbus_glib 
+		    dbus.libs dbus_glib compositeproto fixesproto damageproto randrproto
+		    xineramaproto renderproto kbproto xextproto libXrender 
 		  ];
 		configureFlags = ["--enable-gtk" "--enable-fuse" 
 			"--enable-annotate" "--enable-librsvg"] ++ 
 			(if args ? extraConfigureFlags then args.extraConfigureFlags else []);
 		patches = [ ./glx-patch-0.6.2.patch ];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 let
 	postAll = FullDepEntry ("
     for i in $out/bin/*; do
@@ -35,7 +37,9 @@ stdenv.mkDerivation
 rec {
 	name = "compiz-0.6.2";
 	builder = writeScript (name + "-builder")
-		(textClosure [doPatch doConfigure doMakeInstall doForceShare postAll]);
+		(textClosure localDefs [doPatch doConfigure doMakeInstall doPropagate 
+			doForceShare postAll]);
+	inherit propagatedBuildInputs;
 	meta = {
 		description = "
 	Compiz window manager
diff --git a/pkgs/applications/window-managers/compiz/default.nix b/pkgs/applications/window-managers/compiz/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/applications/window-managers/compiz/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/applications/window-managers/compiz/extra.nix b/pkgs/applications/window-managers/compiz/extra.nix
index 501518d3f67..70f4e5dd8c3 100644
--- a/pkgs/applications/window-managers/compiz/extra.nix
+++ b/pkgs/applications/window-managers/compiz/extra.nix
@@ -8,7 +8,7 @@ stdenv.mkDerivation {
     sha256 = "7fc7faafccfdf22dea7ac1de6629dcb55ec63d84fcb57a14559309cf284fa94f";
   };
   buildInputs = [
-    pkgconfig compiz perl perlXMLParser GConf dbus gtk
+    pkgconfig compiz perl perlXMLParser GConf dbus.libs gtk
   ];
   preBuild = "
     makeFlagsArray=(moduledir=$out/lib/compiz)
diff --git a/pkgs/applications/window-managers/fbpanel/4.12.nix b/pkgs/applications/window-managers/fbpanel/4.12.nix
new file mode 100644
index 00000000000..1958ffa642b
--- /dev/null
+++ b/pkgs/applications/window-managers/fbpanel/4.12.nix
@@ -0,0 +1,23 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+	fetchurl {
+		url = http://garr.dl.sourceforge.net/sourceforge/fbpanel/fbpanel-4.12.tgz;
+		sha256 = "0zv0zkq6w4h7dk0ji8bm9cqpj2qxv3ss161mqg9y68shvxvmfrlz";
+	};
+
+		buildInputs = [libX11 gtk pkgconfig libXmu libXpm 
+		  libpng libjpeg libtiff librsvg];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "fbpanel";
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	Just a desktop panel.	
+";
+	};
+}
diff --git a/pkgs/applications/window-managers/xmonad/default.nix b/pkgs/applications/window-managers/xmonad/default.nix
new file mode 100644
index 00000000000..ccd2dc05adb
--- /dev/null
+++ b/pkgs/applications/window-managers/xmonad/default.nix
@@ -0,0 +1,42 @@
+{stdenv, fetchurl, ghc, X11, xmessage}:
+
+stdenv.mkDerivation (rec {
+
+  pname = "xmonad";
+  version = "0.5";
+
+  name = "${pname}-${version}";
+
+  src = fetchurl {
+    url = "http://hackage.haskell.org/packages/archive/${pname}/${version}/${name}.tar.gz";
+    sha256 = "cfcc4501b000fa740ed35a5be87dc01216e036219551630dcf71d9c3cf57e4c4";
+  };
+
+  buildInputs = [ghc X11];
+
+  meta = {
+    description = "xmonad is a tiling window manager for X";
+  };
+
+  configurePhase = '' 
+    sed -i 's|"xmessage"|"${xmessage}/bin/xmessage"|' XMonad/Core.hs
+    ghc --make Setup.lhs
+    ./Setup configure --prefix="$out"
+  '';
+
+  buildPhase = ''
+    ./Setup build
+  '';
+
+  installPhase = ''
+    ./Setup copy
+    ./Setup register --gen-script
+    mkdir $out/nix-support
+    sed -i 's/|.*\(ghc-pkg update\)/| \1/' register.sh
+    cp register.sh $out/nix-support/register-ghclib.sh
+    sed -i 's/\(ghc-pkg update\)/\1 --user/' register.sh
+    mkdir -p $out/bin
+    cp register.sh $out/bin/register-ghclib-${name}.sh
+  '';
+
+})
diff --git a/pkgs/build-support/fetchcvs/builder.sh b/pkgs/build-support/fetchcvs/builder.sh
index 16aad96116d..be3e9e46355 100644
--- a/pkgs/build-support/fetchcvs/builder.sh
+++ b/pkgs/build-support/fetchcvs/builder.sh
@@ -1,8 +1,5 @@
 source $stdenv/setup
 
-if test -z "$tag"; then
-  tag="-DNOW"
-fi
 # creating the export drictory and checking out there only to be able to
 # move the content without the root directory into $out ...
 # cvs -f -d "$url" export $tag -d "$out" "$module"
@@ -10,6 +7,16 @@ fi
 # See als man Page for those options
 
 ensureDir $out export
+set -x
+if [ -n "$tag" ]; then
+  tag="-r $tag"
+else
+  if [ -n "$date" ]; then
+    tag="-D $date"
+  else
+    tag="-D NOW"
+  fi
+fi
 cd export; cvs -f -d "$url" export $tag "$module"
 mv */* $out
 
diff --git a/pkgs/build-support/fetchcvs/default.nix b/pkgs/build-support/fetchcvs/default.nix
index 6cd31ddaade..60463ec5644 100644
--- a/pkgs/build-support/fetchcvs/default.nix
+++ b/pkgs/build-support/fetchcvs/default.nix
@@ -1,13 +1,13 @@
 # example tags:
-# "-DNOW" (get current version)
-# "-D2007-20-10" (get the last version before given date)
-# "-r <tagname>" (get version by tag name)
-{stdenv, cvs, nix}: {url, module, tag, sha256}:
+# date="2007-20-10"; (get the last version before given date)
+# tag="<tagname>" (get version by tag name)
+# If you don't specify neither one date="NOW" will be used (get latest)
+
+{stdenv, cvs, nix}: {url, module, tag ? null, date ? null, sha256}:
 
 stdenv.mkDerivation {
   name = "cvs-export";
   builder = ./builder.sh;
   buildInputs = [cvs nix];
-
-  inherit url module tag sha256;
+  inherit url module sha256 tag date;
 }
diff --git a/pkgs/build-support/fetchsvn/builder.sh b/pkgs/build-support/fetchsvn/builder.sh
index d06efa88e29..b53ce95579a 100644
--- a/pkgs/build-support/fetchsvn/builder.sh
+++ b/pkgs/build-support/fetchsvn/builder.sh
@@ -12,7 +12,7 @@ fi
 # hash of the output matters.
 echo 'p' | svn export -r "$rev" "$url" $out
 
-actual=$(nix-hash $out)
+actual=$(nix-hash $out --type "$outputHashAlgo")
 if test "$actual" != "$outputHash"; then
     echo "hash is $actual, expected $outputHash" >&2
     exit 1
diff --git a/pkgs/build-support/fetchsvn/default.nix b/pkgs/build-support/fetchsvn/default.nix
index ff842b0ee24..ce6a1e61d9c 100644
--- a/pkgs/build-support/fetchsvn/default.nix
+++ b/pkgs/build-support/fetchsvn/default.nix
@@ -1,4 +1,5 @@
-{stdenv, subversion, nix, sshSupport ? false, openssh ? null}: {url, rev ? "HEAD", md5}:
+{stdenv, subversion, nix, sshSupport ? false, openssh ? null}: 
+{url, rev ? "HEAD", md5 ? "", sha256 ? ""}:
 
 stdenv.mkDerivation {
   name = "svn-export";
@@ -6,11 +7,11 @@ stdenv.mkDerivation {
   buildInputs = [subversion nix];
 
   # Nix <= 0.7 compatibility.
-  id = md5;
+  /*id = if sha256 == "" then md5 else sha256;*/
 
-  outputHashAlgo = "md5";
+  outputHashAlgo = if sha256=="" then "md5" else "sha256";
   outputHashMode = "recursive";
-  outputHash = md5;
+  outputHash = if sha256 =="" then md5 else sha256;
   
   inherit url rev sshSupport openssh;
 }
diff --git a/pkgs/build-support/fetchurl/mirrors.nix b/pkgs/build-support/fetchurl/mirrors.nix
index 2fc8ce4eec2..d245b1ac3f8 100644
--- a/pkgs/build-support/fetchurl/mirrors.nix
+++ b/pkgs/build-support/fetchurl/mirrors.nix
@@ -42,4 +42,66 @@ rec {
     ftp://ftp.heanet.ie/mirrors/ftp.kde.org/
     ftp://ftp.kde.org/pub/kde/
   ];
+
+  # Gentoo files.
+  gentoo = [
+    http://www.ibiblio.org/pub/Linux/distributions/gentoo/
+    http://distfiles.gentoo.org/
+  ];
+
+  savannah = [
+    ftp://ftp.twaren.net/Unix/NonGNU/
+    ftp://mirror.csclub.uwaterloo.ca/nongnu/
+    ftp://mirror.publicns.net/pub/nongnu/
+    ftp://savannah.c3sl.ufpr.br/
+    http://download.savannah.gnu.org/
+    http://ftp.cc.uoc.gr/mirrors/nongnu.org/
+    http://ftp.twaren.net/Unix/NonGNU/
+    http://mirror.csclub.uwaterloo.ca/nongnu/
+    http://mirror.publicns.net/pub/nongnu/
+    http://nongnu.askapache.com/
+    http://nongnu.bigsearcher.com/
+    http://savannah.c3sl.ufpr.br/
+    http://www.centervenus.com/mirrors/nongnu/
+    http://www.de-mirrors.de/nongnu/
+    http://www.very-clever.com/download/nongnu/
+    http://www.wikifusion.info/nongnu/
+  ];
+
+  # BitlBee mirrors, see http://www.bitlbee.org/main.php/mirrors.html .
+  bitlbee = [
+    http://get.bitlbee.org/
+    http://get.bitlbee.be/
+    http://get.us.bitlbee.org/
+    http://ftp.snt.utwente.nl/pub/software/bitlbee/
+    http://bitlbee.intergenia.de/
+  ];
+
+  # ImageMagick mirrors, see http://www.imagemagick.org/script/download.php .
+  imagemagick = [
+    ftp://gd.tuwien.ac.at/pub/graphics/ImageMagick/
+    ftp://ftp.carnet.hr/pub/misc/imagemagick/
+    ftp://ftp.fu-berlin.de/unix/X11/graphics/ImageMagick
+    http://imagemagick.linux-mirror.org/download
+    http://image_magick.veidrodis.com/image_magick/
+    http://imagemagick.oss-mirror.org/download
+    ftp://ftp.kddlabs.co.jp/graphics/ImageMagick/
+    ftp://ftp.u-aizu.ac.jp/pub/graphics/image/ImageMagick/imagemagick.org
+    ftp://zoffy.asahi-net.or.jp/pub/graphics/ImageMagick
+    ftp://ftp.nluug.nl/pub/ImageMagick
+    http://ftp.surfnet.nl/pub/ImageMagick/
+    ftp://sunsite.icm.edu.pl/packages/ImageMagick/
+    ftp://ftp.chg.ru/packages/ImageMagick
+    http://ftp.chg.ru/packages/ImageMagick
+    http://ftp.efair.ru/pub/software/graphics/ImageMagick/
+    ftp://ftp.efair.ru/pub/software/graphics/ImageMagick/
+    ftp://ftp.sunet.se/pub/multimedia/graphics/ImageMagick
+    http://www.smudge-it.co.uk/pub/imagemagick/
+    ftp://www.rx-host.net/pub/graphics/ImageMagick
+    ftp://ftp.fifi.org/pub/ImageMagick/
+    ftp://ftp.imagemagick.org/pub/ImageMagick
+    ftp://ftp.imagemagick.net/pub/ImageMagick
+    http://imagemagick.site2nd.org/imagemagick
+  ];
+
 }
diff --git a/pkgs/build-support/gcc-wrapper/builder.sh b/pkgs/build-support/gcc-wrapper/builder.sh
index f9dbc0e784f..7a2f9c20f27 100644
--- a/pkgs/build-support/gcc-wrapper/builder.sh
+++ b/pkgs/build-support/gcc-wrapper/builder.sh
@@ -50,14 +50,17 @@ fi
 doSubstitute() {
     local src=$1
     local dst=$2
-    substitute "$src" "$dst" \
-        --subst-var "out" \
-        --subst-var "shell" \
-        --subst-var "gcc" \
-        --subst-var "gccProg" \
-        --subst-var "binutils" \
-        --subst-var "libc" \
-        --subst-var-by "ld" "$ldPath/ld"
+    # Can't use substitute() here, because replace may not have been
+    # built yet (in the bootstrap).
+    sed \
+        -e "s^@out@^$out^g" \
+        -e "s^@shell@^$shell^g" \
+        -e "s^@gcc@^$gcc^g" \
+        -e "s^@gccProg@^$gccProg^g" \
+        -e "s^@binutils@^$binutils^g" \
+        -e "s^@libc@^$libc^g" \
+        -e "s^@ld@^$ldPath/ld^g" \
+        < "$src" > "$dst" 
 }
 
 
@@ -108,3 +111,11 @@ doSubstitute "$addFlags" "$out/nix-support/add-flags.sh"
 doSubstitute "$setupHook" "$out/nix-support/setup-hook"
 
 cp -p $utils $out/nix-support/utils.sh
+
+
+# Propagate the wrapped gcc so that if you install the wrapper, you get
+# tools like gcov, the manpages, etc. as well (including for binutils
+# and Glibc).
+if test -z "$nativeTools"; then
+    echo $gcc $binutils $libc > $out/nix-support/propagated-user-env-packages
+fi
diff --git a/pkgs/build-support/make-wrapper/make-wrapper.sh b/pkgs/build-support/make-wrapper/make-wrapper.sh
index 847db8910fd..558ff94c1a0 100644
--- a/pkgs/build-support/make-wrapper/make-wrapper.sh
+++ b/pkgs/build-support/make-wrapper/make-wrapper.sh
@@ -1,6 +1,7 @@
 makeWrapper() {
-    original=$1
-    wrapper=$2
+    local original=$1
+    local wrapper=$2
+    local params varName value command separator n fileNames
 
     ensureDir "$(dirname $wrapper)"
 
@@ -17,6 +18,12 @@ makeWrapper() {
             echo "export $varName=$value" >> $wrapper
         fi
 
+        if test "$p" = "--run"; then
+            command=${params[$((n + 1))]}
+            n=$((n + 1))
+            echo "$command" >> $wrapper
+        fi
+
         if test "$p" = "--suffix" -o "$p" = "--prefix"; then
             varName=${params[$((n + 1))]}
             separator=${params[$((n + 2))]}
@@ -72,3 +79,11 @@ filterExisting() {
         fi
     done
 }
+
+# Syntax: wrapProgram <PROGRAM> <MAKE-WRAPPER FLAGS...>
+wrapProgram() {
+    local prog="$1"
+    local hidden="$(dirname "$prog")/.wrapped-$(basename "$prog")"
+    mv $prog $hidden
+    makeWrapper $hidden $prog "$@"
+}
diff --git a/pkgs/build-support/substitute/substitute-all.sh b/pkgs/build-support/substitute/substitute-all.sh
index 3d3999ad520..796a1a47152 100644
--- a/pkgs/build-support/substitute/substitute-all.sh
+++ b/pkgs/build-support/substitute/substitute-all.sh
@@ -1,5 +1,7 @@
 source $stdenv/setup
 
+eval "$preInstall"
+
 args=
 
 target=$out
@@ -13,3 +15,5 @@ substituteAll $src $target
 if test -n "$isExecutable"; then
     chmod +x $target
 fi
+
+eval "$postInstall"
diff --git a/pkgs/data/documentation/man-pages/default.nix b/pkgs/data/documentation/man-pages/default.nix
index 6a553b86e29..6adf9034474 100644
--- a/pkgs/data/documentation/man-pages/default.nix
+++ b/pkgs/data/documentation/man-pages/default.nix
@@ -1,14 +1,19 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "man-pages-2.43";
+  name = "man-pages-2.74";
   
   src = fetchurl {
-    url = ftp://ftp.win.tue.nl/pub/linux-local/manpages/man-pages-2.43.tar.gz;
-    sha256 = "01dibzkssaq0ssq61adhmri29ws9jbhbn2yxmjvb3gg8q7gjah9w";
+    url = ftp://ftp.win.tue.nl/pub/linux-local/manpages/man-pages-2.74.tar.gz;
+    sha256 = "1k6hf6va29gnf2c9kpwd6w555gp1vimf73ac2ij2j7dqx64hy7s7";
   };
 
   preBuild = "
     makeFlagsArray=(MANDIR=$out/share/man)
   ";
+
+  meta = {
+    description = "Linux development manual pages";
+    homepage = ftp://ftp.win.tue.nl/pub/linux-local/manpages/;
+  };
 }
diff --git a/pkgs/data/fonts/fontWrap/default.nix b/pkgs/data/fonts/fontWrap/default.nix
new file mode 100644
index 00000000000..8bc120c686a
--- /dev/null
+++ b/pkgs/data/fonts/fontWrap/default.nix
@@ -0,0 +1,28 @@
+args : with args;
+	let localDefs = builderDefs {
+		src =""; /* put a fetchurl here */
+		buildInputs = [mkfontdir mkfontscale];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let
+	doInstall = FullDepEntry ("
+		ensureDir \$out/share/fonts/
+		cd \$out/share/fonts
+		for i in ${toString paths}; do
+			find \$i -type f -exec ln -s '{}' . ';' ;
+		done
+		mkfontdir 
+		mkfontscale
+	") [minInit addInputs defEnsureDir] ;
+in
+stdenv.mkDerivation rec {
+	name = "wrapped-font-dir";
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [ doInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Just a wrapper to create fonts.dir and fonts.scale .
+";
+	};
+}
diff --git a/pkgs/data/fonts/freefont-ttf/default.nix b/pkgs/data/fonts/freefont-ttf/default.nix
index 19e1a21450d..e1f8c74ae62 100644
--- a/pkgs/data/fonts/freefont-ttf/default.nix
+++ b/pkgs/data/fonts/freefont-ttf/default.nix
@@ -6,6 +6,8 @@ stdenv.mkDerivation {
     url = http://download.savannah.gnu.org/releases/freefont/freefont-ttf-20060126.tar.gz;
     md5 = "822aba4e2ed065d9d3ded6e26e495854";
   };
-  buildPhase = "true";
-  installPhase = "ensureDir $out/share/fonts/truetype; cp *.ttf $out/share/fonts/truetype";
-}
\ No newline at end of file
+  installPhase = ''
+    ensureDir $out/share/fonts/truetype
+    cp *.ttf $out/share/fonts/truetype
+  '';
+}
diff --git a/pkgs/data/misc/shared-mime-info/0.22.nix b/pkgs/data/misc/shared-mime-info/0.22.nix
new file mode 100644
index 00000000000..399b3296d38
--- /dev/null
+++ b/pkgs/data/misc/shared-mime-info/0.22.nix
@@ -0,0 +1,2 @@
+args:
+import ./common.nix "1chz63v9jr009z9jhs07klybmhyf58i8vxipigf5gkdabjiclcyr" args
diff --git a/pkgs/data/misc/shared-mime-info/0.23.nix b/pkgs/data/misc/shared-mime-info/0.23.nix
new file mode 100644
index 00000000000..38617dfe8e3
--- /dev/null
+++ b/pkgs/data/misc/shared-mime-info/0.23.nix
@@ -0,0 +1,2 @@
+args:
+import ./common.nix "080ny2vy00202hxcm7xm72j1zmyfs15dbsnqipwni6b2dg2am3q3" args
diff --git a/pkgs/data/misc/shared-mime-info/common.nix b/pkgs/data/misc/shared-mime-info/common.nix
new file mode 100644
index 00000000000..8c2ff363c6a
--- /dev/null
+++ b/pkgs/data/misc/shared-mime-info/common.nix
@@ -0,0 +1,16 @@
+hash: args: with args;
+
+stdenv.mkDerivation rec {
+  name = "shared-mime-info-" + version;
+
+  src = fetchurl {
+    url = "http://freedesktop.org/~hadess/${name}.tar.bz2";
+    sha256 = hash;
+  };
+
+  buildInputs = [perl perlXMLParser pkgconfig gettext libxml2 glib];
+
+  meta = {
+    homepage = http://freedesktop.org/wiki/Software/shared-mime-info;
+  };
+}
diff --git a/pkgs/data/misc/shared-mime-info/default.nix b/pkgs/data/misc/shared-mime-info/default.nix
deleted file mode 100644
index 0b82782d31d..00000000000
--- a/pkgs/data/misc/shared-mime-info/default.nix
+++ /dev/null
@@ -1,12 +0,0 @@
-{stdenv, fetchurl, perl, perlXMLParser, pkgconfig, gettext, libxml2, glib}:
-
-stdenv.mkDerivation {
-  name = "shared-mime-info-0.22";
-
-  src = fetchurl {
-	url = http://freedesktop.org/~hadess/shared-mime-info-0.22.tar.bz2;
-    sha256 = "1chz63v9jr009z9jhs07klybmhyf58i8vxipigf5gkdabjiclcyr";
-  };
-
-  buildInputs = [perl perlXMLParser pkgconfig gettext libxml2 glib];
-}
diff --git a/pkgs/data/misc/xkeyboard-config/0.9.nix b/pkgs/data/misc/xkeyboard-config/0.9.nix
new file mode 100644
index 00000000000..c7c92cd6c27
--- /dev/null
+++ b/pkgs/data/misc/xkeyboard-config/0.9.nix
@@ -0,0 +1,23 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "xkeyboard-config-0.9";
+
+  src = fetchurl {
+    url = http://xlibs.freedesktop.org/xkbdesc/xkeyboard-config-0.9.tar.bz2;
+    sha256 = "0zbpprhlv8ggsvgnwqw8d4cx0ry86szm36ghigwb1sn46q0c915v";
+  };
+
+  buildInputs = [perl perlXMLParser xkbcomp];
+
+  ICONV = "iconv";
+
+  preConfigure = "
+    configureFlags=\"--with-xkb-base=$out/etc/X11/xkb -with-xkb-rules-symlink=xorg,xfree86\"
+  ";
+
+  postInstall = ''
+  	rm ''${out}/etc/X11/xkb/compiled
+	cat ${./level3-deadkeys-us-intl} >> $out/etc/X11/xkb/symbols/us
+  '';
+}
diff --git a/pkgs/data/misc/xkeyboard-config/1.2.nix b/pkgs/data/misc/xkeyboard-config/1.2.nix
new file mode 100644
index 00000000000..de67b00baea
--- /dev/null
+++ b/pkgs/data/misc/xkeyboard-config/1.2.nix
@@ -0,0 +1,22 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "xkeyboard-config-${version}";
+
+  src = fetchurl {
+          url = http://xlibs.freedesktop.org/xkbdesc/xkeyboard-config-1.2.tar.bz2;
+          sha256 = "1xr7vfgabgyggnkjb56a0bd39yxjhyrldcdsq9pqnw3izfb6i1b4";
+        };
+  buildInputs = [perl perlXMLParser xkbcomp gettext];
+
+  ICONV = "iconv";
+
+  preConfigure = "
+    configureFlags=\"--with-xkb-base=$out/etc/X11/xkb -with-xkb-rules-symlink=xorg,xfree86\"
+  ";
+
+  postInstall = ''
+  	rm ''${out}/etc/X11/xkb/compiled || true;
+	cat ${./level3-deadkeys-us-intl} | sed -e 's/altgr-intl/altgr-intl-rich/g' >> $out/etc/X11/xkb/symbols/us
+  '';
+}
diff --git a/pkgs/data/misc/xkeyboard-config/default.nix b/pkgs/data/misc/xkeyboard-config/default.nix
index 9eae78b0700..31836d24ecf 100644
--- a/pkgs/data/misc/xkeyboard-config/default.nix
+++ b/pkgs/data/misc/xkeyboard-config/default.nix
@@ -16,5 +16,8 @@ stdenv.mkDerivation {
     configureFlags=\"--with-xkb-base=$out/etc/X11/xkb -with-xkb-rules-symlink=xorg,xfree86\"
   ";
 
-  postInstall = "rm \${out}/etc/X11/xkb/compiled";
+  postInstall = ''
+  	rm ''${out}/etc/X11/xkb/compiled
+	cat ${./level3-deadkeys-us-intl} >> $out/etc/X11/xkb/symbols/us
+  '';
 }
diff --git a/pkgs/data/misc/xkeyboard-config/level3-deadkeys-us-intl b/pkgs/data/misc/xkeyboard-config/level3-deadkeys-us-intl
new file mode 100644
index 00000000000..91d21f76143
--- /dev/null
+++ b/pkgs/data/misc/xkeyboard-config/level3-deadkeys-us-intl
@@ -0,0 +1,95 @@
+
+// Grabbed from http://lists.freedesktop.org/archives/xorg/2007-July/026686.html
+// Submitted there by Adriaan van Nijendaal, he says he submitted it to X.org
+// for inclusion, so it should be OK to use it as if it were part of X.org
+
+// The keyboard section in the X-server config file
+// (/etc/X11/xorg.conf on my system) looks like this:
+//
+// Section "InputDevice"
+//   Driver	"kbd"
+//   Identifier	"Keyboard[0]"
+//   Option	"XkbModel"	"pc101"
+//   Option	"XkbLayout"	"us"
+//   Option	"XkbVariant"	"altgr-intl"
+// EndSection
+//
+// To be effective, you need to install this file, change the X config
+// file and restart the X-server. Or, alternatively, you can do this
+// run-time:
+//
+// setxkbmap -v -rules xorg -model pc101 -layout us -variant altgr-intl
+//
+// Once the X-server has loaded the new config, a keyboard can be
+// displayed with: (if you change "-ll 1" into "-ll 2", you'll see
+// the special keys ONLY.)
+//
+//   xkbcomp -o /tmp/keyboard.xkm -opt cgkst -xkb $DISPLAY
+//   xkbprint -o /tmp/keyboard.xkm.ps -kc -nkg 2 -ntg 4 -lg 1 -ll 1 \
+//	-lc en_US.iso885915 -level2 -mono -label symbols -w 3 $DISPLAY;
+//   gv -seascape /tmp/keyboard.xkm.ps
+//   rm -f /tmp/keyboard.xkm.ps /tmp/keyboard.xkm
+//
+
+partial alphanumeric_keys
+xkb_symbols "altgr-intl" {
+
+    name[Group1]= "U.S. English - International (AltGr dead keys)";
+
+    include "us(basic)"
+
+    key <TLDE> { [    grave,	asciitilde,	dead_grave,	dead_tilde	] };
+    key <AE01> { [	  1,	exclam,		onesuperior,	exclamdown	] };
+    key <AE02> { [	  2,	at,		twosuperior,	dead_doubleacute] };
+    key <AE03> { [	  3,	numbersign,	threesuperior,	dead_macron	] };
+    key <AE04> { [	  4,	dollar,		currency,	sterling	] };
+    key <AE05> { [	  5,	percent,		EuroSign		] };
+    key <AE06> { [	  6,	asciicircum,	dead_circumflex, dead_stroke	] };
+    key <AE07> { [	  7,	ampersand,		dead_horn		] };
+    key <AE08> { [	  8,	asterisk,		dead_ogonek		] };
+    key <AE09> { [	  9,	parenleft,  leftsinglequotemark,dead_breve	] };
+    key <AE10> { [	  0,	parenright,rightsinglequotemark,dead_abovering	] };
+    key <AE11> { [    minus,	underscore,	yen,		dead_belowdot	] };
+    key <AE12> { [    equal,	plus,		multiply,	division	] };
+
+    key <AD01> { [	  q,	Q,		adiaeresis,	Adiaeresis	] };
+    key <AD02> { [	  w,	W,		aring,		Aring		] };
+    key <AD03> { [	  e,	E,		eacute,		Eacute		] };
+    key <AD04> { [	  r,	R,		ediaeresis,	Ediaeresis	] };
+    key <AD05> { [	  t,	T,		thorn,		THORN		] };
+    key <AD06> { [	  y,	Y,		udiaeresis,	Udiaeresis	] };
+    key <AD07> { [	  u,	U,		uacute,		Uacute		] };
+    key <AD08> { [	  i,	I,		iacute,		Iacute		] };
+    key <AD09> { [	  o,	O,		oacute,		Oacute		] };
+    key <AD10> { [	  p,	P,		odiaeresis,	Odiaeresis	] };
+    key <AD11> { [ bracketleft,	braceleft,		guillemotleft		] };
+    key <AD12> { [ bracketright,braceright,		guillemotright		] };
+
+    key <AC01> { [	  a,	A,		aacute,		Aacute		] };
+    key <AC02> { [	  s,	S,		ssharp,		section		] };
+    key <AC03> { [	  d,	D,		eth,		ETH		] };
+    key <AC04> { [	  f,	F						] };
+    key <AC05> { [	  g,	G						] };
+    key <AC06> { [	  h,	H						] };
+    key <AC07> { [	  j,	J,		idiaeresis,	Idiaeresis	] };
+    key <AC08> { [	  k,	K						] };
+    key <AC09> { [	  l,	L,		oslash,		Ooblique	] };
+    key <AC10> { [semicolon,	colon,		paragraph,	degree		] };
+    key <AC11> { [apostrophe,	quotedbl,	dead_acute,	dead_diaeresis	] };
+
+    key <AB01> { [	  z,	Z,		ae,		AE		] };
+    key <AB02> { [	  x,	X,		oe,		OE		] };
+    key <AB03> { [	  c,	C,		copyright,	cent		] };
+    key <AB04> { [	  v,	V,		registered,	registered	] };
+    key <AB05> { [	  b,	B						] };
+    key <AB06> { [	  n,	N,		ntilde,		Ntilde		] };
+    key <AB07> { [	  m,	M,		mu,		mu		] };
+    key <AB08> { [    comma,	less,		ccedilla,	Ccedilla	] };
+    key <AB09> { [   period,	greater,	dead_abovedot,	dead_caron	] };
+    key <AB10> { [    slash,	question,	questiondown,	dead_hook	] };
+    key <BKSL> { [backslash,	bar,		notsign,	brokenbar	] };
+
+    // Let's have free choice
+    //include "level3(ralt_switch)"
+};
+
diff --git a/pkgs/desktops/gnome/default.nix b/pkgs/desktops/gnome/default.nix
index 6410e9c053a..014a99b674a 100644
--- a/pkgs/desktops/gnome/default.nix
+++ b/pkgs/desktops/gnome/default.nix
@@ -1,12 +1,6 @@
 # todo audiofile is also part of the gnome platform. Move it to this collection?
 
-{ stdenv, fetchurl, pkgconfig, audiofile
-, flex, bison, popt, perl, zlib, libxml2, libxslt
-, perlXMLParser, docbook_xml_dtd_42, docbook_xml_dtd_412
-, gettext, x11, libtiff, libjpeg
-, libpng, gtkLibs, xlibs, bzip2, libcm, python, dbus_glib, ncurses
-, which, libxml2Python, iconnamingutils
-}:
+args: with args;
 
 assert dbus_glib.glib == gtkLibs.glib;
 
@@ -57,7 +51,7 @@ rec {
 
   gnomevfs = import ./gnome-vfs.nix {
     inherit fetchurl stdenv gnome pkgconfig perl libxml2 popt
-      perlXMLParser gettext bzip2 dbus_glib;
+      perlXMLParser gettext bzip2 dbus_glib openssl hal samba fam;
     input = platform.gnomevfs;
   };
 
@@ -153,7 +147,7 @@ rec {
   };
 
   gtksourceview = import ./gtksourceview.nix {
-    inherit fetchurl stdenv pkgconfig perl perlXMLParser gtk libxml2
+    inherit fetchurl stdenv pkgconfig perl perlXMLParser gtk libxml2 gettext
             libgnomeprint gnomevfs libbonobo /* !!! <- should be propagated in gnomevfs */
             GConf /* idem */ libgnomeprintui libgnomecanvas /* !!! through printui */;
     input = desktop.gtksourceview;
@@ -210,7 +204,7 @@ rec {
 
   gnomedocutils = import ./gnome-doc-utils.nix {
     inherit stdenv fetchurl pkgconfig perl perlXMLParser python
-      libxml2 libxslt gettext;
+      libxml2 libxslt gettext libxml2Python;
     input = desktop.gnomedocutils;
   };
 
diff --git a/pkgs/desktops/gnome/gnome-doc-utils.nix b/pkgs/desktops/gnome/gnome-doc-utils.nix
index f1650d9650a..8a77d96475f 100644
--- a/pkgs/desktops/gnome/gnome-doc-utils.nix
+++ b/pkgs/desktops/gnome/gnome-doc-utils.nix
@@ -1,7 +1,4 @@
-{ input, stdenv, fetchurl, pkgconfig, perl, perlXMLParser, python
-, libxml2, libxslt, gettext
-}:
-
+args: with args;
 # !!! xml2po needs to store the path to libxml2
 
 stdenv.mkDerivation {
@@ -9,8 +6,18 @@ stdenv.mkDerivation {
   
   buildInputs = [
     pkgconfig perl perlXMLParser python
-    libxml2 libxslt gettext
+    libxml2 libxslt gettext python libxml2Python
   ];
 
   configureFlags = "--disable-scrollkeeper";
+
+  postInstall = "
+    mv \$out/bin/xml2po \$out/bin/.xml2po.orig
+    pythonPathLibXml2=\"\$(toPythonPath ${libxml2Python})\"
+    echo -e '#! ${stdenv.shell}\nPYTHONPATH=$PYTHONPATH:'\"\$( toPythonPath \$out  )"+
+    ":\${pythonPathLibXml2//python2.5/python2.4}"+
+    ":\$( toPythonPath ${libxml2Python} )\""+
+    "' \$(dirname \$0)/.xml2po.orig \"\$@\"' > \$out/bin/xml2po;
+    chmod a+x \$out/bin/xml2po
+  ";
 }
diff --git a/pkgs/desktops/gnome/gnome-vfs.nix b/pkgs/desktops/gnome/gnome-vfs.nix
index b374ad4d94d..24b99fb3b83 100644
--- a/pkgs/desktops/gnome/gnome-vfs.nix
+++ b/pkgs/desktops/gnome/gnome-vfs.nix
@@ -1,14 +1,11 @@
-{ input, stdenv, fetchurl, gnome, pkgconfig, perl, libxml2
-, popt, perlXMLParser, gettext, bzip2, dbus_glib
-}:
+args: with args;
 
 stdenv.mkDerivation {
   inherit (input) name src;
   buildInputs = [
     pkgconfig perl gnome.glib libxml2 gnome.GConf gnome.libbonobo
     gnome.gnomemimedata popt perlXMLParser gettext bzip2
-    dbus_glib
+    dbus_glib hal openssl samba fam
   ];
   patches = [./no-kerberos.patch];
-  configureFlags = "--disable-hal";
 }
diff --git a/pkgs/desktops/gnome/gtksourceview.nix b/pkgs/desktops/gnome/gtksourceview.nix
index 8ad7955e8d4..8afafac8cf4 100644
--- a/pkgs/desktops/gnome/gtksourceview.nix
+++ b/pkgs/desktops/gnome/gtksourceview.nix
@@ -1,6 +1,7 @@
 { input, stdenv, fetchurl, perl, perlXMLParser, pkgconfig
 , gtk, libxml2, libgnomeprint, gnomevfs, libbonobo, GConf
 , libgnomeprintui, libgnomecanvas
+, gettext
 }:
 
 stdenv.mkDerivation {
@@ -8,6 +9,7 @@ stdenv.mkDerivation {
   buildInputs = [
     perl perlXMLParser pkgconfig gnomevfs
     libbonobo GConf libgnomeprintui libgnomecanvas
+    gettext
   ];
   propagatedBuildInputs = [gtk libxml2 libgnomeprint];
 }
diff --git a/pkgs/desktops/kde-4/kdebase/builder.sh b/pkgs/desktops/kde-4/base/builder.sh
index 41cff761b36..99b357fcf16 100755
--- a/pkgs/desktops/kde-4/kdebase/builder.sh
+++ b/pkgs/desktops/kde-4/base/builder.sh
@@ -1,21 +1,12 @@
 source ${stdenv}/setup
 
-myPreBuild()
-{
-	for i in ${qt}/include/*; do
-		NIX_CFLAGS_COMPILE="-I$i ${NIX_CFLAGS_COMPILE}"
-	done;
-	echo "${NIX_CFLAGS_COMPILE}"
-}
-preBuild=myPreBuild
-
 myPatchPhase()
 {
 	echo "Fixing dbus calls in CMakeLists.txt files"
 # Trailing slash in sed is essential
 	find .. -name CMakeLists.txt \
 	| xargs sed -e "s@\${DBUS_INTERFACES_INSTALL_DIR}/@${kdelibs}/share/dbus-1/interfaces/@" -i
-	sed -e '/^#define HAS_RANDR_1_2 1$/d' -i ../workspace/kcontrol/randr/randr.h
+	#sed -e '/^#define HAS_RANDR_1_2 1$/d' -i ../workspace/kcontrol/randr/randr.h
 }
 patchPhase=myPatchPhase
 genericBuild
diff --git a/pkgs/desktops/kde-4/base/default.nix b/pkgs/desktops/kde-4/base/default.nix
new file mode 100644
index 00000000000..451dd4863c3
--- /dev/null
+++ b/pkgs/desktops/kde-4/base/default.nix
@@ -0,0 +1,14 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdebase-4.0.0";
+  #builder = ./builder.sh;
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdebase-4.0.0.tar.bz2;
+    md5 = "01d8f2f16cbd4e225efc996b0dd39769";
+  };
+
+  propagatedBuildInputs = [kdepimlibs libusb];
+  inherit kdelibs;
+}
diff --git a/pkgs/desktops/kde-4/decibel/default.nix b/pkgs/desktops/kde-4/decibel/default.nix
new file mode 100644
index 00000000000..ff98b48ee6f
--- /dev/null
+++ b/pkgs/desktops/kde-4/decibel/default.nix
@@ -0,0 +1,11 @@
+args: with args;
+stdenv.mkDerivation {
+	name = "decibel-0.5.0";
+
+	src = fetchurl {
+		url = http://decibel.kde.org/fileadmin/downloads/decibel/releases/decibel-0.5.0.tar.gz;
+		sha256 = "07visasid4mpzm0ba5j9qy0lxxb6451lvbr2gnc1vzfvjagffqz4";
+	};
+
+	buildInputs = [kdelibs kdebase ];
+}
diff --git a/pkgs/desktops/kde-4/default.nix b/pkgs/desktops/kde-4/default.nix
new file mode 100644
index 00000000000..9732d9e2b2b
--- /dev/null
+++ b/pkgs/desktops/kde-4/default.nix
@@ -0,0 +1,35 @@
+args:
+rec {
+  fullargs = args // { kdelibs = libs; kdepimlibs = pimlibs; kdebase = base; kderuntime = runtime; };
+  libs = import ./libs (args // { kdesupport = support; });
+  pimlibs = import ./pimlibs (args // { kdelibs = libs; });
+  graphics = import ./graphics (fullargs // { kdeworkspace = workspace; } );
+  multimedia = import ./multimedia (fullargs // { kdeworkspace = workspace; } );
+  toys = import ./toys (fullargs // { kdeworkspace = workspace; } );
+  network = import ./network (fullargs // { kdeworkspace = workspace; } );
+  utils = import ./utils (fullargs // { kdeworkspace = workspace; } );
+  games = import ./games (fullargs // { kdeworkspace = workspace; } );
+  edu = import ./edu (fullargs // { kdeworkspace = workspace; } );
+  base = import ./base fullargs;
+  runtime = import ./runtime fullargs;
+  workspace = import ./workspace fullargs;
+  extragear_plasma = import ./extragear (fullargs // { kdeworkspace = workspace; });
+  support = import ./support args;
+  decibel = import ./decibel fullargs;
+  pim = import ./pim (fullargs // {kdeworkspace = workspace; });
+
+  env = with args; runCommand "kde-env"
+  {
+	  KDEDIRS = lib.concatStringsSep ":" ([ libs pimlibs graphics multimedia
+	  toys network utils games edu base runtime workspace extragear_plasma pim] ++
+	  support.all);
+	  scriptName = "echo-kde-dirs";
+  }
+  "
+  ensureDir \${out}/bin
+  scriptPath=\${out}/bin/\${scriptName}
+  echo \"#!/bin/sh\" > \${scriptPath}
+  echo \"echo -n export KDEDIRS=\${KDEDIRS}\" >> \${scriptPath}
+  chmod +x \${scriptPath}
+  ";
+}
diff --git a/pkgs/desktops/kde-4/edu/default.nix b/pkgs/desktops/kde-4/edu/default.nix
new file mode 100644
index 00000000000..0cf140a5de9
--- /dev/null
+++ b/pkgs/desktops/kde-4/edu/default.nix
@@ -0,0 +1,20 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "kdeedu-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdeedu-4.0.0.tar.bz2;
+    md5 = "73924e158e4a2de2107be441c808251f";
+  };
+
+  buildInputs = [kdelibs kdepimlibs kdeworkspace boost readline openbabel ocaml
+  libusb facile python];
+  myCmakeFiles = ./myCmakeFiles;
+  patchPhase = "
+  cp ${myCmakeFiles}/* ../cmake/modules
+  sed -e 's@+facile@\${LIBFACILE_INCLUDE_DIR}@' -i \\
+  ../kalzium/src/CMakeOCamlInstructions.cmake
+  ";
+  configureFlags = "--debug-trycompile";
+}
diff --git a/pkgs/desktops/kde-4/edu/myCmakeFiles/CheckBoostAndPythonCompatible.cmake b/pkgs/desktops/kde-4/edu/myCmakeFiles/CheckBoostAndPythonCompatible.cmake
new file mode 100644
index 00000000000..35701ecf5c6
--- /dev/null
+++ b/pkgs/desktops/kde-4/edu/myCmakeFiles/CheckBoostAndPythonCompatible.cmake
@@ -0,0 +1,38 @@
+include(CheckCXXSourceCompiles)
+include(CheckIncludeFileCXX)
+include(CheckLibraryExists)
+
+MACRO(check_boost_and_python_compatible
+	_bo_inc _bo_ld _bo_py_lib
+	_py_inc _py_ld _py_lib)
+
+	set(_save_CXX_FLAGS ${CMAKE_CXX_FLAGS})
+	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${KDE4_ENABLE_EXCEPTIONS}")
+
+	set(CMAKE_REQUIRED_FLAGS "-L${_bo_ld} -L${_py_ld}")
+	set(CMAKE_REQUIRED_INCLUDES ${_py_inc} ${_bo_inc})
+	set(CMAKE_REQUIRED_LIBRARIES ${_bo_py_lib} ${_py_lib})
+
+	check_cxx_source_compiles("
+#include <boost/python.hpp>
+const char* greet() { return \"Hello world!\"; }
+BOOST_PYTHON_MODULE(hello) { boost::python::def(\"greet\", greet); }
+
+int main() { return 0; }
+
+// some vars, in case of the compilation fail...
+// python include dir: ${_py_inc}
+// python lib: ${_py_lib}
+// 
+// boost python lib: ${_bo_py_lib}
+// boost include dir: ${_bo_inc}
+// boost lib dir: ${_bo_ld}
+// 
+"
+BOOST_PYTHON_${_bo_inc}_${_bo_ld}_${_bo_py_lib}_${_py_inc}_${_py_ld}_${_py_lib}_COMPATIBLE )
+
+	set(CMAKE_REQUIRED_FLAGS)
+	set(CMAKE_REQUIRED_INCLUDES)
+	set(CMAKE_REQUIRED_LIBRARIES)
+	set(CMAKE_CXX_FLAGS ${_save_CXX_FLAGS})
+ENDMACRO(check_boost_and_python_compatible)
diff --git a/pkgs/desktops/kde-4/edu/myCmakeFiles/FindBoostPython.cmake b/pkgs/desktops/kde-4/edu/myCmakeFiles/FindBoostPython.cmake
new file mode 100644
index 00000000000..b68959d8a9c
--- /dev/null
+++ b/pkgs/desktops/kde-4/edu/myCmakeFiles/FindBoostPython.cmake
@@ -0,0 +1,90 @@
+# - Try to find the a valid boost+python combination
+# Once done this will define
+#
+#  Boost_PYTHON_FOUND - system has a valid boost+python combination
+#  BOOST_PYTHON_INCLUDES - the include directory for boost+python
+#  BOOST_PYTHON_LIBS - the needed libs for boost+python
+
+# Copyright (c) 2006, Pino Toscano, <toscano.pino@tiscali.it>
+#
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+
+if(BOOST_PYTHON_INCLUDES AND BOOST_PYTHON_LIBS)
+	# Already in cache, be silent
+	set(Boost_PYTHON_FIND_QUIETLY TRUE)
+endif(BOOST_PYTHON_INCLUDES AND BOOST_PYTHON_LIBS)
+
+SET(Boost_PYTHON_LIB_SUFFIXES "-mt" "-gcc-mt")
+SET(Boost_KNOWN_VERSIONS "-1_34_1" "-1_34_0" "-1_33_1" "-1_33_0")
+
+FIND_PACKAGE(Boost)
+INCLUDE(PythonLibsUtils)
+INCLUDE(CheckBoostAndPythonCompatible)
+
+IF(Boost_FOUND AND Boost_LIBRARY_DIRS)
+
+	SET(Boost_PYTHON_LIB_NAMES boost_python)
+	FOREACH(_suffix ${Boost_PYTHON_LIB_SUFFIXES})
+		set(Boost_PYTHON_LIB_NAMES ${Boost_PYTHON_LIB_NAMES}
+			boost_python${_suffix})
+		FOREACH(_bo_ver ${Boost_KNOWN_VERSIONS})
+			set(Boost_PYTHON_LIB_NAMES ${Boost_PYTHON_LIB_NAMES}
+				boost_python${_suffix}${_bo_ver})
+		ENDFOREACH(_bo_ver)
+	ENDFOREACH(_suffix)
+
+	SET(_found FALSE)
+	FOREACH(_boost_python_lib ${Boost_PYTHON_LIB_NAMES})
+		IF(NOT _found)
+			FIND_LIBRARY(Boost_PYTHON_LIB_FULLPATH
+				NAME ${_boost_python_lib}
+				PATHS ${Boost_LIBRARY_DIRS}
+				NO_DEFAULT_PATH
+				)
+			IF(Boost_PYTHON_LIB_FULLPATH)
+				SET(Boost_PYTHON_LIB ${_boost_python_lib})
+				SET(_found TRUE)
+			ENDIF(Boost_PYTHON_LIB_FULLPATH)
+		ENDIF(NOT _found)
+	ENDFOREACH(_boost_python_lib)
+
+	IF(Boost_PYTHON_LIB)
+		SET(_found FALSE)
+		FOREACH(_py_ver ${PYTHON_KNOWN_VERSIONS})
+			if (NOT _found)
+				python_find_version(${_py_ver} _py_inc _py_ld _py_lib)
+				IF(PYTHON_REQ_VERSION_FOUND)
+					MESSAGE(STATUS " ${Boost_INCLUDE_DIRS} ${Boost_LIBRARY_DIRS} ${Boost_PYTHON_LIB} ${_py_inc} ${_py_ld} ${_py_lib}")
+					check_boost_and_python_compatible(
+						"${Boost_INCLUDE_DIRS}" "${Boost_LIBRARY_DIRS}"
+						"${Boost_PYTHON_LIB}" "${_py_inc}" "${_py_ld}"
+						"${_py_lib}")
+					SET(_found
+						BOOST_PYTHON_${Boost_INCLUDE_DIRS}_${Boost_LIBRARY_DIRS}_${Boost_PYTHON_LIB}_${_py_inc}_${_py_ld}_${_py_lib}_COMPATIBLE)
+
+					IF(BOOST_PYTHON_${Boost_INCLUDE_DIRS}_${Boost_LIBRARY_DIRS}_${Boost_PYTHON_LIB}_${_py_inc}_${_py_ld}_${_py_lib}_COMPATIBLE)
+						SET(BOOST_PYTHON_INCLUDES ${Boost_INCLUDE_DIRS} ${_py_inc})
+						SET(BOOST_PYTHON_LIBS "-l${_py_lib} -L${_py_ld} -l${Boost_PYTHON_LIB}")
+						SET(BOOST_PYTHON_FOUND TRUE)
+						SET(_found TRUE)
+					ENDIF(BOOST_PYTHON_${Boost_INCLUDE_DIRS}_${Boost_LIBRARY_DIRS}_${Boost_PYTHON_LIB}_${_py_inc}_${_py_ld}_${_py_lib}_COMPATIBLE)
+				ENDIF(PYTHON_REQ_VERSION_FOUND)
+			ENDIF(NOT _found)
+		ENDFOREACH(_py_ver)
+	ENDIF(Boost_PYTHON_LIB)
+ENDIF(Boost_FOUND AND Boost_LIBRARY_DIRS)
+
+if(BOOST_PYTHON_FOUND)
+	if(NOT BoostPython_FIND_QUIETLY)
+		message(STATUS "Found Boost+Python: ${BOOST_PYTHON_INCLUDES} ${BOOST_PYTHON_LIBS}")
+	endif(NOT BoostPython_FIND_QUIETLY)
+	set(KIG_ENABLE_PYTHON_SCRIPTING 1)
+else (BOOST_PYTHON_FOUND)
+	if (BoostPython_FIND_REQUIRED)
+		message(FATAL_ERROR "Could NOT find Boost+Python")
+	endif(BoostPython_FIND_REQUIRED)
+	set(KIG_ENABLE_PYTHON_SCRIPTING 0)
+endif(BOOST_PYTHON_FOUND)
+
+mark_as_advanced(BOOST_PYTHON_INCLUDES BOOST_PYTHON_LIBS)
diff --git a/pkgs/desktops/kde-4/edu/myCmakeFiles/FindLibfacile.cmake b/pkgs/desktops/kde-4/edu/myCmakeFiles/FindLibfacile.cmake
new file mode 100644
index 00000000000..154531dabc1
--- /dev/null
+++ b/pkgs/desktops/kde-4/edu/myCmakeFiles/FindLibfacile.cmake
@@ -0,0 +1,45 @@
+# - Try to find Libfacile
+# Once done this will define
+#
+#  LIBFACILE_FOUND - system has Libfacile
+#  LIBFACILE_INCLUDE_DIR - the Libfacile include directory
+#  LIBFACILE_LIBRARIES - Link these to use Libfacile
+#  LIBFACILE_DEFINITIONS - Compiler switches required for using Libfacile
+#
+# Copyright (c) 2006, Carsten Niehaus, <cniehaus@gmx.de>
+# Copyright (c) 2006, Montel Laurent, <montel@kde.org>
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+
+
+find_package(OCaml)
+
+set(LIBFACILE_FOUND FALSE)
+
+if( OCAML_FOUND )
+   find_file(LIBFACILE_LIBRARIES NAME facile.a
+       PATHS ${OCAMLC_DIR} ENV CMAKE_LIBRARY_PATH
+	   PATH_SUFFIXES facile ocaml/facile
+   )
+   message(STATUS "LIBFACILE_LIBRARIES :<${LIBFACILE_LIBRARIES}>") 
+   if (LIBFACILE_LIBRARIES)
+	   get_filename_component(LIBFACILE_INCLUDE_DIR ${LIBFACILE_LIBRARIES} PATH)
+	   message(STATUS "LIBFACILE_INCLUDE_DIR <${LIBFACILE_INCLUDE_DIR}>")
+       set(LIBFACILE_FOUND TRUE)
+   endif(LIBFACILE_LIBRARIES)
+endif(OCAML_FOUND)
+
+
+if(LIBFACILE_FOUND)
+   if(NOT Libfacile_FIND_QUIETLY)
+      message(STATUS "Found Libfacile: ${LIBFACILE_LIBRARIES}")
+   endif(NOT Libfacile_FIND_QUIETLY)
+else(LIBFACILE_FOUND)
+   if(Libfacile_FIND_REQUIRED)
+      message(FATAL_ERROR "Could not find Libfacile")
+   endif(Libfacile_FIND_REQUIRED)
+endif(LIBFACILE_FOUND)
+
+# show the LIBFACILE_INCLUDE_DIR and LIBFACILE_LIBRARIES variables only in the advanced view
+mark_as_advanced(LIBFACILE_INCLUDE_DIR LIBFACILE_LIBRARIES )
+ 
diff --git a/pkgs/desktops/kde-4/edu/myCmakeFiles/PythonLibsUtils.cmake b/pkgs/desktops/kde-4/edu/myCmakeFiles/PythonLibsUtils.cmake
new file mode 100644
index 00000000000..df54324712a
--- /dev/null
+++ b/pkgs/desktops/kde-4/edu/myCmakeFiles/PythonLibsUtils.cmake
@@ -0,0 +1,46 @@
+SET(PYTHON_KNOWN_VERSIONS "2.5" "2.4" "2.3" "2.2" "2.1" "2.0" "1.6" "1.5")
+
+MACRO(python_find_version _py_ver _py_inc _py_ld _py_lib)
+	STRING(REPLACE "." "" _py_ver_nd "${_py_ver}")
+
+	SET(PY_INSTALL_PATH
+		[HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_py_ver}\\InstallPath])
+
+	SET(_py_libnames "python${_py_ver}" "python${_py_ver_nd}")
+
+	SET(_py_found FALSE)
+	FOREACH(_py_libname ${_py_libnames})
+		IF (NOT _py_found)
+			SET(_py_lib_full _py_lib_full-NOTFOUND)
+
+			FIND_LIBRARY(_py_lib_full
+				NAMES "${_py_libname}"
+				PATHS "${PY_INSTALL_PATH}/libs"
+				NO_SYSTEM_ENVIRONMENT_PATH
+			)
+			FIND_LIBRARY(_py_lib_full
+				NAMES "${_py_libname}"
+				PATHS "${PY_INSTALL_PATH}/libs"
+				PATH_SUFFIXES "python${_py_ver}/config"
+				NO_SYSTEM_ENVIRONMENT_PATH
+			)
+			IF(_py_lib_full)
+				SET(_py_lib "${_py_libname}")
+				GET_FILENAME_COMPONENT(_py_ld "${_py_lib_full}" PATH)
+				SET(_py_found TRUE)
+			ENDIF(_py_lib_full)
+		ENDIF(NOT _py_found)
+	ENDFOREACH(_py_libname)
+
+	IF(_py_found)
+		FIND_PATH(_py_inc
+			NAMES Python.h
+			PATHS
+				${PY_INSTALL_PATH}/include
+			PATH_SUFFIXES
+				"python${_py_ver}"
+		)
+	ENDIF(_py_found)
+
+	SET(PYTHON_REQ_VERSION_FOUND ${_py_found})
+ENDMACRO(python_find_version)
diff --git a/pkgs/desktops/kde-4/extragear/default.nix b/pkgs/desktops/kde-4/extragear/default.nix
new file mode 100644
index 00000000000..c67d4b8682c
--- /dev/null
+++ b/pkgs/desktops/kde-4/extragear/default.nix
@@ -0,0 +1,14 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "extragear-plasma-4.0beta4";
+  
+  src = fetchurl {
+    url = mirror://kde/unstable/3.95/src/extragear-plasma-3.95.0.tar.bz2;
+    sha256 = "1nzfy34ig66gfpgv6kbcmcap13axcy7kvj43srbd0ic6a0giv283";
+  };
+
+  buildInputs = [ kdeworkspace kdebase ];
+  patchPhase = "
+  sed -e 's@<Plasma@<KDE/Plasma@' -i ../applets/*/*.h";
+}
diff --git a/pkgs/desktops/kde-4/games/default.nix b/pkgs/desktops/kde-4/games/default.nix
new file mode 100644
index 00000000000..8f3b6c0ec48
--- /dev/null
+++ b/pkgs/desktops/kde-4/games/default.nix
@@ -0,0 +1,12 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdegames-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdegames-4.0.0.tar.bz2;
+    md5 = "6264c0034f6389a2807a4e1723ba1c81";
+  };
+
+  buildInputs = [kdelibs kdepimlibs kdeworkspace];
+}
diff --git a/pkgs/desktops/kde-4/graphics/default.nix b/pkgs/desktops/kde-4/graphics/default.nix
new file mode 100644
index 00000000000..6ab84fd8eff
--- /dev/null
+++ b/pkgs/desktops/kde-4/graphics/default.nix
@@ -0,0 +1,13 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdegraphics-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdegraphics-4.0.0.tar.bz2;
+    md5 = "6cad7b165d99c43d1a19a0350598821c";
+  };
+
+  buildInputs = [kdelibs kdepimlibs kdeworkspace libgphoto2 saneBackends
+  djvulibre exiv2 poppler chmlib];
+}
diff --git a/pkgs/desktops/kde-4/kdebase/default.nix b/pkgs/desktops/kde-4/kdebase/default.nix
deleted file mode 100644
index ebc0ba3cab3..00000000000
--- a/pkgs/desktops/kde-4/kdebase/default.nix
+++ /dev/null
@@ -1,55 +0,0 @@
-{ stdenv, fetchurl
-, inputproto, kbproto, scrnsaverproto, xextproto, xf86miscproto
-, xf86vidmodeproto, xineramaproto, xproto
-, libICE
-, libX11
-, libXau
-, libXcomposite
-, libXcursor
-, libXdamage
-, libXdmcp
-, libXext
-, libXfixes
-, libXft
-, libXi
-, libXinerama
-, libXpm
-, libXrandr
-, libXrender
-, libXScrnSaver
-, libXt
-, libXtst
-, libXv
-, libXxf86misc
-, libxkbfile
-, zlib, perl, qt, openssl, pcre
-, pkgconfig, libjpeg, libpng, libtiff, libxml2, libxslt, libtool, expat
-, freetype, bzip2, strigi, cmake, shared_mime_info, alsaLib, libungif
-, libusb, glib, mesa
-, cups, kdelibs, kdepimlibs
-}:
-
-stdenv.mkDerivation {
-  name = "kdebase-4.0beta1";
-  builder = ./builder.sh;
-  
-  src = fetchurl {
-    url = mirror://kde/unstable/3.92/src/kdebase-3.92.0.tar.bz2;
-    sha256 = "1xh5a93l6anmix358fll4xfqm5fl4hpm1ksmlab8hr8s7vqng707";
-  };
-
-  buildInputs = [
-	inputproto kbproto scrnsaverproto xextproto xf86miscproto xf86vidmodeproto
-	xineramaproto xproto libICE libX11 libXau libXcomposite libXcursor
-	libXdamage libXdmcp libXext libXfixes libXft libXi libXpm libXrandr
-	libXinerama mesa stdenv.gcc.libc
-	libXrender libXScrnSaver libXt libXtst libXv libXxf86misc libxkbfile
-    zlib perl qt openssl pcre 
-    pkgconfig libjpeg libpng libtiff libxml2 libxslt expat
-    libtool freetype bzip2 strigi cmake shared_mime_info alsaLib libungif cups
-	kdelibs kdepimlibs libusb glib
-  ];
-# TODO : it should be done through setup-hooks
-  KDEDIRS="${kdelibs}/share/apps:${kdepimlibs}/share/apps";
-  inherit qt kdelibs;
-}
diff --git a/pkgs/desktops/kde-4/kdelibs/default.nix b/pkgs/desktops/kde-4/kdelibs/default.nix
deleted file mode 100644
index 9d59da00088..00000000000
--- a/pkgs/desktops/kde-4/kdelibs/default.nix
+++ /dev/null
@@ -1,48 +0,0 @@
-{ stdenv, fetchurl
-, inputproto, kbproto, scrnsaverproto, xextproto, xf86miscproto
-, xf86vidmodeproto, xineramaproto, xproto
-, libICE
-, libX11
-, libXau
-, libXcomposite
-, libXcursor
-, libXdamage
-, libXdmcp
-, libXext
-, libXfixes
-, libXft
-, libXi
-, libXpm
-, libXrandr
-, libXrender
-, libXScrnSaver
-, libXt
-, libXtst
-, libXv
-, libXxf86misc
-, libxkbfile
-, zlib, perl, qt, openssl, pcre
-, pkgconfig, libjpeg, libpng, libtiff, libxml2, libxslt, libtool, expat
-, freetype, bzip2, strigi, cmake, shared_mime_info, alsaLib, libungif
-, cups
-}:
-
-stdenv.mkDerivation {
-  name = "kdelibs-4.0beta1";
-  
-  src = fetchurl {
-    url = mirror://kde/unstable/3.92/src/kdelibs-3.92.0.tar.bz2;
-    sha256 = "19jd9nx5g0ayxavj3ys52wx5ppxw9yr9jylxk7qplxsm525ryf1p";
-  };
-
-  buildInputs = [
-	inputproto kbproto scrnsaverproto xextproto xf86miscproto xf86vidmodeproto
-	xineramaproto xproto libICE libX11 libXau libXcomposite libXcursor
-	libXdamage libXdmcp libXext libXfixes libXft libXi libXpm libXrandr
-	libXrender libXScrnSaver libXt libXtst libXv libXxf86misc libxkbfile
-    zlib perl qt openssl pcre 
-    pkgconfig libjpeg libpng libtiff libxml2 libxslt expat
-    libtool freetype bzip2 strigi cmake shared_mime_info alsaLib libungif cups
-  ];
-  patchPhase = "sed -e 's@ NO_SYSTEM_PATH@@g' -i ../cmake/modules/FindX11.cmake";
-}
diff --git a/pkgs/desktops/kde-4/kdepim/builder.sh b/pkgs/desktops/kde-4/kdepim/builder.sh
deleted file mode 100755
index 73d0e9febcd..00000000000
--- a/pkgs/desktops/kde-4/kdepim/builder.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-source ${stdenv}/setup
-
-myPreBuild()
-{
-	for i in ${qt}/include/*; do
-		NIX_CFLAGS_COMPILE="-I$i ${NIX_CFLAGS_COMPILE}"
-	done;
-	echo "${NIX_CFLAGS_COMPILE}"
-}
-preBuild=myPreBuild
-
-myPatchPhase()
-{
-	sed -e '3s/)/ ${CMAKE_MODULE_PATH})/' -i ../CMakeLists.txt
-}
-patchPhase=myPatchPhase
-
-genericBuild
diff --git a/pkgs/desktops/kde-4/kdepim/default.nix b/pkgs/desktops/kde-4/kdepim/default.nix
deleted file mode 100644
index dd1e706bf74..00000000000
--- a/pkgs/desktops/kde-4/kdepim/default.nix
+++ /dev/null
@@ -1,55 +0,0 @@
-{ stdenv, fetchurl
-, inputproto, kbproto, scrnsaverproto, xextproto, xf86miscproto
-, xf86vidmodeproto, xineramaproto, xproto
-, libICE
-, libX11
-, libXau
-, libXcomposite
-, libXcursor
-, libXdamage
-, libXdmcp
-, libXext
-, libXfixes
-, libXft
-, libXi
-, libXinerama
-, libXpm
-, libXrandr
-, libXrender
-, libXScrnSaver
-, libXt
-, libXtst
-, libXv
-, libXxf86misc
-, libxkbfile
-, zlib, perl, qt, openssl, pcre
-, pkgconfig, libjpeg, libpng, libtiff, libxml2, libxslt, libtool, expat
-, freetype, bzip2, strigi, cmake, shared_mime_info, alsaLib, libungif
-, libusb, glib, mesa, gpgme, boost
-, cups, kdelibs, kdepimlibs
-}:
-
-stdenv.mkDerivation {
-  name = "kdepim-4.0beta1";
-  builder = ./builder.sh;
-  
-  src = fetchurl {
-    url = mirror://kde/unstable/3.92/src/kdepim-3.92.0.tar.bz2;
-    sha256 = "1wlq1h7j07f24n1mjnv9wbfsxn2vn24qfn5dgn4j4fsl84qha16i";
-  };
-
-  buildInputs = [
-	inputproto kbproto scrnsaverproto xextproto xf86miscproto xf86vidmodeproto
-	xineramaproto xproto libICE libX11 libXau libXcomposite libXcursor
-	libXdamage libXdmcp libXext libXfixes libXft libXi libXpm libXrandr
-	libXinerama mesa stdenv.gcc.libc
-	libXrender libXScrnSaver libXt libXtst libXv libXxf86misc libxkbfile
-    zlib perl qt openssl pcre 
-    pkgconfig libjpeg libpng libtiff libxml2 libxslt expat
-    libtool freetype bzip2 strigi cmake shared_mime_info alsaLib libungif cups
-	kdelibs kdepimlibs libusb glib gpgme boost
-  ];
-# TODO : it should be done through setup-hooks
-  KDEDIRS="${kdelibs}/share/apps:${kdepimlibs}/share/apps";
-  inherit qt kdelibs;
-}
diff --git a/pkgs/desktops/kde-4/kdepimlibs/default.nix b/pkgs/desktops/kde-4/kdepimlibs/default.nix
deleted file mode 100644
index 44c6728b5e3..00000000000
--- a/pkgs/desktops/kde-4/kdepimlibs/default.nix
+++ /dev/null
@@ -1,48 +0,0 @@
-{ stdenv, fetchurl
-, inputproto, kbproto, scrnsaverproto, xextproto, xf86miscproto
-, xf86vidmodeproto, xineramaproto, xproto
-, libICE
-, libX11
-, libXau
-, libXcomposite
-, libXcursor
-, libXdamage
-, libXdmcp
-, libXext
-, libXfixes
-, libXft
-, libXi
-, libXpm
-, libXrandr
-, libXrender
-, libXScrnSaver
-, libXt
-, libXtst
-, libXv
-, libXxf86misc
-, libxkbfile
-, zlib, perl, qt, openssl, pcre
-, pkgconfig, libjpeg, libpng, libtiff, libxml2, libxslt, libtool, expat
-, freetype, bzip2, strigi, cmake, shared_mime_info, alsaLib, libungif
-, cups, kdelibs, boost, gpgme
-}:
-
-stdenv.mkDerivation {
-  name = "kdepimlibs-4.0beta1";
-  
-  src = fetchurl {
-    url = mirror://kde/unstable/3.92/src/kdepimlibs-3.92.0.tar.bz2;
-    sha256 = "0q7zzj8n282xaxvdij74fb17w5c1vja7izxfrkcbq7arn9f40wbx";
-  };
-
-  buildInputs = [
-	inputproto kbproto scrnsaverproto xextproto xf86miscproto xf86vidmodeproto
-	xineramaproto xproto libICE libX11 libXau libXcomposite libXcursor
-	libXdamage libXdmcp libXext libXfixes libXft libXi libXpm libXrandr
-	libXrender libXScrnSaver libXt libXtst libXv libXxf86misc libxkbfile
-    zlib perl qt openssl pcre 
-    pkgconfig libjpeg libpng libtiff libxml2 libxslt expat
-    libtool freetype bzip2 strigi cmake shared_mime_info alsaLib libungif cups
-	kdelibs boost gpgme
-  ];
-}
diff --git a/pkgs/desktops/kde-4/libs/FindIlmBase.cmake b/pkgs/desktops/kde-4/libs/FindIlmBase.cmake
new file mode 100644
index 00000000000..1511e9509ce
--- /dev/null
+++ b/pkgs/desktops/kde-4/libs/FindIlmBase.cmake
@@ -0,0 +1,74 @@
+# Try to find the IlmBase libraries
+# This check defines:
+#
+#  ILMBASE_FOUND - system has IlmBase
+#  ILMBASE_INCLUDE_DIR - IlmBase include directory
+#  ILMBASE_LIBRARIES - Libraries needed to use IlmBase
+#
+# Copyright (c) 2006, Alexander Neundorf, <neundorf@kde.org>
+# Copyright (c) 2007, Yury G. Kudryashov, <urkud.urkud@gmail.com>
+#
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+
+if (ILMBASE_INCLUDE_DIR AND ILMBASE_LIBRARIES)
+  # in cache already
+  SET(ILMBASE_FOUND TRUE)
+
+else (ILMBASE_INCLUDE_DIR AND ILMBASE_LIBRARIES)
+IF (NOT WIN32)
+  # use pkg-config to get the directories and then use these values
+  # in the FIND_PATH() and FIND_LIBRARY() calls
+  INCLUDE(UsePkgConfig)
+  
+  PKGCONFIG(IlmBase _IlmBaseIncDir _IlmBaseLinkDir _IlmBaseLinkFlags _IlmBaseCflags)
+ENDIF (NOT WIN32)  
+  FIND_PATH(ILMBASE_INCLUDE_DIR ImathBox.h
+     ${_IlmBaseIncDir}
+     ${_IlmBaseIncDir}/OpenEXR/
+  )
+
+  FIND_LIBRARY(ILMBASE_HALF_LIBRARY NAMES Half
+    PATHS
+    ${_IlmBaseLinkDir}
+    NO_DEFAULT_PATH
+  )
+  FIND_LIBRARY(ILMBASE_HALF_LIBRARY NAMES Half )
+  
+  FIND_LIBRARY(ILMBASE_IEX_LIBRARY NAMES Iex
+    PATHS
+    ${_IlmBaseLinkDir}
+    NO_DEFAULT_PATH
+  )
+  FIND_LIBRARY(ILMBASE_IEX_LIBRARY NAMES Iex )
+  
+  FIND_LIBRARY(ILMBASE_IMATH_LIBRARY NAMES Imath
+    PATHS
+    ${_IlmBaseLinkDir}
+    NO_DEFAULT_PATH
+  )
+  FIND_LIBRARY(ILMBASE_IMATH_LIBRARY NAMES Imath )  
+  
+  if (ILMBASE_INCLUDE_DIR AND ILMBASE_IMATH_LIBRARY AND ILMBASE_IEX_LIBRARY AND ILMBASE_HALF_LIBRARY)
+     set(ILMBASE_FOUND TRUE)
+     set(ILMBASE_LIBRARIES ${ILMBASE_IMATH_LIBRARY} ${ILMBASE_IEX_LIBRARY} ${ILMBASE_HALF_LIBRARY} CACHE STRING "The libraries needed to use IlmBase")
+  endif (ILMBASE_INCLUDE_DIR AND ILMBASE_IMATH_LIBRARY AND ILMBASE_IEX_LIBRARY AND ILMBASE_HALF_LIBRARY)
+  
+  if (ILMBASE_FOUND)
+    if (NOT IlmBase_FIND_QUIETLY)
+      message(STATUS "Found ILMBASE: ${ILMBASE_LIBRARIES}")
+    endif (NOT IlmBase_FIND_QUIETLY)
+  else (ILMBASE_FOUND)
+    if (IlmBase_FIND_REQUIRED)
+      message(FATAL_ERROR "Could NOT find ILMBASE")
+    endif (IlmBase_FIND_REQUIRED)
+  endif (ILMBASE_FOUND)
+  
+  MARK_AS_ADVANCED(
+     ILMBASE_INCLUDE_DIR 
+     ILMBASE_LIBRARIES 
+     ILMBASE_IMATH_LIBRARY 
+     ILMBASE_IEX_LIBRARY 
+     ILMBASE_HALF_LIBRARY )
+  
+endif (ILMBASE_INCLUDE_DIR AND ILMBASE_LIBRARIES)
diff --git a/pkgs/desktops/kde-4/libs/FindOpenEXR.cmake b/pkgs/desktops/kde-4/libs/FindOpenEXR.cmake
new file mode 100644
index 00000000000..b1f590544fa
--- /dev/null
+++ b/pkgs/desktops/kde-4/libs/FindOpenEXR.cmake
@@ -0,0 +1,68 @@
+# Try to find the OpenEXR libraries
+# This check defines:
+#
+#  OPENEXR_FOUND - system has OpenEXR
+#  OPENEXR_INCLUDE_DIR - OpenEXR include directory
+#  OPENEXR_LIBRARIES - Libraries needed to use OpenEXR
+#
+# Copyright (c) 2006, Alexander Neundorf, <neundorf@kde.org>
+# Copyright (c) 2007, Yury G. Kudryashov, <urkud.urkud@gmail.com>
+#
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+
+
+if (OPENEXR_INCLUDE_DIR AND OPENEXR_LIBRARIES)
+  # in cache already
+  SET(OPENEXR_FOUND TRUE)
+
+else (OPENEXR_INCLUDE_DIR AND OPENEXR_LIBRARIES)
+FIND_PACKAGE(IlmBase)
+IF (NOT ILMBASE_FOUND)
+	SET(OPENEXR_FOUND FALSE)
+ELSE (NOT ILMBASE_FOUND)
+IF (NOT WIN32)
+  # use pkg-config to get the directories and then use these values
+  # in the FIND_PATH() and FIND_LIBRARY() calls
+  INCLUDE(UsePkgConfig)
+  
+  PKGCONFIG(OpenEXR _OpenEXRIncDir _OpenEXRLinkDir _OpenEXRLinkFlags _OpenEXRCflags)
+ENDIF (NOT WIN32)  
+  FIND_PATH(OPENEXR_INCLUDE_DIR ImfRgbaFile.h
+     ${_OpenEXRIncDir}
+     ${_OpenEXRIncDir}/OpenEXR/
+  )
+
+  FIND_LIBRARY(OPENEXR_ILMIMF_LIBRARY NAMES IlmImf 
+    PATHS
+    ${_OpenEXRLinkDir}
+    NO_DEFAULT_PATH
+  )
+  FIND_LIBRARY(OPENEXR_ILMIMF_LIBRARY NAMES IlmImf )  
+  
+  if (OPENEXR_INCLUDE_DIR AND OPENEXR_ILMIMF_LIBRARY)
+     set(OPENEXR_FOUND TRUE)
+     set(OPENEXR_LIBRARIES ${ILMBASE_LIBRARIES} ${OPENEXR_ILMIMF_LIBRARY} CACHE STRING "The libraries needed to use OpenEXR")
+	 set(OPENEXR_INCLUDE_DIR ${OPENEXR_INCLUDE_DIR} ${ILMBASE_INCLUDE_DIR})
+  endif (OPENEXR_INCLUDE_DIR AND OPENEXR_ILMIMF_LIBRARY)
+ENDIF (NOT ILMBASE_FOUND)
+  
+  if (OPENEXR_FOUND)
+    if (NOT OpenEXR_FIND_QUIETLY)
+      message(STATUS "Found OPENEXR: ${OPENEXR_LIBRARIES}")
+    endif (NOT OpenEXR_FIND_QUIETLY)
+  else (OPENEXR_FOUND)
+    if (OpenEXR_FIND_REQUIRED)
+      message(FATAL_ERROR "Could NOT find OPENEXR")
+    endif (OpenEXR_FIND_REQUIRED)
+  endif (OPENEXR_FOUND)
+  
+  MARK_AS_ADVANCED(
+     OPENEXR_INCLUDE_DIR 
+     OPENEXR_LIBRARIES 
+     OPENEXR_ILMIMF_LIBRARY 
+     OPENEXR_IMATH_LIBRARY 
+     OPENEXR_IEX_LIBRARY 
+     OPENEXR_HALF_LIBRARY )
+  
+endif (OPENEXR_INCLUDE_DIR AND OPENEXR_LIBRARIES)
diff --git a/pkgs/desktops/kde-4/libs/default.nix b/pkgs/desktops/kde-4/libs/default.nix
new file mode 100644
index 00000000000..91f722ec658
--- /dev/null
+++ b/pkgs/desktops/kde-4/libs/default.nix
@@ -0,0 +1,27 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "kdelibs-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdelibs-4.0.0.tar.bz2;
+    md5 = "79d0f83ca81fc4a135663943340c0b8f";
+  };
+
+  propagatedBuildInputs = [
+	cmake inputproto kbproto scrnsaverproto xextproto xf86miscproto xf86vidmodeproto
+	xineramaproto xproto libICE libX11 libXau libXcomposite libXcursor
+	libXdamage libXdmcp libXext libXfixes libXft libXi libXpm libXrandr
+	libXrender libXScrnSaver libXt libXtst libXv libXxf86misc libxkbfile zlib
+	perl qt openssl pcre pkgconfig libjpeg libpng libtiff libxml2 libxslt expat
+    libtool freetype bzip2 shared_mime_info alsaLib libungif cups
+	gettext enchant openexr aspell stdenv.gcc.libc
+  ] ++ kdesupport.all;
+  patchPhase = "cp ${findIlmBase} ../cmake/modules/FindIlmBase.cmake;
+  cp $findOpenEXR ../cmake/modules/FindOpenEXR.cmake;
+  sed -e 's@Soprano/DummyModel@Soprano/Util/DummyModel@' -i ../nepomuk/core/resourcemanager.cpp;";
+
+  findIlmBase = ./FindIlmBase.cmake;
+  findOpenEXR = ./FindOpenEXR.cmake;
+  setupHook=./setup.sh;
+}
diff --git a/pkgs/desktops/kde-4/libs/setup.sh b/pkgs/desktops/kde-4/libs/setup.sh
new file mode 100755
index 00000000000..6f899442d27
--- /dev/null
+++ b/pkgs/desktops/kde-4/libs/setup.sh
@@ -0,0 +1,5 @@
+addKDEDIRS()
+{
+	addToSearchPath KDEDIRS /share/kde4 /. $1
+}
+envHooks=(${envHooks[@]} addKDEDIRS)
diff --git a/pkgs/desktops/kde-4/multimedia/default.nix b/pkgs/desktops/kde-4/multimedia/default.nix
new file mode 100644
index 00000000000..f1f7994ce1a
--- /dev/null
+++ b/pkgs/desktops/kde-4/multimedia/default.nix
@@ -0,0 +1,13 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdemultimedia-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdemultimedia-4.0.0.tar.bz2;
+    md5 = "0bf1cd18a23017a37324d9f8c4902e19";
+  };
+
+  buildInputs = [kdelibs kdepimlibs kdeworkspace libogg flac cdparanoia lame
+  libvorbis];
+}
diff --git a/pkgs/desktops/kde-4/network/default.nix b/pkgs/desktops/kde-4/network/default.nix
new file mode 100644
index 00000000000..f99f2184bca
--- /dev/null
+++ b/pkgs/desktops/kde-4/network/default.nix
@@ -0,0 +1,12 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdenetwork-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdenetwork-4.0.0.tar.bz2;
+    md5 = "f362bd34b589800845abfb99589d4cfc";
+  };
+
+  buildInputs = [kdelibs kdepimlibs kdeworkspace sqlite libidn];
+}
diff --git a/pkgs/desktops/kde-4/pim/builder.sh b/pkgs/desktops/kde-4/pim/builder.sh
new file mode 100755
index 00000000000..8963fae048c
--- /dev/null
+++ b/pkgs/desktops/kde-4/pim/builder.sh
@@ -0,0 +1,10 @@
+source ${stdenv}/setup
+
+myPatchPhase()
+{
+# They reset CMAKE_MODULE_PATH, not adding to the existing
+	sed -e '3s/)/ ${CMAKE_MODULE_PATH})/' -i ../CMakeLists.txt
+}
+patchPhase=myPatchPhase
+
+genericBuild
diff --git a/pkgs/desktops/kde-4/pim/default.nix b/pkgs/desktops/kde-4/pim/default.nix
new file mode 100644
index 00000000000..f0f4184d391
--- /dev/null
+++ b/pkgs/desktops/kde-4/pim/default.nix
@@ -0,0 +1,15 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdepim-4.0beta4";
+  
+  src = fetchurl {
+    url = mirror://kde/unstable/3.95/src/kdepim-3.95.0.tar.bz2;
+    sha256 = "0gzvm4h6ij7i119apmh9w82raygahr18bl0i9m3ynf2mcca0aq94";
+  };
+
+  buildInputs = [libXinerama mesa stdenv.gcc.libc alsaLib kdelibs kdepimlibs
+  kdeworkspace libusb glib];
+  qt4BadIncludes = true;
+  inherit qt kdelibs;
+}
diff --git a/pkgs/desktops/kde-4/pimlibs/default.nix b/pkgs/desktops/kde-4/pimlibs/default.nix
new file mode 100644
index 00000000000..30c6ca6250b
--- /dev/null
+++ b/pkgs/desktops/kde-4/pimlibs/default.nix
@@ -0,0 +1,12 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdepimlibs-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdepimlibs-4.0.0.tar.bz2;
+    md5 = "1a68662230fcd4ec8cea90bb780f920e";
+  };
+
+  propagatedBuildInputs = [kdelibs boost gpgme cyrus_sasl openldap];
+}
diff --git a/pkgs/desktops/kde-4/runtime/builder.sh b/pkgs/desktops/kde-4/runtime/builder.sh
new file mode 100755
index 00000000000..99b357fcf16
--- /dev/null
+++ b/pkgs/desktops/kde-4/runtime/builder.sh
@@ -0,0 +1,12 @@
+source ${stdenv}/setup
+
+myPatchPhase()
+{
+	echo "Fixing dbus calls in CMakeLists.txt files"
+# Trailing slash in sed is essential
+	find .. -name CMakeLists.txt \
+	| xargs sed -e "s@\${DBUS_INTERFACES_INSTALL_DIR}/@${kdelibs}/share/dbus-1/interfaces/@" -i
+	#sed -e '/^#define HAS_RANDR_1_2 1$/d' -i ../workspace/kcontrol/randr/randr.h
+}
+patchPhase=myPatchPhase
+genericBuild
diff --git a/pkgs/desktops/kde-4/runtime/default.nix b/pkgs/desktops/kde-4/runtime/default.nix
new file mode 100644
index 00000000000..7b9d16bdc45
--- /dev/null
+++ b/pkgs/desktops/kde-4/runtime/default.nix
@@ -0,0 +1,15 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdebase-runtime-4.0.0";
+  builder = ./builder.sh;
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdebase-runtime-4.0.0.tar.bz2;
+    md5 = "da93f59497ff90ad01bd4ab9b458f6cb";
+  };
+
+  propagatedBuildInputs = [kdepimlibs libusb kdebase xineLib];
+  inherit kdelibs;
+}
+
diff --git a/pkgs/desktops/kde-4/support/akode.nix b/pkgs/desktops/kde-4/support/akode.nix
new file mode 100644
index 00000000000..8fdf6736572
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/akode.nix
@@ -0,0 +1,7 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "akode-2.0.0dev";
+  src = svnSrc "akode" "0xkzv386wvh16njjv8z84mg3czp7j7n60lwhwns5fwqhx1s30h5y";
+  buildInputs = [ cmake qt openssl gettext cyrus_sasl alsaLib ];
+}
diff --git a/pkgs/desktops/kde-4/support/default.nix b/pkgs/desktops/kde-4/support/default.nix
new file mode 100644
index 00000000000..426a5811bd7
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/default.nix
@@ -0,0 +1,22 @@
+oldArgs:
+let
+	args = oldArgs // {
+	svnSrc = name: hash:
+	oldArgs.fetchsvn {
+		url = "svn://anonsvn.kde.org/home/kde/trunk/kdesupport/${name}";
+		rev = 747269;
+		sha256 = hash;
+	};
+	};
+in
+rec {
+	akode = (import ./akode.nix) args;
+	eigen = (import ./eigen.nix) args;
+	gmm = (import ./gmm.nix) args;
+	qca = (import ./qca.nix) args;
+	qimageblitz = (import ./qimageblitz.nix) args;
+	soprano = (import ./soprano.nix) args;
+	strigi = (import ./strigi.nix) args;
+	taglib = (import ./taglib.nix) args;
+	all = [qca gmm eigen taglib soprano strigi qimageblitz];
+}
diff --git a/pkgs/desktops/kde-4/support/eigen.nix b/pkgs/desktops/kde-4/support/eigen.nix
new file mode 100644
index 00000000000..163683a2921
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/eigen.nix
@@ -0,0 +1,7 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "eigen-1.0.5";
+  src = svnSrc "eigen" "0dr2gzrf17bdgxj4f9ibk7x5j7fqwwjsl800dzfvrhgj6v1mxm4x";
+  buildInputs = [ cmake ];
+}
diff --git a/pkgs/desktops/kde-4/support/gmm.nix b/pkgs/desktops/kde-4/support/gmm.nix
new file mode 100644
index 00000000000..843f9f6aaed
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/gmm.nix
@@ -0,0 +1,7 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "gmm-svn";
+  src = svnSrc "gmm" "0qvx9jf17z0mpwy8k6w6bla94gkkslkiv5w98aajfcq34n0zxcpc";
+  buildInputs = [ cmake ];
+}
diff --git a/pkgs/desktops/kde-4/support/qca.nix b/pkgs/desktops/kde-4/support/qca.nix
new file mode 100644
index 00000000000..fda435c7bff
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/qca.nix
@@ -0,0 +1,8 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "qca-2.0.0dev";
+  src = svnSrc "qca" "0dycmk8fn57mz2pfxck6d0g833fqg9zrw17789vxb4ks0xz0p3zp";
+  buildInputs = [ cmake qt openssl gettext cyrus_sasl libgcrypt gnupg ];
+  patchPhase = "sed -e '/set(qca_PLUGINSDIR/s@\${QT_PLUGINS_DIR}@\${CMAKE_INSTALL_PREFIX}/plugins@' -i ../CMakeLists.txt";
+}
diff --git a/pkgs/desktops/kde-4/support/qimageblitz.nix b/pkgs/desktops/kde-4/support/qimageblitz.nix
new file mode 100644
index 00000000000..3364b4eac5d
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/qimageblitz.nix
@@ -0,0 +1,7 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "qimageblitz-4.0.0svn";
+  src = svnSrc "qimageblitz" "0gi78bald70bc540jqcpa70x23hycywibn4raf5602hv4d5n8mnx";
+  buildInputs = [cmake qt];
+}
diff --git a/pkgs/desktops/kde-4/support/soprano.nix b/pkgs/desktops/kde-4/support/soprano.nix
new file mode 100644
index 00000000000..0cb490b9db7
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/soprano.nix
@@ -0,0 +1,8 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "soprano-1.9.0svn";
+  src = svnSrc "soprano" "02xfp7g41ahxwczkxipyi13rav6akhwgspxdhgk5gm94rg10hq2l";
+  CLUCENE_HOME=cluceneCore;
+  buildInputs = [ cmake qt cluceneCore redland ];
+}
diff --git a/pkgs/desktops/kde-4/support/strigi.nix b/pkgs/desktops/kde-4/support/strigi.nix
new file mode 100644
index 00000000000..d1ec98ea25f
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/strigi.nix
@@ -0,0 +1,9 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "strigi-svn";
+  src = svnSrc "strigi" "0dp145n93bqp91lvk2n10mghppyhdm3anh1l3a18d20hrvsm42z5";
+  CLUCENE_HOME=cluceneCore;
+  buildInputs = [ cmake zlib cluceneCore bzip2 libxml2 qt dbus
+  log4cxx stdenv.gcc.libc exiv2 bison cppunit perl ];
+}
diff --git a/pkgs/desktops/kde-4/support/taglib.nix b/pkgs/desktops/kde-4/support/taglib.nix
new file mode 100644
index 00000000000..9a2acc96636
--- /dev/null
+++ b/pkgs/desktops/kde-4/support/taglib.nix
@@ -0,0 +1,7 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "taglib-1.4svn";
+  src = svnSrc "taglib" "1myfgykflbs3l1mrzg4iv8rb1mbd0vpmzl5dnnslfi9b0xg6ydip";
+  buildInputs = [ cmake zlib ];
+}
diff --git a/pkgs/desktops/kde-4/toys/default.nix b/pkgs/desktops/kde-4/toys/default.nix
new file mode 100644
index 00000000000..39933f0b131
--- /dev/null
+++ b/pkgs/desktops/kde-4/toys/default.nix
@@ -0,0 +1,12 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdetoys-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdetoys-4.0.0.tar.bz2;
+    md5 = "6e4e2eea3d87718f48716f975b48ada2";
+  };
+
+  buildInputs = [kdelibs kdepimlibs kdeworkspace];
+}
diff --git a/pkgs/desktops/kde-4/utils/default.nix b/pkgs/desktops/kde-4/utils/default.nix
new file mode 100644
index 00000000000..2b256a8e768
--- /dev/null
+++ b/pkgs/desktops/kde-4/utils/default.nix
@@ -0,0 +1,13 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdeutils-4.0.0";
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdeutils-4.0.0.tar.bz2;
+    md5 = "5815625f215ff3be47a21074d2c047a0";
+  };
+
+  buildInputs = [kdelibs kdepimlibs kdeworkspace gmp libzip python ];
+# TODO : tpctl
+}
diff --git a/pkgs/desktops/kde-4/workspace/builder.sh b/pkgs/desktops/kde-4/workspace/builder.sh
new file mode 100755
index 00000000000..648d6175f35
--- /dev/null
+++ b/pkgs/desktops/kde-4/workspace/builder.sh
@@ -0,0 +1,12 @@
+source ${stdenv}/setup
+
+myPatchPhase()
+{
+	echo "Fixing dbus calls in CMakeLists.txt files"
+# Trailing slash in sed is essential
+	find .. -name CMakeLists.txt \
+	| xargs sed -e "s@\${DBUS_INTERFACES_INSTALL_DIR}/@${kdelibs}/share/dbus-1/interfaces/@" -i
+	sed -e '/^#define HAS_RANDR_1_2 1$/d' -i ../kcontrol/randr/randr.h
+}
+patchPhase=myPatchPhase
+genericBuild
diff --git a/pkgs/desktops/kde-4/workspace/default.nix b/pkgs/desktops/kde-4/workspace/default.nix
new file mode 100644
index 00000000000..70d2b3eddc3
--- /dev/null
+++ b/pkgs/desktops/kde-4/workspace/default.nix
@@ -0,0 +1,15 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "kdebase-workspace-4.0.0";
+  builder = ./builder.sh;
+  
+  src = fetchurl {
+    url = http://download.kde.org/stable/4.0.0/src/kdebase-workspace-4.0.0.tar.bz2;
+    md5 = "f3d2155ff5ff7472a8884bd3f31bff16";
+  };
+
+  buildInputs = [kdelibs kdepimlibs kdebase kderuntime stdenv.gcc.libc];
+  inherit kdelibs;
+}
+
diff --git a/pkgs/development/compilers/bigloo/default.nix b/pkgs/development/compilers/bigloo/default.nix
new file mode 100644
index 00000000000..2fb0b7c2276
--- /dev/null
+++ b/pkgs/development/compilers/bigloo/default.nix
@@ -0,0 +1,130 @@
+args:
+( args.mkDerivationByConfiguration {
+    flagConfig = {
+    /*
+Bigloo compiler:
+   --native=yes|no [default yes]
+   --jvm=yes|no|force [default no]
+   --dotnet=yes|no|force [default no]
+   --customgc=yes|no [default yes]
+   --bee=partial|full [default partial]
+
+API:
+   --enable-[calendar|fthread|mail|multimedia|pkgcomp|pkglib|pthread|sqlite|srfi1|ssl|web]
+   --disable-[calendar|fthread|mail|multimedia|pkgcomp|pkglib|pthread|sqlite|srfi1|ssl|web]
+
+Path:
+   --prefix=dir (sets bin, lib, zip, man, info and doc dirs)
+   --bindir=file
+   --libdir=file
+   --gcdir=dir (directory for non custom gc library)
+   --fildir=file
+   --zipdir=file
+   --dlldir=file
+   --mandir=file
+   --infodir=file
+   --docdir=file
+   --tmpdir=file (Bigloo tmp dir)
+   --tmp=file (Installation tmp dir)
+   --lispdir=file
+
+Tools and compilers:
+   --bigloo=comp [default bigloo]
+   --cc=comp [default gcc]
+   --ld=comp [default gcc]
+   --as=asm
+   --cflags=compilation flags
+   --lflags=compiler link flags
+   --coflags=optimization_flags
+   --cpicflags=pic_flags
+   --ldlibs=ld_libs
+   --ldcomplibs=ld_compiler_libs
+   --ldflags=ld_flags
+   --emacs=file
+   --xemacs=file (deprecated, use "--emacs" option)
+   --indent=file
+   --icc (configure for icc)
+
+Host configuration:
+   --arch=[i586|i686|athlon|athlon-tbird|athlon-mp|athlon-xp|k6-2|k6-3|pentium3|pentium4] (configure for specified hardware)
+   --a.out=file
+   --a.bat=file
+   --dirname=file-or-command
+   --force-posixos=operating-system
+   --os-win32
+   --os-macosx (tune for MacOSX)
+   --no-os-macosx (disable MacOSX auto configuration)
+   --cygwin-dos-path=[dos path]
+   --cygwin-dos-jvm=yes|no [default yes]
+   --no-share (disable shared libraries support)
+   --no-ldpreload
+   --sharedbde=yes|no [default no] (link Bde tools against shared libraries)
+   --sharedcompiler=yes|no [default no] (link Bigloo against shared libraries)
+
+JVM configuration:
+   --java=file
+   --javac=file
+   --javaprefix=dir
+   --javashell=shell [should be sh or msdos (default sh)]
+   --native-default-backend
+   --jvm-default-backend
+
+.NET configuration:
+   --pnet (configure for GNU pnet)
+   --mono (configure for Ximian Mono)
+   --dotnetldstyle=style [should be pnet, mono]
+   --dotnetcsccstyle=style [should be pnet, mono]
+   --dotnetclrstyle=style [should be pnet, mono]
+   --dotnetcscc=file
+   --dotnetld=file
+   --dotnetclr=file
+   --dotnetclropt=options
+   --dotnetshell=shell [should be sh or msdos (default sh)]
+   --dotnetasm=asm [optional]
+
+Misc:
+   --finalization=yes|no [default no]
+   --benchmark=yes|no [default no] (must use --arch too)
+   --stack-check=no
+
+Configuration settings:
+   --bigloo.h[=file]
+   --bigloo_gc.h[=file]
+   --bigloo_config.h[=file]
+   --bigloo_config.jvm[=file]
+   --Makefile.config=file
+   --configure.log=file
+   --no-summary
+   --bootconfig
+   --bootdir=dir
+   --configureinfo=yes|no [default no]
+
+   */
+
+    }; 
+
+    extraAttrs = co : rec {
+      name = "bigloo3.0d-alpha05Feb08"; # Thanks to Manuel Serrano for fixing the mv trouble 
+
+      # take care, modifying generated C-Code (altering string and length of string) 
+      preConfigure = 
+        "sed -i -e 's=/bin/rm -f \", 14=rm -f \", 9=' "
+         + " -e 's=/bin/mv \", 11=mv \", 6=' "
+         + "comptime/Cc/cc.c\n"
+      + "sed -i -e 's=/bin/rm=rm=' "
+           + " -e 's=/bin/mv=mv=' "
+         + "configure  gc/install-gc-*";
+
+      src = args.fetchurl {
+        url = "ftp://ftp-sop.inria.fr/mimosa/fp/Bigloo/${name}.tar.gz";
+        sha256 = "03rknb1nl3z2f86k6iazbrapmli2m8lcs21lqrri8ys8s72dm33w";
+      };
+
+    meta = { 
+      description = "scheme -> C / Java compiler (.net experimental)";
+      homepage = http://www-sop.inria.fr/mimosa/fp/Bigloo/;
+      # you can choose one of the following licenses: 
+      license = ["GPL"];
+    };
+  };
+} ) args
diff --git a/pkgs/development/compilers/fpc/binary.nix b/pkgs/development/compilers/fpc/binary.nix
index b76441e38d6..99725b501c0 100644
--- a/pkgs/development/compilers/fpc/binary.nix
+++ b/pkgs/development/compilers/fpc/binary.nix
@@ -1,9 +1,8 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "fpc-2.0.4-binary";
 
-  src = args.
-	fetchurl {
+  src = fetchurl {
 		url = ftp://ftp.chg.ru/pub/lang/pascal/fpc/dist/i386-linux-2.0.4/fpc-2.0.4.i386-linux.tar;
 		sha256 = "0b2szv2anbf58h4i5mlph93afv9qdx6i0jqggba04d3anjbl9gfy";
 	};
diff --git a/pkgs/development/compilers/fpc/default.nix b/pkgs/development/compilers/fpc/default.nix
index 5da4f65aea7..0d2f1fb525d 100644
--- a/pkgs/development/compilers/fpc/default.nix
+++ b/pkgs/development/compilers/fpc/default.nix
@@ -1,16 +1,16 @@
 args:
 if ((args ? startFPC) && (args.startFPC != null))
 	then 
-args.stdenv.mkDerivation {
+with args;
+stdenv.mkDerivation {
   name = "fpc-2.2.0";
 
-  src = args.
-	fetchurl {
+  src = fetchurl {
 		url = ftp://freepascal.stack.nl/pub/fpc/dist/source-2.2.0/fpcbuild-2.2.0.tar.gz;
 		sha256 = "0pvsdmimknkgy8jgdz9kd7w5bs9fy5ynrgswpk0ib6x0y26zxijm";
 	};
 
-  buildInputs = [args.startFPC args.gawk];
+  buildInputs = [startFPC gawk];
 
   installFlags = "INSTALL_PREFIX=\${out}";
   postInstall = "ln -fs $out/lib/fpc/*/ppc386 $out/bin;
diff --git a/pkgs/development/compilers/gcc-3.4/builder.sh b/pkgs/development/compilers/gcc-3.4/builder.sh
index 5a89201377d..eb1f211dce8 100644
--- a/pkgs/development/compilers/gcc-3.4/builder.sh
+++ b/pkgs/development/compilers/gcc-3.4/builder.sh
@@ -37,22 +37,10 @@ fi
 
 preConfigure=preConfigure
 preConfigure() {
-    
-    # Determine the frontends to build.
-    langs="c"
-    if test -n "$langCC"; then
-        langs="$langs,c++"
-    fi
-    if test -n "$langF77"; then
-        langs="$langs,f77"
-    fi
-
     # Perform the build in a different directory.
     mkdir ../build
     cd ../build
-
     configureScript=../$sourceRoot/configure
-    configureFlags="--enable-languages=$langs $configureFlags"
 }
 
 
diff --git a/pkgs/development/compilers/gcc-3.4/default.nix b/pkgs/development/compilers/gcc-3.4/default.nix
index 4cb834304e3..de7f079b2d9 100644
--- a/pkgs/development/compilers/gcc-3.4/default.nix
+++ b/pkgs/development/compilers/gcc-3.4/default.nix
@@ -5,6 +5,8 @@
 
 assert langC;
 
+with import ../../../lib;
+
 stdenv.mkDerivation {
   name = "gcc-3.4.6";
   builder = ./builder.sh;
@@ -15,7 +17,22 @@ stdenv.mkDerivation {
 
   patches = if noSysDirs then [./no-sys-dirs.patch] else [];
 
-  inherit noSysDirs langC langCC langF77 profiledCompiler;
+  inherit noSysDirs profiledCompiler;
+
+  configureFlags = "
+    --disable-multilib
+    --with-system-zlib
+    --enable-languages=${
+      concatStrings (intersperse ","
+        (  optional langC   "c"
+        ++ optional langCC  "c++"
+        ++ optional langF77 "f77"
+        )
+      )
+    }
+  ";
+
+  passthru = { inherit langC langCC langF77; };
 
   meta = {
     homepage = "http://gcc.gnu.org/";
diff --git a/pkgs/development/compilers/gcc-4.1/default.nix b/pkgs/development/compilers/gcc-4.1/default.nix
index e6d5452512e..621f96e49f9 100644
--- a/pkgs/development/compilers/gcc-4.1/default.nix
+++ b/pkgs/development/compilers/gcc-4.1/default.nix
@@ -15,18 +15,18 @@ stdenv.mkDerivation ({
   builder = if langF77 then ./fortran.sh else  ./builder.sh;
   
   src =
-    [(fetchurl {
+    optional /*langC*/ true (fetchurl {
       url = mirror://gnu/gcc/gcc-4.1.2/gcc-core-4.1.2.tar.bz2;
       sha256 = "07binc1hqlr0g387zrg5sp57i12yzd5ja2lgjb83bbh0h3gwbsbv";
-    })] ++
-    (if /*langCC*/ true then [(fetchurl {
+    }) ++
+    optional /*langCC*/ true (fetchurl {
       url = mirror://gnu/gcc/gcc-4.1.2/gcc-g++-4.1.2.tar.bz2;
       sha256 = "1qm2izcxna10jai0v4s41myki0xkw9174qpl6k1rnrqhbx0sl1hc";
-    })] else []) ++
-    (if langF77 then [(fetchurl {
+    }) ++
+    optional langF77 (fetchurl {
       url = mirror://gnu/gcc/gcc-4.1.2/gcc-fortran-4.1.2.tar.bz2;
       sha256 = "0772dhmm4gc10420h0d0mfkk2sirvjmjxz8j0ywm8wp5qf8vdi9z";
-    })] else []);
+    });
     
   patches =
     optional noSysDirs [./no-sys-dirs.patch];
diff --git a/pkgs/development/compilers/gcc-4.2/builder.sh b/pkgs/development/compilers/gcc-4.2/builder.sh
index c17d0403702..ee11e974a40 100644
--- a/pkgs/development/compilers/gcc-4.2/builder.sh
+++ b/pkgs/development/compilers/gcc-4.2/builder.sh
@@ -40,6 +40,7 @@ if test "$noSysDirs" = "1"; then
     done
 
     makeFlagsArray=( \
+        "${makeFlagsArray[@]}" \
         NATIVE_SYSTEM_HEADER_DIR="$NIX_FIXINC_DUMMY" \
         SYSTEM_HEADER_DIR="$NIX_FIXINC_DUMMY" \
         LIMITS_H_TEST=true \
@@ -68,18 +69,30 @@ postInstall() {
     # Remove `fixincl' to prevent a retained dependency on the
     # previous gcc.
     rm -rf $out/libexec/gcc/*/*/install-tools
+    rm -rf $out/lib/gcc/*/*/install-tools
 
     # Get rid of some "fixed" header files
     rm -rf $out/lib/gcc/*/*/include/root
+
+    # Replace hard links for i686-pc-linux-gnu-gcc etc. with symlinks.
+    for i in $out/bin/*-gcc*; do
+        if cmp -s $out/bin/gcc $i; then
+            ln -sfn gcc $i
+        fi
+    done
+
+    for i in $out/bin/*-c++* $out/bin/*-g++*; do
+        if cmp -s $out/bin/g++ $i; then
+            ln -sfn g++ $i
+        fi
+    done
 }
 
 
-if test -z "$staticCompiler"; then
-    if test -z "$profiledCompiler"; then
-        buildFlags="bootstrap $buildFlags"
-    else    
-        buildFlags="profiledbootstrap $buildFlags"
-    fi
+if test -z "$profiledCompiler"; then
+    buildFlags="bootstrap $buildFlags"
+else    
+    buildFlags="profiledbootstrap $buildFlags"
 fi
 
 genericBuild
diff --git a/pkgs/development/compilers/gcc-4.2/default.nix b/pkgs/development/compilers/gcc-4.2/default.nix
index df0f3e5c48d..7fcf7717c5a 100644
--- a/pkgs/development/compilers/gcc-4.2/default.nix
+++ b/pkgs/development/compilers/gcc-4.2/default.nix
@@ -8,22 +8,24 @@ assert langC;
 
 with import ../../../lib;
 
+let version = "4.2.3"; in
+
 stdenv.mkDerivation {
-  name = "gcc-4.2.2";
+  name = "gcc-${version}";
   builder = ./builder.sh;
   
   src =
     optional /*langC*/ true (fetchurl {
-      url = mirror://gnu/gcc/gcc-4.2.2/gcc-core-4.2.2.tar.bz2;
-      sha256 = "01hdwd4im2xzg159fk022zqyhlxphqvpmabd25bqb8fjbs2yi80a";
+      url = "mirror://gnu/gcc/gcc-${version}/gcc-core-${version}.tar.bz2";
+      sha256 = "04y84s46wzy4h44hpacf7vyla7b5zfc1qvdq3myvrhp82cp0bv4r";
     }) ++
-    optional /*langCC*/ true (fetchurl {
-      url = mirror://gnu/gcc/gcc-4.2.2/gcc-g++-4.2.2.tar.bz2;
-      sha256 = "04xankxi3bi4gvgv8rq9h6w3bdx59bg9zh0zv6lyw373gy26ygmq";
+    optional langCC (fetchurl {
+      url = "mirror://gnu/gcc/gcc-${version}/gcc-g++-${version}.tar.bz2";
+      sha256 = "0spzz549fifwv02ym33azzwizl0zkq5m1fgy88ccmcyzmwpgyzfq";
     }) ++
     optional langF77 (fetchurl {
-      url = mirror://gnu/gcc/gcc-4.2.2/gcc-fortran-4.2.2.tar.bz2;
-      sha256 = "1fybl88w0l99cqppx18i6hnq5dsrssx3qd7vr2ybmmk3nfx8pziq";
+      url = "mirror://gnu/gcc/gcc-${version}/gcc-fortran-${version}.tar.bz2";
+      sha256 = "1l3ww6qymrkcfqlssb41a5fdnh6w2hqk0v2ijx56jgjbdnzawyp0";
     });
     
   patches =
@@ -47,7 +49,7 @@ stdenv.mkDerivation {
     ${if stdenv.isi686 then "--with-arch=i686" else ""}
   ";
 
-  makeFlags = if staticCompiler then "LDFLAGS=-static" else "";
+  NIX_EXTRA_LDFLAGS = if staticCompiler then "-static" else "";
 
   passthru = { inherit langC langCC langF77; };
 
diff --git a/pkgs/development/compilers/ghc-6.6.1/builder.sh b/pkgs/development/compilers/ghc-6.6.1/builder.sh
deleted file mode 100644
index 0ea4fc496f9..00000000000
--- a/pkgs/development/compilers/ghc-6.6.1/builder.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-source $stdenv/setup
-
-# Setup isolated package management
-postInstall()
-{
-    ensureDir "$out/nix-support"
-    echo "# Path to the GHC compiler directory in the store" > $out/nix-support/setup-hook
-    echo "ghc=$out" >> $out/nix-support/setup-hook
-    echo ""         >> $out/nix-support/setup-hook
-    cat $setupHook  >> $out/nix-support/setup-hook
-}
-postInstall=postInstall
-
-configureFlags="--with-gmp-libraries=$gmp/lib --with-readline-libraries=\"$readline/lib\""
-
-preConfigure()
-{
-    chmod u+x rts/gmp/configure
-    # still requires a hack for ncurses
-    sed -i "s|^\(library-dirs.*$\)|\1 \"$ncurses/lib\"|" libraries/readline/package.conf.in
-}
-preConfigure=preConfigure
-
-
-# Standard configure/make/make install
-genericBuild
diff --git a/pkgs/development/compilers/ghc-6.6.1/default.nix b/pkgs/development/compilers/ghc-6.6.1/default.nix
index 738b6a79fc7..14a59aeeeba 100644
--- a/pkgs/development/compilers/ghc-6.6.1/default.nix
+++ b/pkgs/development/compilers/ghc-6.6.1/default.nix
@@ -1,6 +1,6 @@
 {stdenv, fetchurl, readline, ghc, perl, m4, gmp, ncurses}:
 
-stdenv.mkDerivation {
+stdenv.mkDerivation (rec {
   name = "ghc-6.6.1";
 
   src = map fetchurl [
@@ -12,15 +12,34 @@ stdenv.mkDerivation {
     }
   ];
 
-  builder = ./builder.sh;
-
-  buildInputs = [ghc readline perl m4];
+  buildInputs = [ghc readline perl m4 gmp];
 
   setupHook = ./setup-hook.sh;
 
   meta = {
-    description = "The Glasgow Haskell Compiler v6.6.1";
+    description = "The Glasgow Haskell Compiler";
   };
 
+  postInstall = ''
+    ensureDir "$out/nix-support"
+    echo "# Path to the GHC compiler directory in the store" > $out/nix-support/setup-hook
+    echo "ghc=$out" >> $out/nix-support/setup-hook
+    echo ""         >> $out/nix-support/setup-hook
+    cat $setupHook  >> $out/nix-support/setup-hook
+  '';
+
+  configureFlags=[
+    "--with-gmp-libraries=${gmp}/lib"
+    "--with-readline-libraries=${readline}/lib"
+    "--with-gmp-includes=${gmp}/include"
+    "--with-gcc=${gcc}/bin/gcc"
+  ];
+
+  preConfigure = ''
+    # still requires a hack for ncurses
+    sed -i "s|^\(library-dirs.*$\)|\1 \"${ncurses}/lib\"|" libraries/readline/package.conf.in
+  '';
+
+  inherit (stdenv) gcc;
   inherit readline gmp ncurses;
-}
+})
diff --git a/pkgs/development/compilers/ghc-6.8/builder.sh b/pkgs/development/compilers/ghc-6.8/builder.sh
deleted file mode 100644
index 0ea4fc496f9..00000000000
--- a/pkgs/development/compilers/ghc-6.8/builder.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-source $stdenv/setup
-
-# Setup isolated package management
-postInstall()
-{
-    ensureDir "$out/nix-support"
-    echo "# Path to the GHC compiler directory in the store" > $out/nix-support/setup-hook
-    echo "ghc=$out" >> $out/nix-support/setup-hook
-    echo ""         >> $out/nix-support/setup-hook
-    cat $setupHook  >> $out/nix-support/setup-hook
-}
-postInstall=postInstall
-
-configureFlags="--with-gmp-libraries=$gmp/lib --with-readline-libraries=\"$readline/lib\""
-
-preConfigure()
-{
-    chmod u+x rts/gmp/configure
-    # still requires a hack for ncurses
-    sed -i "s|^\(library-dirs.*$\)|\1 \"$ncurses/lib\"|" libraries/readline/package.conf.in
-}
-preConfigure=preConfigure
-
-
-# Standard configure/make/make install
-genericBuild
diff --git a/pkgs/development/compilers/ghc-6.8/default.nix b/pkgs/development/compilers/ghc-6.8/default.nix
index 1e1577ea292..518b5f391a3 100644
--- a/pkgs/development/compilers/ghc-6.8/default.nix
+++ b/pkgs/development/compilers/ghc-6.8/default.nix
@@ -1,41 +1,46 @@
 {stdenv, fetchurl, readline, ghc, perl, m4, gmp, ncurses}:
 
 stdenv.mkDerivation (rec {
-  name = "ghc-6.8.0.20071018";
+  name = "ghc-6.8.2";
   homepage = "http://www.haskell.org/ghc";
 
   src = map fetchurl [
     { url = "${homepage}/dist/stable/dist/${name}-src.tar.bz2";
-      md5 = "7e61bd2a55c2d6ed5a6d996d19d3f6bf";
+      md5 = "745c6b7d4370610244419cbfec4b2f84";
     }
     { url = "${homepage}/dist/stable/dist/${name}-src-extralibs.tar.bz2";
-      md5 = "7b155c1d1e7daa492cc2161b3828a377";
+      md5 = "d199c50814188fb77355d41058b8613c";
     }
   ];
 
-  buildInputs = [ghc readline perl m4];
+  buildInputs = [ghc readline perl m4 gmp];
 
   setupHook = ./setup-hook.sh;
 
   meta = {
-    description = "The Glasgow Haskell Compiler v6.8 (snapshot)";
+    description = "The Glasgow Haskell Compiler";
   };
 
-  postInstall = "
-    ensureDir \"$out/nix-support\"
-    echo \"# Path to the GHC compiler directory in the store\" > $out/nix-support/setup-hook
-    echo \"ghc=$out\" >> $out/nix-support/setup-hook
-    echo \"\"         >> $out/nix-support/setup-hook
-    cat $setupHook    >> $out/nix-support/setup-hook
-  ";
-
-  configureFlags="--with-gmp-libraries=$gmp/lib --with-readline-libraries=\"$readline/lib\"";
+  postInstall = ''
+    ensureDir "$out/nix-support"
+    echo "# Path to the GHC compiler directory in the store" > $out/nix-support/setup-hook
+    echo "ghc=$out" >> $out/nix-support/setup-hook
+    echo ""         >> $out/nix-support/setup-hook
+    cat $setupHook  >> $out/nix-support/setup-hook
+  '';
+
+  configureFlags=[
+    "--with-gmp-libraries=${gmp}/lib"
+    "--with-readline-libraries=${readline}/lib"
+    "--with-gmp-includes=${gmp}/include"
+    "--with-gcc=${gcc}/bin/gcc"
+  ];
 
-  # the presence of this file makes Cabal cry for happy while generating makefiles ...
   preConfigure = "
-    echo 'GhcThreaded=NO' > mk/build.mk
-    rm libraries/haskell-src/Language/Haskell/Parser.ly
+    # still requires a hack for ncurses
+    sed -i \"s|^\\\(ld-options.*$\\\)|\\\1 -L${ncurses}/lib|\" libraries/readline/readline.buildinfo.in
   ";
 
+  inherit (stdenv) gcc;
   inherit readline gmp ncurses;
 })
diff --git a/pkgs/development/compilers/ghc-6.8/setup-hook.sh b/pkgs/development/compilers/ghc-6.8/setup-hook.sh
index 23da6de0382..489c8d532b8 100644
--- a/pkgs/development/compilers/ghc-6.8/setup-hook.sh
+++ b/pkgs/development/compilers/ghc-6.8/setup-hook.sh
@@ -1,5 +1,5 @@
 # Support dir for isolating GHC
-ghc_support=$TMPDIR/ghc-6.6-nix-support
+ghc_support=$TMPDIR/ghc-6.8-nix-support
 mkdir -p $ghc_support
 
 # Create isolated package config
diff --git a/pkgs/development/compilers/ghc-6.8/x86_64-linux_patch b/pkgs/development/compilers/ghc-6.8/x86_64-linux_patch
new file mode 100644
index 00000000000..26a9cf2781e
--- /dev/null
+++ b/pkgs/development/compilers/ghc-6.8/x86_64-linux_patch
@@ -0,0 +1,24 @@
+diff -ru /tmp/ghc_fresh/ghc-6.9.20071119/compiler/codeGen/CgUtils.hs ./ghc-6.9.20071119/compiler/codeGen/CgUtils.hs
+--- /tmp/ghc_fresh/ghc-6.9.20071119/compiler/codeGen/CgUtils.hs 2007-12-05 15:02:30.000000000 +0100
++++ ./ghc-6.9.20071119/compiler/codeGen/CgUtils.hs      2007-12-05 15:33:16.000000000 +0100
+@@ -51,7 +51,7 @@
+   ) where
+ 
+ #include "HsVersions.h"
+-#include "MachRegs.h"
++#include "../includes/MachRegs.h"
+ 
+ import CgMonad
+ import TyCon
+diff -ru /tmp/ghc_fresh/ghc-6.9.20071119/compiler/nativeGen/MachRegs.lhs ./ghc-6.9.20071119/compiler/nativeGen/MachRegs.lhs
+--- /tmp/ghc_fresh/ghc-6.9.20071119/compiler/nativeGen/MachRegs.lhs     2007-12-05 15:02:30.000000000 +0100
++++ ./ghc-6.9.20071119/compiler/nativeGen/MachRegs.lhs  2007-12-05 15:32:41.000000000 +0100
+@@ -90,7 +90,7 @@
+ -- HACK: go for the max
+ #endif
+ 
+-#include "MachRegs.h"
++#include "../includes/MachRegs.h"
+ 
+ import Cmm
+ import MachOp          ( MachRep(..) )
diff --git a/pkgs/development/compilers/ghc/boot.nix b/pkgs/development/compilers/ghc/boot.nix
index 50eff51e063..ab606d4c2ba 100644
--- a/pkgs/development/compilers/ghc/boot.nix
+++ b/pkgs/development/compilers/ghc/boot.nix
@@ -1,20 +1,56 @@
 {stdenv, fetchurl, perl, readline, ncurses, gmp}:
 
-assert stdenv.system == "i686-linux" || stdenv.system == "x86_64-linux";
-
 stdenv.mkDerivation {
-  name = "ghc-6.4.2";
-  builder = ./boot.sh;
-  src = if stdenv.system == "i686-linux" then
-        (fetchurl {
-             url = http://nix.cs.uu.nl/dist/tarballs/ghc-6.4.2-i386-unknown-linux.tar.bz2;
-             md5 = "092fe2e25dab22b926babe97cc77db1f";
-        }) else
-        (fetchurl {
-             url = http://haskell.org/ghc/dist/6.4.2/ghc-6.4.2-x86_64-unknown-linux.tar.bz2;
-             md5 = "8f5fe48798f715cd05214a10987bf6d5";
-        });             
+  name = if stdenv.system == "i686-darwin" then "ghc-6.6.1" else "ghc-6.4.2";
+
+  src =
+    if stdenv.system == "i686-linux" then
+      fetchurl {
+        url = http://nix.cs.uu.nl/dist/tarballs/ghc-6.4.2-i386-unknown-linux.tar.bz2;
+        md5 = "092fe2e25dab22b926babe97cc77db1f";
+      }
+    else if stdenv.system == "x86_64-linux" then
+      fetchurl {
+        url = http://haskell.org/ghc/dist/6.4.2/ghc-6.4.2-x86_64-unknown-linux.tar.bz2;
+        md5 = "8f5fe48798f715cd05214a10987bf6d5";
+      }
+    else if stdenv.system == "i686-darwin" then
+      fetchurl {
+        url = http://www.haskell.org/ghc/dist/6.6.1/ghc-6.6.1-i386-apple-darwin.tar.bz2;
+        sha256 = "1drbsicanr6jlykvs4vs6gbi2q9ac1bcaxz2vzwh3pfv3lfibwia";
+      }
+    else throw "cannot bootstrap GHC on this platform"; 
+
   buildInputs = [perl];
-  propagatedBuildInputs = [readline ncurses gmp];
-  inherit readline ncurses gmp;
+
+  # On Linux, use patchelf to modify the executables so that they can
+  # find readline/gmp.
+  postBuild = if stdenv.isLinux then "
+    find . -type f -perm +100 \\
+        -exec patchelf --interpreter \"$(cat $NIX_GCC/nix-support/dynamic-linker)\" \\
+        --set-rpath \"${readline}/lib:${ncurses}/lib:${gmp}/lib\" {} \\;
+  " else "";
+
+  # The binaries for Darwin use frameworks, so fake those frameworks,
+  # and create some wrapper scripts that set DYLD_FRAMEWORK_PATH so
+  # that the executables work with no special setup.
+  postInstall = if stdenv.isDarwin then "
+
+    ensureDir $out/frameworks/GMP.framework/Versions/A
+    ln -s ${gmp}/lib/libgmp.dylib $out/frameworks/GMP.framework/GMP
+    ln -s ${gmp}/lib/libgmp.dylib $out/frameworks/GMP.framework/Versions/A/GMP
+    ensureDir $out/frameworks/GNUreadline.framework/Versions/A
+    ln -s ${readline}/lib/libreadline.dylib $out/frameworks/GNUreadline.framework/GNUreadline
+    ln -s ${readline}/lib/libreadline.dylib $out/frameworks/GNUreadline.framework/Versions/A/GNUreadline
+
+    mv $out/bin $out/bin-orig
+    mkdir $out/bin
+    for i in $(cd $out/bin-orig && ls); do
+        echo \"#! $SHELL -e\" >> $out/bin/$i
+        echo \"DYLD_FRAMEWORK_PATH=$out/frameworks exec $out/bin-orig/$i -framework-path $out/frameworks \\\"\\$@\\\"\" >> $out/bin/$i
+        chmod +x $out/bin/$i
+    done
+
+  " else "";
+
 }
diff --git a/pkgs/development/compilers/ghc/boot.sh b/pkgs/development/compilers/ghc/boot.sh
deleted file mode 100644
index 4b88b6bdba3..00000000000
--- a/pkgs/development/compilers/ghc/boot.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-source $stdenv/setup
-
-postBuild=postBuild
-postBuild () {
-    find . -type f -perm +100 \
-        -exec patchelf --interpreter "$(cat $NIX_GCC/nix-support/dynamic-linker)" \
-        --set-rpath "$readline/lib:$ncurses/lib:$gmp/lib" {} \;
-}
-
-genericBuild
diff --git a/pkgs/development/compilers/ghc/createGhcWrapper/default.nix b/pkgs/development/compilers/ghc/createGhcWrapper/default.nix
index 5eeb4d43190..4d6094f5d72 100644
--- a/pkgs/development/compilers/ghc/createGhcWrapper/default.nix
+++ b/pkgs/development/compilers/ghc/createGhcWrapper/default.nix
@@ -1,9 +1,15 @@
-args: with args;
+args: with args; with lib; with annotatedDerivations;
 
 stdenv.mkDerivation {
   inherit suffix name ghc ;
 
-  buildInputs = libraries ++ [ghcPkgUtil];
+  buildInputs = map delAnnotation (libraries ++ [ghcPkgUtil]);
+  #tags = if (installSourceAndTags == true) then
+  #        map sourceWithTagsDerivation ( uniqList { inputList = 
+  #            ( filterAnnotated ( concatLists (map uniqAnnotatedDeps libraries ) ) ) ; } )
+  #        else [];
+  tags = map (x : sourceWithTagsDerivation (x.sourceWithTags)) 
+          (uniqList { inputList=  filter annotatedWithSourceAndTagInfo libraries; } );
 
   phases="installPhase";
 
@@ -21,5 +27,12 @@ GHC_PACKAGE_PATH=\${GHC_PACKAGE_PATH}\${g} \$ghc/bin/$app \"\\\$@\"
 EOF
       chmod +x \"\$out/bin/\$a$suffix\"
     done
+
+    ensureDir \$out/{src,tags}
+    for i in \$tags; do
+      for path in src tags; do
+        ln -s \$i/\$path/* \$out/\$path
+      done
+    done
 ";
 }
diff --git a/pkgs/development/compilers/ghcs/default.nix b/pkgs/development/compilers/ghcs/default.nix
index c3a46968880..6dd37576524 100644
--- a/pkgs/development/compilers/ghcs/default.nix
+++ b/pkgs/development/compilers/ghcs/default.nix
@@ -1,11 +1,13 @@
-{ ghcPkgUtil, gnum4, perl, ghcboot, stdenv, fetchurl, recurseIntoAttrs, gmp, readline, lib } : rec {
+{ ghcPkgUtil, gnum4, perl, ghcboot, stdenv, fetchurl, recurseIntoAttrs, gmp, readline, lib, annotatedDerivations, hasktags, ctags } : 
+with annotatedDerivations;
+rec {
   
   /* What's in here?
      Goal:  really pure GHC. This means put every library into its each package.conf
      and add all together using GHC_PACKAGE_PATH
 
      First I've tried separating the build of ghc from it's lib. It hase been to painful. I've failed.
-     Now there is splitpackagedb.hs which just takes the installed package.conf
+     Now there is nix_ghc_pkg_tool.hs which just takes the installed package.conf
      and creates a new package db file for each contained package.
 
      The final attribute set looks similar to this:
@@ -31,31 +33,6 @@
 
   */
 
-  # creates a nix package out of the single package.conf files created when after installing ghc (see splitpackagedb.hs)
-  packageByPackageDB = otherPkg : name : packageconfpath : propagatedBuildInputs : stdenv.mkDerivation {
-    inherit name otherPkg propagatedBuildInputs;
-    phases = "buildPhase fixupPhase";
-    buildInputs = [ghcPkgUtil];
-    buildPhase = "setupHookRegisteringPackageDatabase \"$otherPkg/${packageconfpath}\"
-      ";
-  };
-
-  # used to automatically get dependencies ( used for core_libs ) 
-  # TODO use kind of state and evaluate deps of a dep only once
-  resolveDeps = ghc : libs : 
-    let attrs = __listToAttrs libs; in
-      rec {
-        # using undocumented feature that attribute can contain hyphens when using listToAttrs
-        # You should be able to get the attribute values using __getAttr
-        result = __listToAttrs (map ( l : lib.av l.name (
-                               packageByPackageDB ghc l.name 
-                                      ("lib/ghc-${ghc.version}/${l.name}.conf")
-                                      (map (n: __getAttr n result) l.deps)
-                ) ) libs );
-      }.result;
-
-
-  
   #this only works for ghc-6.8 right now
   ghcAndLibraries = { version, src /* , core_libraries, extra_libraries  */
                     , extra_src }:
@@ -74,12 +51,14 @@
         sed -i \"s|^\(library-dirs.*$\)|\1 \\\"$ncurses/lib\\\"|\" libraries/readline/package.conf.in
       ";
 
-      splitpackagedb = ./splitpackagedb.hs;
+      # TODO add unique (filter duplicates?) shouldn't be there? 
+      nix_ghc_pkg_tool = ./nix_ghc_pkg_tool.hs;
 
       configurePhase = "./configure"
        +" --prefix=\$out "
        +" --with-ghc=\$ghcboot/bin/ghc"
        +" --with-gmp-libraries=$gmp/lib"
+       +" --with-gmp-includes=${gmp}/include"
        +" --with-readline-libraries=\"$readline/lib\"";
 
       # now read the main package.conf and create a single package db file for each of them
@@ -88,9 +67,10 @@
       #  note : I don't know yet wether it's a good idea to have RUNGHC.. It's faster
       # but you can't pass packages, can you?
       postInstall = "
-        cp \$splitpackagedb splitpackagedb.hs
-        \$out/bin/ghc-\$version --make -o splitpackagedb  splitpackagedb.hs;
-        ./splitpackagedb \$out/lib/ghc-\$version/package.conf \$out/lib/ghc-\$version
+        cp \$nix_ghc_pkg_tool nix_ghc_pkg_tool.hs
+        \$out/bin/ghc-\$version --make -o nix_ghc_pkg_tool  nix_ghc_pkg_tool.hs;
+        ./nix_ghc_pkg_tool split \$out/lib/ghc-\$version/package.conf \$out/lib/ghc-\$version
+        cp nix_ghc_pkg_tool \$out/bin
 
         if test -x \$out/bin/runghc; then
           RUNHGHC=\$out/bin/runghc # > ghc-6.7/8 ?
@@ -105,64 +85,120 @@
       ";
     };
 
-    # Why this effort? If you want to use pretty-0.9 you can do this now without cabal choosing the 1.0 version hassle 
-    core_libs = resolveDeps ghc
-      [ { name = "Cabal-1.2.0"; deps = ["base-2.1" "pretty-1.0" "old-locale-1.0" "old-time-1.0" "directory-1.0" "unix-2.0" "process-1.0" "array-0.1" "containers-0.1" "rts-1.0" "filepath-1.0"];} #
-        { name = "array-0.1"; deps = ["base-2.1"];}
-        { name = "base-2.1"; deps = [];} #
-        { name = "bytestring-0.9"; deps = [ "base-2.1" "array-0.1" ];}
-        { name = "containers-0.1"; deps = [ "base-2.1" "array-0.1" ];}
-        { name = "directory-1.0"; deps = [ "base-2.1" "old-locale-1.0" "old-time-1.0" "filepath-1.0"];}
-        { name = "filepath-1.0"; deps = [ "base-2.1" ];} #
-        { name = "ghc-6.8.0.20071004"; deps = [ "base-2.1" "old-locale-1.0" "old-time-1.0" "filepath-1.0" "directory-1.0" "array-0.1" "containers-0.1" "hpc-0.5" "bytestring-0.9" "pretty-1.0" "packedstring-0.1" "template-haskell-0.1" "unix-2.0" "process-1.0" "readline-1.0" "Cabal-1.2.0" "random-1.0" "haskell98-1.0"];}
-        { name = "haskell98-1.0"; deps = [ "base-2.1" "old-locale-1.0" "old-time-1.0" "filepath-1.0" "directory-1.0" "random-1.0" "unix-2.0" "process-1.0" "array-0.1"];}
-        { name = "hpc-0.5"; deps = [ "base-2.1" "old-locale-1.0" "old-time-1.0" "filepath-1.0" "directory-1.0" "array-0.1" "containers-0.1"]; }
-        { name = "old-locale-1.0"; deps = [ "base-2.1"];}
-        { name = "old-time-1.0"; deps = [ "base-2.1" "old-locale-1.0" ];}
-        { name = "packedstring-0.1"; deps = [ "base-2.1" "array-0.1" ];}
-        { name = "pretty-1.0"; deps = [ "base-2.1" ];}
-        { name = "process-1.0"; deps = [ "base-2.1" "old-locale-1.0" "old-time-1.0" "filepath-1.0" "directory-1.0" "unix-2.0"];}
-        { name = "random-1.0"; deps = [ "base-2.1" "old-locale-1.0" "old-time-1.0"];}
-        { name = "readline-1.0"; deps = [ "base-2.1" "old-locale-1.0" "old-time-1.0" "filepath-1.0" "directory-1.0" "unix-2.0" "process-1.0" ];}
-        { name = "rts-1.0"; deps = [ "base-2.1" ];} #
-        { name = "template-haskell-0.1"; deps = [ "base-2.1" "pretty-1.0" "array-0.1" "packedstring-0.1" "containers-0.1" ];}
-        { name = "unix-2.0"; deps = [ "base-2.1" "old-locale-1.0" "old-time-1.0" "filepath-1.0" "directory-1.0" ];}
-      ];
-
-      
-
-    extra_libs = [];
-
-    #all_libs = core_libs ++ extra_libs;
-
-  } );
-
-  ghc68 = ghcAndLibraries {
-    version = "6.8.0.20071004";
+    core_libs = rec {
+        #   name (using lowercase letters everywhere because using installing packages having different capitalization is discouraged) - this way there is not that much to remember?
+
+        cabal_darcs_name = "cabal-darcs";
+
+        # introducing p here to speed things up.
+        # It merges derivations (defined below) and additional inputs. I hope that using as few nix functions as possible results in greates speed?
+        # unfortunately with x; won't work because it forces nix to evaluate all attributes of x which would lead to infinite recursion
+        pkgs = let x = derivations; in {
+            # ghc extra packages 
+          cabal = { name = "Cabal-1.2.3.0"; srcDir = "libraries/Cabal";
+                          deps = [x.base x.pretty x.old_locale x.old_time
+                            x.directory x.unix x.process x.array x.containers
+                            x.rts x.filepath ]; };
+          array = { name = "array-0.1.0.0"; srcDir = "libraries/array";
+                          deps = [x.base ]; };
+          base = { name = "base-3.0.1.0"; srcDir = "libraries/base";
+                          deps = [x.rts ]; };
+          bytestring = { name = "bytestring-0.9.0.1"; srcDir = "libraries/bytestring";
+                          deps = [ x.base x.array ];};
+          containers = { name = "containers-0.1.0.1"; srcDir = "libraries/containers";
+                          deps = [ x.base x.array ];};
+          directory = { name = "directory-1.0.0.0"; srcDir = "libraries/directory";
+                          deps = [ x.base x.old_locale x.old_time x.filepath ];};
+          filepath = { name = "filepath-1.1.0.0"; srcDir = "libraries/filepath";
+                          deps = [ x.base ];};
+          ghc = { name = "ghc-${version}"; srcDir = "libraries/Cabal";
+                          deps = [ x.base x.old_locale x.old_time x.filepath
+                            x.directory x.array x.containers x.hpc x.bytestring
+                            x.pretty x.packedstring x.template_haskell x.unix
+                            x.process x.readline x.cabal x.random x.haskell98 ]; };
+          haskell98 = { name = "haskell98-1.0.1.0"; srcDir = "libraries/haskell98";
+                          deps = [ x.base x.old_locale x.old_time x.filepath
+                            x.directory x.random x.unix x.process x.array]; };
+          hpc = { name = "hpc-0.5.0.0"; srcDir = "libraries/hpc";
+                          deps = [ x.base x.old_locale x.old_time x.filepath
+                            x.directory x.array x.containers ]; };
+          old_locale = { name = "old-locale-1.0.0.0"; srcDir = "libraries/old-locale";
+                          deps = [ x.base ]; };
+          old_time = { name = "old-time-1.0.0.0"; srcDir = "libraries/old-time";
+                          deps = [ x.base x.old_locale ];};
+          packedstring = { name = "packedstring-0.1.0.0"; srcDir = "libraries/packedstring";
+                          deps = [ x.base x.array ];};
+          pretty = { name = "pretty-1.0.0.0"; srcDir = "libraries/pretty";
+                          deps = [ x.base ];};
+          process = { name = "process-1.0.0.0"; srcDir = "libraries/process";
+                          deps = [ x.base x.old_locale x.old_time x.filepath
+                            x.directory x.unix ]; };
+          random = { name = "random-1.0.0.0"; srcDir = "libraries/random";
+                          deps = [ x.base x.old_locale x.old_time ]; };
+          readline = { name = "readline-1.0.1.0"; srcDir = "libraries/readline";
+                          deps = [ x.base x.old_locale x.old_time x.filepath
+                            x.directory x.unix x.process ];};
+          rts = rec { 
+                  name = "rts-1.0"; srcDir = "rts"; # TODO: Doesn't have .hs files so I should use ctags if creating tags at all
+                  deps = [];
+                  createTagFiles = [
+                      { name = "${name}_haskell_tags";
+                        tagCmd = "${toString ctags}/bin/ctags -R .;mv tags \$TAG_FILE"; }
+                    ];
+          };
+          template_haskell = { name = "template-haskell-2.2.0.0"; srcDir = "libraries/template-haskell";
+                          deps = [ x.base x.pretty x.array x.packedstring x.containers ];};
+          unix = { name = "unix-2.3.0.0"; srcDir = "libraries/unix";
+                          deps = [ x.base x.old_locale x.old_time x.filepath x.directory ];};
+        };
+
+        toDerivation = attrs : with attrs;
+              rec {
+                inherit name;
+
+                #aDeps = concatLists ( catAttrs ( subsetmap id args [ "buildInputs" "propagatedBuildInputs" ] ) );
+                aDeps = deps;
+
+                # dummy derivation, only creates setup-hook for package database located in the ghc derivation 
+                aDeriv = stdenv.mkDerivation {
+                    inherit name;
+                    phases = "buildPhase fixupPhase";
+                    buildInputs = [ ghcPkgUtil ];
+                    propagatedBuildInputs = [ ghc ] ++ map delAnnotation  attrs.deps;
+                    buildPhase = "setupHookRegisteringPackageDatabase \"${ghc}/lib/ghc-${ghc.version}/${name}.conf\"";
+                };
+
+                sourceWithTags = {
+                  src = ghc.src;
+                  inherit srcDir;
+                  name = name + "-src-with-tags";
+                  createTagFiles = lib.maybeAttr "createTagFiles" [
+                      { name = "${name}_haskell_tags";
+                        tagCmd = "${toString hasktags}/bin/hasktags-modified --ctags `find . -type f -name \"*.*hs\"`; sort tags > \$TAG_FILE"; } 
+                    ] attrs;
+                };
+          };
+        derivations = with lib; builtins.listToAttrs (lib.concatLists ( lib.mapRecordFlatten 
+                  ( n : attrs : let d = (toDerivation attrs); in [ (nv n d) (nv attrs.name d) ] ) pkgs ) );
+    }.derivations;
+  });
+
+  ghc68 = ghcAndLibraries rec {
+    version = "6.8.2";
     src = fetchurl {
-      url = http://www.haskell.org/ghc/dist/stable/dist/ghc-6.8.0.20071004-src.tar.bz2;
-      sha256 = "1yyl7sxykmvkiwfxkfzpqa6cmgw19phkyjcdv99ml22j16wli63l";
+      #url = http://www.haskell.org/ghc/dist/stable/dist/ghc-6.8.0.20071004-src.tar.bz2;
+      #sha256 = "1yyl7sxykmvkiwfxkfzpqa6cmgw19phkyjcdv99ml22j16wli63l";
+      url = "http://www.haskell.org/ghc/dist/stable/dist/ghc-${version}-src.tar.bz2";
+      md5 = "745c6b7d4370610244419cbfec4b2f84";
       #url = http://www.haskell.org/ghc/dist/stable/dist/ghc-6.8.20070912-src.tar.bz2;
       #sha256 = "1b1gvi7hc7sc0fkh29qvzzd5lgnlvdv3ayiak4mkfnzkahvmq85s";
     };
 
     extra_src = fetchurl {
-      url = http://www.haskell.org/ghc/dist/stable/dist/ghc-6.8.0.20071004-src-extralibs.tar.bz2;
-      sha256 = "0vjx4vb2xhv5v2wj74ii3gpjim7x9wj0m87zglqlhc8xn31pmrd2";
+      url = "http://www.haskell.org/ghc/dist/stable/dist/ghc-${version}-src-extralibs.tar.bz2";
+      sha256 = "044mpbzpkbxcnqhjnrnmjs00mr85057d123rrlz2vch795lxbkcn";
       #url = http://www.haskell.org/ghc/dist/stable/dist/ghc-6.8.20070912-src-extralibs.tar.bz2;
       #sha256 = "0py7d9nh3lkhjxr3yb3n9345d0hmzq79bi40al5rcr3sb84rnp9r";
     };
-
-    # this will change because of dependency hell :) 
-    #core_libraries = [ "Cabal" /* "Win32" */ "array" "base" "bytestring" "containers" 
-                       #"directory" "doc" "filepath" "haskell98" "hpc" "old-locale" "old-time"
-                       #"packedstring" "pretty" "process" "random" "readline" "stamp" 
-                       #"template-haskell" "unix" ];
-
-    #extra_libraries = [ "ALUT" "GLUT" "HGL" "HUnit" "ObjectIO" "OpenAL" "OpenGL" "QuickCheck" "X11" 
-                        #"arrows" "cgi" "fgl" "haskell-src" "html" "mtl" "network" "parallel" "parsec" 
-                        #"regex-base" "regex-compat" "regex-posix" "stm" "time" "xhtm" ];
-
   };
 }
-
diff --git a/pkgs/development/compilers/ghcs/nix_ghc_pkg_tool.hs b/pkgs/development/compilers/ghcs/nix_ghc_pkg_tool.hs
new file mode 100644
index 00000000000..494b37807fa
--- /dev/null
+++ b/pkgs/development/compilers/ghcs/nix_ghc_pkg_tool.hs
@@ -0,0 +1,48 @@
+-- packages: filepath,Cabal,directory
+{-# OPTIONS_GHC -fglasgow-exts #-}
+module Main where
+import Distribution.InstalledPackageInfo (InstalledPackageInfo (..))
+import Distribution.Package (showPackageId)
+import System.FilePath
+import System.Environment
+import System.Directory
+import System.IO
+import System.Exit
+import Data.List
+
+usage = unlines [
+    " usage a) <app-name> split in_path out_path"
+  , "       b) <app-anme> join out_path"
+  , "This small helper executable servers two purposes:"
+  , "a) split the main package db created by ghc installation into single libs"
+  , "   so that nix can add them piecwise as needed to buildInputs"
+  , "b) merge databases into one single file, so when building a library"
+  , "   we can create one db containing all dependencies passed by GHC_PACKAGE_PATH"
+  , "   I think this is a better solution than patching and mantaining cabal so"
+  , "   that it support GHC_PACKAGE_PATH (not only by accident) ?"
+  ]
+
+mySplit :: (Eq Char) => [Char] ->[[ Char ]]
+mySplit [] = []
+mySplit list = let (l, l') = span (not . (`elem` ":;")) list
+                    in l: mySplit (drop 1 l')
+
+myReadFile f = doesFileExist f >>= \fe ->
+    if fe then readFile f
+          else do hPutStrLn stderr $ "unable to read file " ++ f
+                  exitWith (ExitFailure 1)
+
+main = do
+  args <- getArgs
+  case args of
+    ["split", inFile, outDir] -> do
+      -- prior to 6.9.x (when exactly) this must be InstalledPackageInfo only (not InstalledPackageInfo_ String) 
+      -- (packagedb :: [InstalledPackageInfo_ String] ) <- fmap read $ myReadFile inFile
+      (packagedb :: [InstalledPackageInfo] ) <- fmap read $ myReadFile inFile
+      mapM_ (\pi -> let fn = outDir </> (showPackageId $ package pi) ++ ".conf"
+                    in writeFile fn (show [pi])
+            ) packagedb
+    ["join", outpath] -> do
+      getEnv "GHC_PACKAGE_PATH" >>= mapM myReadFile . nub . mySplit 
+        >>= writeFile outpath . show . concat . map (read :: String -> [InstalledPackageInfo])
+    _ -> putStrLn usage
diff --git a/pkgs/development/compilers/ghcs/splitpackagedb.hs b/pkgs/development/compilers/ghcs/splitpackagedb.hs
deleted file mode 100644
index 0f7ceb0d401..00000000000
--- a/pkgs/development/compilers/ghcs/splitpackagedb.hs
+++ /dev/null
@@ -1,25 +0,0 @@
-{-# OPTIONS_GHC -fglasgow-exts #-}
-module Main where
-import Distribution.InstalledPackageInfo (InstalledPackageInfo (..))
-import Distribution.Package (showPackageId)
-import System.FilePath
-import System.Environment
-
-usage = unlines [
-  "<appname> in outDir"
-  , "reads package db appname"
-  , "and creates a package database for each contained package in outDir"
-  , "" 
-  , "The purpose is to be able to control availible packages to ensure purity in nix."
-  , "Separating each package from the auomated ghc build process is to painful (for me)"
-  ]
-
-main = do
-  args <- getArgs
-  case args of
-    [inFile, outDir] -> do
-      (packagedb :: [InstalledPackageInfo] ) <- fmap read $ readFile inFile
-      mapM_ (\pi -> let fn = outDir </> (showPackageId $ package pi) ++ ".conf"
-                    in writeFile fn (show [pi])
-            ) packagedb
-    _ -> putStrLn usage
diff --git a/pkgs/development/compilers/gwt/builder.sh b/pkgs/development/compilers/gwt/builder.sh
new file mode 100644
index 00000000000..f21b521382b
--- /dev/null
+++ b/pkgs/development/compilers/gwt/builder.sh
@@ -0,0 +1,33 @@
+source $stdenv/setup
+
+tar xfvj $src
+ensureDir $out
+cp -av $name $out
+
+# Create wrapper scripts so that the GWT compiler/host work
+
+libPath="$libstdcpp5/lib:$glib/lib:$gtk/lib:$atk/lib:$pango/lib:$libX11/lib:$libXt/lib:$out/$name/mozilla-1.7.12"
+
+ensureDir $out/bin
+
+cat > $out/bin/gwt-compile <<EOF
+#!/bin/sh
+
+export LD_LIBRARY_PATH=$libPath
+export APPDIR=\`dirname \$0\`
+export LIBXCB_ALLOW_SLOPPY_LOCK=1 # Workaround for bug in Java AWT implementation
+
+java  -cp "\$APPDIR/src:\$APPDIR/bin:$out/$name/gwt-user.jar:$out/$name/gwt-dev-linux.jar" com.google.gwt.dev.GWTCompiler -out "\$APPDIR/www" $@
+EOF
+chmod 755 $out/bin/gwt-compile
+
+cat > $out/bin/gwt-shell <<EOF
+#!/bin/sh
+
+export LD_LIBRARY_PATH=$libPath
+export APPDIR=\`dirname \$0\`
+export LIBXCB_ALLOW_SLOPPY_LOCK=1 # Workaround for bug in Java AWT implementation
+
+java  -cp "\$APPDIR/src:\$APPDIR/bin:$out/$name/gwt-user.jar:$out/$name/gwt-dev-linux.jar" com.google.gwt.dev.GWTShell -out "\$APPDIR/www" $@
+EOF
+chmod 755 $out/bin/gwt-shell
diff --git a/pkgs/development/compilers/gwt/default.nix b/pkgs/development/compilers/gwt/default.nix
new file mode 100644
index 00000000000..50f05e81419
--- /dev/null
+++ b/pkgs/development/compilers/gwt/default.nix
@@ -0,0 +1,14 @@
+{stdenv, fetchurl, glib, gtk, pango, atk, libX11, libXt, libstdcpp5}:
+
+stdenv.mkDerivation {
+  name = "gwt-linux-1.4.61";
+  builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://google-web-toolkit.googlecode.com/files/gwt-linux-1.4.61.tar.bz2;
+    md5 = "5aa5d630716817f7cf22dc2a36c0fcbd";
+  };
+
+  inherit glib gtk pango atk libX11 libXt libstdcpp5;
+  buildInputs = [glib gtk pango atk libX11 libXt libstdcpp5];
+}
diff --git a/pkgs/development/compilers/java-front/builder.sh b/pkgs/development/compilers/java-front/builder.sh
new file mode 100644
index 00000000000..0177abcccea
--- /dev/null
+++ b/pkgs/development/compilers/java-front/builder.sh
@@ -0,0 +1,4 @@
+source $stdenv/setup
+
+configureFlags="--with-aterm=$aterm --with-sdf=$sdf --with-strategoxt=$strategoxt"
+genericBuild
diff --git a/pkgs/development/compilers/java-front/default.nix b/pkgs/development/compilers/java-front/default.nix
new file mode 100644
index 00000000000..fc60e72a562
--- /dev/null
+++ b/pkgs/development/compilers/java-front/default.nix
@@ -0,0 +1,14 @@
+{stdenv, fetchurl, aterm, sdf, strategoxt, pkgconfig}:
+
+stdenv.mkDerivation {
+  name = "java-front-0.9";
+  builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://buildfarm.st.ewi.tudelft.nl/releases/strategoxt/java-front-0.9pre17376-qi43zwhy/java-front-0.9pre17376.tar.gz;
+    md5 = "fec70158b110c77a2e5db29676438029";
+  };
+
+  inherit aterm sdf strategoxt;
+  buildInputs = [pkgconfig aterm sdf strategoxt];
+}
diff --git a/pkgs/development/compilers/jdk/builder.sh b/pkgs/development/compilers/jdk/builder.sh
index 1b61d548c1b..71dd6c433f6 100644
--- a/pkgs/development/compilers/jdk/builder.sh
+++ b/pkgs/development/compilers/jdk/builder.sh
@@ -1,3 +1,4 @@
+buildInputs="$unzip"
 source $stdenv/setup
 
 src=$filename.bin
diff --git a/pkgs/development/compilers/jdk/default-5.nix b/pkgs/development/compilers/jdk/default-5.nix
new file mode 100644
index 00000000000..9fb52378b3f
--- /dev/null
+++ b/pkgs/development/compilers/jdk/default-5.nix
@@ -0,0 +1,9 @@
+{stdenv, fetchurl, unzip}: 
+
+if stdenv.system == "i686-linux" || stdenv.system == "x86_64-linux"
+  then
+    (import ./jdk5-sun-linux.nix) {
+      inherit stdenv fetchurl unzip;
+    }
+  else
+    abort "the Java 5 SDK is not supported on this platform"
diff --git a/pkgs/development/compilers/jdk/jdk5-sun-linux.nix b/pkgs/development/compilers/jdk/jdk5-sun-linux.nix
new file mode 100644
index 00000000000..6a15b1f9ec9
--- /dev/null
+++ b/pkgs/development/compilers/jdk/jdk5-sun-linux.nix
@@ -0,0 +1,23 @@
+/**
+ * This Nix expression requires the user to download the j2sdk
+ * distribution to /tmp. Please obtain jdk-1_5_0_14-linux-i586.bin
+ * from java.sun.com by hand and place it in /tmp. Blame Sun, not me.
+ *
+ * Note that this is not necessary if someone has already pushed a
+ * binary.
+ */
+{stdenv, fetchurl, unzip}: 
+
+assert stdenv.system == "i686-linux" || stdenv.system == "x86_64-linux";
+
+stdenv.mkDerivation {
+  name = "jdk-1.5.0_14";
+  filename = "jdk-1_5_0_14";
+  dirname = "jdk1.5.0_14";
+  builder = ./builder.sh;
+  pathname = if stdenv.system == "x86_64-linux" then "/tmp/jdk-1_5_0_14-linux-amd64.bin" else "/tmp/jdk-1_5_0_14-linux-i586.bin";
+  md5 = if stdenv.system == "x86_64-linux" then "9dc74d939dd42988280f2c22ab9521bf" else "32df8f2be09c3a0f39da1b3869164b55";
+  
+  stdenv = stdenv;
+  inherit unzip;
+}
diff --git a/pkgs/development/compilers/jdk/jdk6-linux.nix b/pkgs/development/compilers/jdk/jdk6-linux.nix
index 17a23c981e0..0c285c4526e 100644
--- a/pkgs/development/compilers/jdk/jdk6-linux.nix
+++ b/pkgs/development/compilers/jdk/jdk6-linux.nix
@@ -14,18 +14,18 @@ assert pluginSupport -> libstdcpp5 != null;
 
 (stdenv.mkDerivation ({
   name =
-    if installjdk then "jdk-1.6.0_3" else "jre-1.6.0_3";
+    if installjdk then "jdk-1.6.0_4" else "jre-1.6.0_4";
 
   src =
     if stdenv.system == "i686-linux" then
       fetchurl {
-        url = http://download.java.net/dlj/binaries/jdk-6u3-dlj-linux-i586.bin;
-        sha256 = "5c44208fbd5f90b3e6a0692ed9e1e98f5feb0c88aa0cfae5186dddb1f05f731b";
+        url = http://download.java.net/dlj/binaries/jdk-6u4-dlj-linux-i586.bin;
+        sha256 = "955186f497a50106cd1788fcaf032eedc560985826c8a6c3cb7ab43220cad23c";
       }
     else if stdenv.system == "x86_64-linux" then
       fetchurl {
-        url = http://download.java.net/dlj/binaries/jdk-6u3-dlj-linux-amd64.bin;
-        sha256 = "8bc80ea1bf739674c1cacdfba9987a4d15adb54f4b1462a0b48b79815f56b311";
+        url = http://download.java.net/dlj/binaries/jdk-6u4-dlj-linux-amd64.bin;
+        sha256 = "be0e21402a79c5b6cd6c96d34451bcc365619cd063930f3ca1c1abe2ee5dbf43";
       }
     else
       abort "jdk requires i686-linux or x86_64 linux";
diff --git a/pkgs/development/compilers/ocaml/ocaml-3.08.0.nix b/pkgs/development/compilers/ocaml/3.08.0.nix
index d063fead4a5..6d4b4ca616c 100644
--- a/pkgs/development/compilers/ocaml/ocaml-3.08.0.nix
+++ b/pkgs/development/compilers/ocaml/3.08.0.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl, x11}:
+args: with args;
 
 stdenv.mkDerivation {
   name = "ocaml-3.08.0";
diff --git a/pkgs/development/compilers/ocaml/ocaml-3.09.1.nix b/pkgs/development/compilers/ocaml/3.09.1.nix
index 996012d6b27..6e9922ccc36 100644
--- a/pkgs/development/compilers/ocaml/ocaml-3.09.1.nix
+++ b/pkgs/development/compilers/ocaml/3.09.1.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl, x11, ncurses}:
+args: with args;
 
 stdenv.mkDerivation {
   name = "ocaml-3.09.1";
diff --git a/pkgs/development/compilers/ocaml/3.10.0.nix b/pkgs/development/compilers/ocaml/3.10.0.nix
new file mode 100644
index 00000000000..a26175755b5
--- /dev/null
+++ b/pkgs/development/compilers/ocaml/3.10.0.nix
@@ -0,0 +1,23 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "ocaml-3.10.0";
+	src = fetchurl {
+		url = "http://caml.inria.fr/pub/distrib/ocaml-3.10/${name}.tar.bz2";
+		sha256 = "1ihmx1civ78s7k2hfc05z1s9vbyx2qw7fg8lnbxnfd6zxkk8878d";
+	};
+	prefixKey = "-prefix ";
+	configureFlags = ["-no-tk" "-x11lib" x11];
+	buildFlags = "world bootstrap world.opt";
+	buildInputs = [x11 ncurses];
+	installTargets = "install installopt"; 
+	patchPhase = "
+	CAT=$(type -tp cat)
+	sed -e \"s@/bin/cat@\${CAT}@\" -i config/auto-aux/sharpbang
+	";
+
+	meta = {
+		homepage = http://caml.inria.fr/ocaml;
+		license = "QPL, LGPL2 (library part)";
+		desctiption = "Most popular variant of the Caml language";
+	};
+}
diff --git a/pkgs/development/compilers/ocaml/default.nix b/pkgs/development/compilers/ocaml/default.nix
index 44603f95764..837a685198b 100644
--- a/pkgs/development/compilers/ocaml/default.nix
+++ b/pkgs/development/compilers/ocaml/default.nix
@@ -1 +1,7 @@
-import ./ocaml-3.09.1.nix
+args:
+args.stdenv.lib.listOfListsToAttrs [
+	[ "3.08.0" (import ./3.08.0.nix args) ]
+	[ "3.09.1" (import ./3.09.1.nix args) ]
+	[ "3.10.0" (import ./3.10.0.nix args) ]
+	[ "default" (import ./3.09.1.nix args) ]
+]
diff --git a/pkgs/development/compilers/qi/9.1.nix b/pkgs/development/compilers/qi/9.1.nix
index 661bb85e798..3a1a4f37886 100644
--- a/pkgs/development/compilers/qi/9.1.nix
+++ b/pkgs/development/compilers/qi/9.1.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 		fetchurl {
 			url = http://www.lambdassociates.org/Download/Qi9.1.zip;
@@ -8,6 +8,7 @@ args : with args;
 		buildInputs = [ unzip clisp];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 let 
 	shell=stdenv.shell;
 in
@@ -28,7 +29,7 @@ in
 stdenv.mkDerivation rec {
 	name = "Qi-"+version;
 	builder = writeScript (name + "-builder")
-		(textClosure [allBuild doForceShare doPropagate]);
+		(textClosure localDefs [allBuild doForceShare doPropagate]);
 	meta = {
 		description = "
 		Qi - next generation on top of Common Lisp.
diff --git a/pkgs/development/compilers/qi/default.nix b/pkgs/development/compilers/qi/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/development/compilers/qi/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/development/compilers/roadsend/default.nix b/pkgs/development/compilers/roadsend/default.nix
new file mode 100644
index 00000000000..d7c693b6864
--- /dev/null
+++ b/pkgs/development/compilers/roadsend/default.nix
@@ -0,0 +1,33 @@
+args:
+let edf = args.lib.enableDisableFeature; in
+( args.mkDerivationByConfiguration {
+    flagConfig = {
+      mandatory = { buildInputs = ["bigloo" "curl"]; };
+    } // edf "pcre" "pcre" { } #support pcre extension [default=check]
+      // edf "fcgi" "fcgi" { } #support FastCGI web backend [default=check]
+      // edf "xml" "xml" { pass ="libxml2"; } #support xml extension [default=check]
+      // edf "mysql" "mysql" { pass = "mysql"; } #support mysql extension [default=check]
+      #// edf "sqlite3=[ARG]" "sqlite3=[ARG]" { } [>use SQLite 3 library [default=yes], optionally
+                                #specify the prefix for sqlite3 library
+      // edf "odbc" "odbc" { } #support ODBC extension [default=check]
+      // edf "gtk" "gtk" { } #support PHP-GTK extension [default=no]
+      // edf "gtk2" "gtk2" { }; #support PHP-GTK 2 extension [default=no]
+
+    optionals = [ "libxml2" "gettext" ];
+    extraAttrs = co : {
+      name = "roadsend-2.9.3";
+
+      src = args.fetchurl {
+        url = "http://code.roadsend.com/snaps/roadsend-php-2.9.4.tar.bz2";
+        sha256 = "0nw7rvrrwkss5cp6ws0m3q63q1mcyy27s8yjhy7kn508db1rgl9x";
+      };
+
+    meta = { 
+      description = "roadsend PHP -> C compiler";
+      homepage = http://www.roadsend.com;
+      # you can choose one of the following licenses: 
+      # Runtime license is LPGL 2.1
+      license = ["GPL2"];
+    };
+  };
+} ) args
diff --git a/pkgs/development/compilers/strategoxt/strategoxt-0.17.nix b/pkgs/development/compilers/strategoxt/strategoxt-0.17.nix
new file mode 100644
index 00000000000..fa56d6e35e6
--- /dev/null
+++ b/pkgs/development/compilers/strategoxt/strategoxt-0.17.nix
@@ -0,0 +1,15 @@
+{stdenv, fetchurl, aterm, sdf, pkgconfig}:
+
+stdenv.mkDerivation {
+
+  name = "strategoxt-0.17";
+  builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://buildfarm.st.ewi.tudelft.nl/releases/strategoxt/strategoxt-0.17M3pre17099/strategoxt-0.17M3pre17099.tar.gz;
+    md5 = "fc9bc3cb6d80bfa6ee1fadd2dd828c72";
+  };
+
+  inherit aterm sdf;
+  buildInputs = [pkgconfig aterm sdf];
+}
diff --git a/pkgs/development/compilers/webdsl/builder.sh b/pkgs/development/compilers/webdsl/builder.sh
new file mode 100644
index 00000000000..d77094a91b0
--- /dev/null
+++ b/pkgs/development/compilers/webdsl/builder.sh
@@ -0,0 +1,8 @@
+source $stdenv/setup
+
+configureFlags="--with-aterm=$aterm --with-sdf=$sdf --with-strategoxt=$strategoxt"
+genericBuild
+
+# Replace /bin/bash in WebDSL script (maybe there is a better solution?)
+
+sed -i -e "s|#!/bin/bash|#!/bin/sh|" $out/bin/webdsl
diff --git a/pkgs/development/compilers/webdsl/default.nix b/pkgs/development/compilers/webdsl/default.nix
new file mode 100644
index 00000000000..da961cbf2f6
--- /dev/null
+++ b/pkgs/development/compilers/webdsl/default.nix
@@ -0,0 +1,14 @@
+{stdenv, fetchurl, aterm, sdf, strategoxt, pkgconfig, javafront}:
+
+stdenv.mkDerivation {
+  name = "webdsl-7.12pre876";
+  builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://buildfarm.st.ewi.tudelft.nl/releases/strategoxt/webdsl-7.12pre876-g60njq3p/webdsl-7.12pre876.tar.gz;
+    md5 = "7cd8709b02e03da74d90f8f8388e8d01";
+  };
+
+  inherit aterm sdf strategoxt javafront;
+  buildInputs = [pkgconfig aterm sdf strategoxt javafront];
+}
diff --git a/pkgs/development/guile-modules/guile-lib/default.nix b/pkgs/development/guile-modules/guile-lib/default.nix
new file mode 100644
index 00000000000..cc26c458a06
--- /dev/null
+++ b/pkgs/development/guile-modules/guile-lib/default.nix
@@ -0,0 +1,38 @@
+{stdenv, fetchurl, guile}:
+
+stdenv.mkDerivation rec {
+  name = "guile-lib-0.1.6";
+  src = fetchurl {
+    url = "http://download.gna.org/guile-lib/" + name + ".tar.gz";
+    sha256 = "827744c7954078f1f37e0bf70252ec70b4d60c1482a3542a49bd09723cf65d12";
+  };
+
+  buildInputs = [guile];
+
+  postInstall = ''
+    # Remove modules already provided by Guile.
+    if "${guile}/bin/guile" -c '(use-modules (srfi srfi-34))'
+    then
+	rm -f "$out/share/guile/site/srfi/srfi-34.scm"
+    fi
+    if "${guile}/bin/guile" -c '(use-modules (srfi srfi-35))'
+    then
+	rm -f "$out/share/guile/site/srfi/srfi-35.scm"
+    fi
+
+    # Make modules available under `/lib/site-guile' to comply with Guile's
+    # setup-hook.
+    mkdir -p "$out/lib/site-guile"
+    for f in "$out/share/guile/site"/*
+    do
+      ln -s "$f" "$out/lib/site-guile/"
+    done
+  '';
+
+  meta = {
+    description = ''Guile-Library, a set of various useful
+                    Guile Scheme modules.'';
+    homepage = http://home.gna.org/guile-lib/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/development/interpreters/clisp/builder.sh b/pkgs/development/interpreters/clisp/builder.sh
deleted file mode 100644
index 89731fbb987..00000000000
--- a/pkgs/development/interpreters/clisp/builder.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-source $stdenv/setup || exit 1
-
-set -e
-
-tar jxvf $src
-cd clisp-*
-sed -e 's@/bin/pwd@'${coreutils}'&@' -i src/clisp-link.in
-./configure --with-readline builddir --build \
-	--prefix=$out --with-dynamic-ffi \
-	--with-module=clx/new-clx --with-module=i18n \
-	--with-module=bindings/glibc \
-	--with-module=pcre --with-module=rawsock \
-	--with-module=readline --with-module=syscalls \
-	--with-module=wildcard --with-modules=zlib ||
-	for i in $(find . -name config.log ); do
-		echo -------
-		echo $i;
-		echo ===
-		cat $i;
-	done > /tmp/clisp-config-log
-cd builddir
-make install
diff --git a/pkgs/development/interpreters/clisp/default.nix b/pkgs/development/interpreters/clisp/default.nix
index 919862378a1..5095bf985d4 100644
--- a/pkgs/development/interpreters/clisp/default.nix
+++ b/pkgs/development/interpreters/clisp/default.nix
@@ -1,15 +1,36 @@
-args:
-args.stdenv.mkDerivation {
-  name = "clisp-2.41a";
-  builder = ./builder.sh;
-  src = args.
+args: with args;
+stdenv.mkDerivation rec {
+  v = "2.43";
+  name = "clisp-${v}";
+  src =
 	fetchurl {
-		url = mirror://gnu/clisp/release/2.41/clisp-2.41a.tar.bz2;
-		sha256 = "08z35bni42dhlqlsg5rr5p025961fl82gqvaadrf0jh20jdqspqy";
+		url = "mirror://gnu/clisp/release/${v}/${name}.tar.bz2";
+		sha256 = "10qyn6wccnayf1cyvrcanay6c6laar6z1r608w7ijp6nb763q8dm";
 	};
 
-  inherit (args) libsigsegv gettext coreutils;
-  buildInputs = (with args;
- [libsigsegv gettext ncurses readline libX11 libXau
-	libXt pcre zlib]);
+  inherit libsigsegv gettext coreutils;
+  buildInputs = [libsigsegv gettext ncurses readline libX11 libXau
+	libXt pcre zlib];
+  
+  patchPhase = ''
+  sed -i 's@/bin/pwd@${coreutils}&@' src/clisp-link.in
+  find . -type f | xargs sed -e 's/-lICE/-lXau &/' -i
+  '';
+
+  configureFlags = "--with-readline builddir --with-dynamic-ffi
+  --with-module=clx/new-clx --with-module=i18n --with-module=bindings/glibc
+  --with-module=pcre --with-module=rawsock --with-module=readline
+  --with-module=syscalls --with-module=wildcard --with-module=zlib";
+
+  preBuild = "cd builddir";
+
+  NIX_CFLAGS_COMPILE="-O0";
+
+  # TODO : make mod-check fails
+  doCheck = 1;
+
+  meta = {
+	  description = "ANSI Common Lisp Implementation";
+	  homepage = http://clisp.cons.org;
+  };
 }
diff --git a/pkgs/development/interpreters/erlang/R11B-5.nix b/pkgs/development/interpreters/erlang/R11B-5.nix
new file mode 100644
index 00000000000..68cc3b5f2b5
--- /dev/null
+++ b/pkgs/development/interpreters/erlang/R11B-5.nix
@@ -0,0 +1,12 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "erlang-" + version;
+  src = fetchurl {
+    url = http://www.erlang.org/download/otp_src_R11B-5.tar.gz;
+    md5 = "96acec41da87d6ee0ef18e1aab36ffdd";
+  };
+  buildInputs = [perl gnum4 ncurses openssl];
+  patchPhase = '' sed -i "s@/bin/rm@rm@" lib/odbc/configure erts/configure '';
+  configureFlags = "--with-ssl=${openssl}";
+}
diff --git a/pkgs/development/interpreters/erlang/R12B-1.nix b/pkgs/development/interpreters/erlang/R12B-1.nix
new file mode 100644
index 00000000000..37ebdbf6ab8
--- /dev/null
+++ b/pkgs/development/interpreters/erlang/R12B-1.nix
@@ -0,0 +1,12 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "erlang-" + version;
+  src = fetchurl {
+    url = "http://www.erlang.org/download/otp_src_" + version + ".tar.gz";
+    sha256 = "16w7snhbjzwiywppsp04yiy2bkncff8pf4i643kqzkqx578jhaqz";
+  };
+  buildInputs = [perl gnum4 ncurses openssl];
+  patchPhase = '' sed -i "s@/bin/rm@rm@" lib/odbc/configure erts/configure '';
+  configureFlags = "--with-ssl=${openssl}";
+}
diff --git a/pkgs/development/interpreters/guile/default.nix b/pkgs/development/interpreters/guile/default.nix
index b643d88a3a9..9aaa796d6b2 100644
--- a/pkgs/development/interpreters/guile/default.nix
+++ b/pkgs/development/interpreters/guile/default.nix
@@ -1,10 +1,26 @@
 args: with args; 
-stdenv.mkDerivation {
-  name = "guile-1.6.7";
+
+stdenv.mkDerivation rec {
+  name = "guile-1.8.4";
   src = fetchurl {
-		url = ftp://ftp.gnu.org/gnu/guile/guile-1.8.2.tar.gz;
-		sha256 = "03kn1ia4s7l24zl2sfbrns6fs3nc9cw2pzsqx8y7wwr80b1nfxhz";
-	};
+    url = "ftp://ftp.gnu.org/gnu/guile/" + name + ".tar.gz";
+    sha256 = "1cz1d4n6vzw0lfsvplsiarwqk675f12j596dzfv0h5r9cljpc0ya";
+  };
+
+  buildInputs = [ makeWrapper ];
+  propagatedBuildInputs = [readline libtool gmp gawk];
+
+  postInstall = ''
+    wrapProgram $out/bin/guile-snarf --prefix PATH : "${gawk}/bin"
+  '';
+
+  setupHook = ./setup-hook.sh;
 
-  propagatedBuildInputs = [readline libtool gmp];
+  meta = {
+    description = ''GNU Guile is an interpreter for the Scheme
+                    programming language, packaged as a library that
+		    can be embedded into programs to make them extensible.'';
+    homepage = http://www.gnu.org/software/guile/;
+    license = "LGPL";
+  };
 }
diff --git a/pkgs/development/interpreters/guile/setup-hook.sh b/pkgs/development/interpreters/guile/setup-hook.sh
new file mode 100644
index 00000000000..114bc4e87cc
--- /dev/null
+++ b/pkgs/development/interpreters/guile/setup-hook.sh
@@ -0,0 +1,8 @@
+addGuileLibPath () {
+    if test -d "$1/lib/site-guile"
+    then
+        export GUILE_LOAD_PATH="${GUILE_LOAD_PATH}${GUILE_LOAD_PATH:+:}$1/lib/site-guile"
+    fi
+}
+
+envHooks=(${envHooks[@]} addGuileLibPath)
diff --git a/pkgs/development/interpreters/lua-5/default.nix b/pkgs/development/interpreters/lua-5/default.nix
index 30ab0311136..6408457e2a0 100644
--- a/pkgs/development/interpreters/lua-5/default.nix
+++ b/pkgs/development/interpreters/lua-5/default.nix
@@ -3,7 +3,7 @@
 stdenv.mkDerivation {
   name = "lua-5.1.2";
   src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/lua-5.1.2.tar.gz;
+    url = http://www.lua.org/ftp/lua-5.1.2.tar.gz;
     sha256 = "17ixifwgjva5592s2rn1ki56wa7hgw0z210r4bcx5lv8zv39iw2w";
   };
   buildFlags = "linux"; # TODO: support for non-linux systems
diff --git a/pkgs/development/interpreters/perl/perl-5.10.nix b/pkgs/development/interpreters/perl/perl-5.10.nix
new file mode 100644
index 00000000000..01f314c19a4
--- /dev/null
+++ b/pkgs/development/interpreters/perl/perl-5.10.nix
@@ -0,0 +1,21 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "perl-5.10.0";
+
+  builder = ./builder.sh;
+  src = fetchurl {
+    url = http://www.cpan.org/src/perl-5.10.0.tar.gz;
+    sha256 = "0bivbz15x02m02gqs6hs77cgjr2msfrhnvp5xqk359jg6w6llill";
+  };
+
+  # This patch does the following:
+  # 1) Do use the PATH environment variable to find the `pwd' command.
+  #    By default, Perl will only look for it in /lib and /usr/lib.
+  #    !!! what are the security implications of this?
+  # 2) Force the use of <errno.h>, not /usr/include/errno.h, on Linux
+  #    systems.  (This actually appears to be due to a bug in Perl.)
+  patches = [./no-sys-dirs.patch];
+
+  setupHook = ./setup-hook.sh;
+}
diff --git a/pkgs/development/interpreters/perl/setup-hook.sh b/pkgs/development/interpreters/perl/setup-hook.sh
index 6903bddd419..70ce2cf8b46 100644
--- a/pkgs/development/interpreters/perl/setup-hook.sh
+++ b/pkgs/development/interpreters/perl/setup-hook.sh
@@ -1,5 +1,5 @@
 addPerlLibPath () {
-	addToSearchPath PERL5LIB /lib/site_perl "" $1
+    addToSearchPath PERL5LIB /lib/site_perl "" $1
 }
 
 envHooks=(${envHooks[@]} addPerlLibPath)
diff --git a/pkgs/development/interpreters/php_configurable/default.nix b/pkgs/development/interpreters/php_configurable/default.nix
index 9a1eeeb67a3..d18a2cf2b05 100644
--- a/pkgs/development/interpreters/php_configurable/default.nix
+++ b/pkgs/development/interpreters/php_configurable/default.nix
@@ -1,3 +1,16 @@
+/*  TODO check security issues such as :
++--------------------------------------------------------------------+
+|                        *** WARNING ***                             |
+|                                                                    |
+| You will be compiling the CGI version of PHP without any           |
+| redirection checking.  By putting this cgi binary somewhere in     |
+| your web space, users may be able to circumvent existing .htaccess |
+| security by loading files directly through the parser.  See        |
+| http://www.php.net/manual/security.php for more details.           |
+*/
+
+let version = "5.2.5"; in
+
 args:
 ( args.mkDerivationByConfiguration {
     flagConfig = {
@@ -394,10 +407,11 @@ args:
 
 # SAPI modules:
           apxs2        =      { cfgOption = "--with-apxs2=\$apacheHttpd/bin/apxs";
-                                pass = { inherit (args) apacheHttpd; }; };
+                                pass = "apacheHttpd"; };
 
 # Extensions 
 
+          zlib          =     { cfgOption = "--with-zlib=${args.zlib}"; pass = "zlib"; };
 
           libxml2       =     { cfgOption = "--with-libxml-dir=\$libxml2";
                                 pass = { inherit (args) libxml2; }; 
@@ -405,6 +419,8 @@ args:
           no_libxml2    =     { cfgOption =  "--disable-libxml";
                               };
 
+          postgresql   =      { cfgOption = "--with-pgsql=\$postgresql";
+                                pass = { inherit (args) postgresql;}; };
           mysql        =      { cfgOption = "--with-mysql=\$mysql";
                                 pass = { inherit (args) mysql;}; };
 
@@ -425,43 +441,82 @@ args:
                                       If unspecified, the default locations are searched
           */
 
+          /*
+             Building xdebug withing php to be able to add the parameters to the ini file.. Ther should be a better way
+            meta = { 
+                    description = "debugging support for PHP";
+                    homepage = http://xdebug.org;
+                    license = "based on the PHP license - as is";
+                    };
+          */
+          xdebug = { buildInputs = [ "automake" "autoconf" ];  
+                     pass = { xdebug_src = args.fetchurl {
+                          name = "xdebug-2.0.2.tar.gz";
+                          url = "http://xdebug.org/link.php?url=xdebug202";
+                          sha256 = "1h0bxvf8krr203fmk1k7izrrr81gz537xmd3pqh4vslwdlbhrvic";
+                   };};};
+
+
     };
 
   defaults = [ "mysql" "mysqli" "pdo_mysql" "libxml2" "apxs2" ];
-  optionals = [ "libxml2" "gettext" ];
+  optionals = [ "libxml2" "gettext" "postgresql" "zlib"];
 
   # Don't konw wether they should be default.. I use them - Marc
 
 
   extraAttrs = co : {
-    name = "php_configurable-5.2.4";
-
-    buildInputs = ( args.lib.getAttr [ "phpIncludes" ] [] args );
+    name = "php_configurable-${version}";
 
+    buildInputs = ( args.lib.getAttr [ "phpIncludes" ] [] args ) ++ co.buildInputs;
 
-    configurePhase = 
-      "
-      iniFile=\$out/etc/\$name.ini
-      [[ -z \"\$libxml2\" ]] || export PATH=\$PATH:\$libxml2/bin
-      ./configure --with-config-file-path=\$iniFile --prefix=\$out " + co.configureFlags;
+    configurePhase = ''
+      iniFile=$out/etc/$name.ini
+      [[ -z "$libxml2" ]] || export PATH=$PATH:$libxml2/bin
+      ./configure --with-config-file-scan-dir=/etc --with-config-file-path=$iniFile --prefix=$out ${co.configureFlags}
+      echo configurePhase end
+    '';
 
-    installPhase = "
+    installPhase = ''
       unset installPhase; installPhase;
-      cp php.ini-recommended $\iniFile
-      echo \"include_path=.\$PATH_DELIMITER\$out/lib/php\$PATH_DELIMITER\$PHP_INCLUDES\" > \$iniFile
-    ";
+      cp php.ini-recommended $iniFile
+
+      # Now Let's build xdebug if flag has been given 
+      # TODO I think there are better paths than the given below
+      if [ -n $flag_set_xdebug ]; then
+        PATH=$PATH:$out/bin
+        tar xfz $xdebug_src; 
+        cd xdebug*
+        phpize
+        ./configure --prefix=$out
+        make
+        ensureDir $out/lib; cp modules/xdebug.so $out/lib
+        cat >> $iniFile << EOF
+          zend_extension="$out/lib/xdebug.so"
+          zend_extension_ts="$out/lib/xdebug.so"
+          zend_extension_debug="$out/lib/xdebug.so"
+          xdebug.remote_enable=true
+          xdebug.remote_host=127.0.0.1
+          xdebug.remote_port=9000
+          xdebug.remote_handler=dbgp
+          xdebug.profiler_enable=0
+          xdebug.profiler_output_dir="/tmp/xdebug"
+          xdebug.remote_mode=req
+        EOF
+      fi
+    '';
 
     src = args.fetchurl {
-      url = http://de.php.net/get/php-5.2.4.tar.bz2/from/this/mirror;
-      sha256 = "1h513j7crz08n7rlh8v7cvxfzisj87mvvyfrkiaa76v1wicm4bsh";
-      name = "php-5.2.4.tar.bz2";
+      url = "http://nl.php.net/get/php-${version}.tar.bz2/from/this/mirror";
+      sha256 = "18xv961924rkk66gdjcmk1mzbzgp2srbiq5jvbgyn6ahvxq1xb2w";
+      name = "php-${version}.tar.bz2";
     };
 
     meta = { 
-        description = "The PHP language runtime engine"; # : CLI, CGI and Apache2 SAPIs ? as well TODO 
-        homepage = http://www.php.net/;
-        license = "PHP-3";
-      };
+      description = "The PHP language runtime engine"; # : CLI, CGI and Apache2 SAPIs ? as well TODO 
+      homepage = http://www.php.net/;
+      license = "PHP-3";
+    };
 
     patches = [./fix.patch];
   };
diff --git a/pkgs/development/interpreters/pyrex/0.9.6.nix b/pkgs/development/interpreters/pyrex/0.9.6.nix
index 7053f949a43..1b11e8efe36 100644
--- a/pkgs/development/interpreters/pyrex/0.9.6.nix
+++ b/pkgs/development/interpreters/pyrex/0.9.6.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/oldtar/Pyrex-0.9.6.tar.gz;
@@ -8,10 +8,11 @@ args : with args;
 		buildInputs = [python];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 stdenv.mkDerivation rec {
 	name = "Pyrex-"+version;
 	builder = writeScript (name + "-builder")
-		(textClosure [installPythonPackage doForceShare]);
+		(textClosure localDefs [installPythonPackage doForceShare]);
 	meta = {
 		description = "
 	Python package compiler or something like that.	
diff --git a/pkgs/development/interpreters/pyrex/default.nix b/pkgs/development/interpreters/pyrex/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/development/interpreters/pyrex/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/development/interpreters/python/2.4.nix b/pkgs/development/interpreters/python/2.4.nix
new file mode 100644
index 00000000000..726d2ac4aa9
--- /dev/null
+++ b/pkgs/development/interpreters/python/2.4.nix
@@ -0,0 +1,52 @@
+{stdenv, fetchurl, zlib ? null, zlibSupport ? true, bzip2}:
+
+assert zlibSupport -> zlib != null;
+
+with stdenv.lib;
+
+let
+
+  buildInputs =
+    optional (stdenv ? gcc && stdenv.gcc.libc != null) stdenv.gcc.libc ++
+    [bzip2] ++ 
+    optional zlibSupport zlib;
+
+in
+
+stdenv.mkDerivation {
+  name = "python-2.4.4";
+  
+  src = fetchurl {
+    url = http://www.python.org/ftp/python/2.4.4/Python-2.4.4.tar.bz2;
+    md5 = "0ba90c79175c017101100ebf5978e906";
+  };
+
+  patches = [
+    # Look in C_INCLUDE_PATH and LIBRARY_PATH for stuff.
+    ./search-path.patch
+  ];
+  
+  inherit buildInputs;
+  C_INCLUDE_PATH = concatStringsSep ":" (map (p: "${p}/include") buildInputs);
+  LIBRARY_PATH = concatStringsSep ":" (map (p: "${p}/lib") buildInputs);
+  
+  configureFlags = "--enable-shared";
+  
+  preConfigure = "
+    # Purity.
+    for i in /usr /sw /opt /pkg; do 
+      substituteInPlace ./setup.py --replace $i /no-such-path
+    done
+  ";
+  
+  postInstall = "
+    ensureDir $out/nix-support
+    cp ${./setup-hook.sh} $out/nix-support/setup-hook
+    rm -rf $out/lib/python2.4/test
+  ";
+
+  passthru = {
+    inherit zlibSupport;
+    libPrefix = "python2.4";
+  };
+}
diff --git a/pkgs/development/interpreters/python/2.5/default.nix b/pkgs/development/interpreters/python/2.5/default.nix
index 9a84bfa7ff8..161584ee707 100644
--- a/pkgs/development/interpreters/python/2.5/default.nix
+++ b/pkgs/development/interpreters/python/2.5/default.nix
@@ -30,7 +30,7 @@ stdenv.mkDerivation {
   C_INCLUDE_PATH = concatStringsSep ":" (map (p: "${p}/include") buildInputs);
   LIBRARY_PATH = concatStringsSep ":" (map (p: "${p}/lib") buildInputs);
   
-  configureFlags = "--enable-shared";
+  configureFlags = "--enable-shared --with-wctype-functions";
   
   preConfigure = "
     # Purity.
diff --git a/pkgs/development/interpreters/python/2.5/setup-hook.sh b/pkgs/development/interpreters/python/2.5/setup-hook.sh
index 27ad6226030..a11f8cbb484 100644
--- a/pkgs/development/interpreters/python/2.5/setup-hook.sh
+++ b/pkgs/development/interpreters/python/2.5/setup-hook.sh
@@ -1,5 +1,5 @@
 addPythonPath() {
-	addToSearchPathWithCustomDelimiter : PYTHONPATH /lib/python2.5/site-packages "" $1
+    addToSearchPathWithCustomDelimiter : PYTHONPATH /lib/python2.5/site-packages "" $1
 }
 
 toPythonPath() {
diff --git a/pkgs/development/interpreters/python/default.nix b/pkgs/development/interpreters/python/default.nix
index 726d2ac4aa9..af90018870f 100644
--- a/pkgs/development/interpreters/python/default.nix
+++ b/pkgs/development/interpreters/python/default.nix
@@ -1,52 +1,6 @@
-{stdenv, fetchurl, zlib ? null, zlibSupport ? true, bzip2}:
-
-assert zlibSupport -> zlib != null;
-
-with stdenv.lib;
-
-let
-
-  buildInputs =
-    optional (stdenv ? gcc && stdenv.gcc.libc != null) stdenv.gcc.libc ++
-    [bzip2] ++ 
-    optional zlibSupport zlib;
-
-in
-
-stdenv.mkDerivation {
-  name = "python-2.4.4";
-  
-  src = fetchurl {
-    url = http://www.python.org/ftp/python/2.4.4/Python-2.4.4.tar.bz2;
-    md5 = "0ba90c79175c017101100ebf5978e906";
-  };
-
-  patches = [
-    # Look in C_INCLUDE_PATH and LIBRARY_PATH for stuff.
-    ./search-path.patch
-  ];
-  
-  inherit buildInputs;
-  C_INCLUDE_PATH = concatStringsSep ":" (map (p: "${p}/include") buildInputs);
-  LIBRARY_PATH = concatStringsSep ":" (map (p: "${p}/lib") buildInputs);
-  
-  configureFlags = "--enable-shared";
-  
-  preConfigure = "
-    # Purity.
-    for i in /usr /sw /opt /pkg; do 
-      substituteInPlace ./setup.py --replace $i /no-such-path
-    done
-  ";
-  
-  postInstall = "
-    ensureDir $out/nix-support
-    cp ${./setup-hook.sh} $out/nix-support/setup-hook
-    rm -rf $out/lib/python2.4/test
-  ";
-
-  passthru = {
-    inherit zlibSupport;
-    libPrefix = "python2.4";
-  };
-}
+args:
+args.stdenv.lib.listOfListsToAttrs [
+	[ "default"  (import ./2.4.nix args) ]
+	[ "2.4"  (import ./2.4.nix args) ]
+	[ "2.5" (import ./2.5 args) ]
+]
diff --git a/pkgs/development/interpreters/tcl/default.nix b/pkgs/development/interpreters/tcl/default.nix
index 0fce5d3236a..1401757c267 100644
--- a/pkgs/development/interpreters/tcl/default.nix
+++ b/pkgs/development/interpreters/tcl/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "tcl-8.4.13";
+  name = "tcl-8.4.16";
   builder = ./builder.sh;
   src = fetchurl {
-    url = mirror://sourceforge/tcl/tcl8.4.13-src.tar.gz;
-    md5 = "c6b655ad5db095ee73227113220c0523";
+    url = mirror://sourceforge/tcl/tcl8.4.16-src.tar.gz;
+    sha256 = "0v9mh53kdvfm4kxgsw8gfxsfl8kvbnnp22bpwyyg5sa4jyjjbs93";
   };
 }
diff --git a/pkgs/development/libraries/SDL_image/default.nix b/pkgs/development/libraries/SDL_image/default.nix
index 93e1cc31f44..d26213ef7cd 100644
--- a/pkgs/development/libraries/SDL_image/default.nix
+++ b/pkgs/development/libraries/SDL_image/default.nix
@@ -1,20 +1,22 @@
-args:
-args.stdenv.mkDerivation {
-  name = "SDL_image-1.2.6";
+args: with args;
+stdenv.mkDerivation (rec {
+  pname = "SDL_image";
+  version = "1.2.6";
 
-  src = args.
-	fetchurl {
-		url = http://www.libsdl.org/projects/SDL_image/release/SDL_image-1.2.6.tar.gz;
-		sha256 = "1i3f72dw3i3l6d77dk81gw57sp0629rng9k76qb37brlz7dv3z48";
-	};
+  name = "${pname}-${version}";
 
-  buildInputs =(with args; [SDL libpng libjpeg libtiff libungif libXpm]);
+  src = fetchurl {
+    url = "http://www.libsdl.org/projects/${pname}/release/${name}.tar.gz";
+    sha256 = "1i3f72dw3i3l6d77dk81gw57sp0629rng9k76qb37brlz7dv3z48";
+  };
+
+  buildInputs = [SDL libpng libjpeg libtiff libungif libXpm];
 
   postInstall = "ln -s \${out}/include/SDL/SDL_image.h \${out}/include/";
 
   meta = {
     description = "
-	SDL image library.
+      SDL image library.
 ";
   };
-}
+})
diff --git a/pkgs/development/libraries/SDL_mixer/default.nix b/pkgs/development/libraries/SDL_mixer/default.nix
index 14b8359c70a..024fd643be6 100644
--- a/pkgs/development/libraries/SDL_mixer/default.nix
+++ b/pkgs/development/libraries/SDL_mixer/default.nix
@@ -1,11 +1,24 @@
-{stdenv, fetchurl, SDL, libogg, libvorbis}:
+args: with args;
+stdenv.mkDerivation (rec {
+  pname = "SDL_mixer";
+  version = "1.2.8";
+
+  name = "${pname}-${version}";
 
-stdenv.mkDerivation {
-  name = "SDL_mixer-1.2.7";
   src = fetchurl {
-    url = http://www.libsdl.org/projects/SDL_mixer/release/SDL_mixer-1.2.7.tar.gz;
-    md5 = "7959b89c8f8f1564ca90968f6c88fa1e";
+    url = "http://www.libsdl.org/projects/${pname}/release/${name}.tar.gz";
+    sha256 = "a8222a274778ff16d0e3ee49a30db27a48a4d357169a915fc599a764e405e0b6";
   };
+
   buildInputs = [SDL libogg libvorbis];
+
   configureFlags = "--disable-music-ogg-shared";
-}
+
+  postInstall = "ln -s \${out}/include/SDL/SDL_mixer.h \${out}/include/";
+
+  meta = {
+    description = "
+      SDL multi-channel audio mixer library.
+";
+  };
+})
diff --git a/pkgs/development/libraries/SDL_net/default.nix b/pkgs/development/libraries/SDL_net/default.nix
new file mode 100644
index 00000000000..7de557322f6
--- /dev/null
+++ b/pkgs/development/libraries/SDL_net/default.nix
@@ -0,0 +1,22 @@
+args: with args;
+stdenv.mkDerivation (rec {
+  pname = "SDL_net";
+  version = "1.2.7";
+
+  name = "${pname}-${version}";
+
+  src = fetchurl {
+    url = "http://www.libsdl.org/projects/SDL_net/release/${name}.tar.gz";
+    sha256 = "2ce7c84e62ff8117b9f205758bcce68ea603e08bc9d6936ded343735b8b77c53";
+  };
+
+  buildInputs = [SDL];
+
+  postInstall = "ln -s \${out}/include/SDL/SDL_net.h \${out}/include/";
+
+  meta = {
+    description = "
+      SDL networking library.
+";
+  };
+})
diff --git a/pkgs/development/libraries/SDL_ttf/default.nix b/pkgs/development/libraries/SDL_ttf/default.nix
index 77b95d02cc3..c7a356adc61 100644
--- a/pkgs/development/libraries/SDL_ttf/default.nix
+++ b/pkgs/development/libraries/SDL_ttf/default.nix
@@ -1,14 +1,13 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "SDL_image-1.2.6";
 
-  src = args.
-	fetchurl {
+  src = fetchurl {
 		url = http://www.libsdl.org/projects/SDL_ttf/release/SDL_ttf-2.0.9.tar.gz;
 		sha256 = "0ls6anmlmwrmy21p3y9nfyl6fkwz4jpgh74kw7xd0hwbg5v8h95l";
 	};
 
-  buildInputs =(with args; [SDL freetype]);
+  buildInputs = [SDL freetype];
 
   postInstall = "ln -s \${out}/include/SDL/SDL_ttf.h \${out}/include/";
 
diff --git a/pkgs/development/libraries/a52dec/default.nix b/pkgs/development/libraries/a52dec/default.nix
index 4a75e11ec30..46dfe38c455 100644
--- a/pkgs/development/libraries/a52dec/default.nix
+++ b/pkgs/development/libraries/a52dec/default.nix
@@ -1,9 +1,15 @@
-{stdenv, fetchurl}:
+args: with args;
 
-stdenv.mkDerivation {
+stdenv.mkDerivation rec {
   name = "a52dec-0.7.4";
   src = fetchurl {
-    url = http://liba52.sourceforge.net/files/a52dec-0.7.4.tar.gz;
-    md5 = "caa9f5bc44232dc8aeea773fea56be80";
+    url = "${meta.homepage}/files/a52dec-0.7.4.tar.gz";
+    sha256 = "0czccp4fcpf2ykp16xcrzdfmnircz1ynhls334q374xknd5747d2";
+  };
+
+  configureFlags = "--enable-shared --disable-static";
+
+  meta = {
+    homepage = http://liba52.sourceforge.net;
   };
 }
diff --git a/pkgs/development/libraries/acl/acl-2.2.45-patch b/pkgs/development/libraries/acl/acl-2.2.45-patch
new file mode 100644
index 00000000000..557381922c3
--- /dev/null
+++ b/pkgs/development/libraries/acl/acl-2.2.45-patch
@@ -0,0 +1,222 @@
+diff -u -U3 -r acl-2.2.45-orig/aclocal.m4 acl-2.2.45-mod/aclocal.m4
+--- acl-2.2.45-orig/aclocal.m4	2007-12-23 16:16:11.000000000 +0300
++++ acl-2.2.45-mod/aclocal.m4	2007-12-23 18:09:04.000000000 +0300
+@@ -228,32 +228,32 @@
+     AC_PACKAGE_NEED_UTILITY($1, "$cc", cc, [C compiler])
+ 
+     if test -z "$MAKE"; then
+-        AC_PATH_PROG(MAKE, gmake,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
++        AC_PATH_PROG(MAKE, gmake,,)
+     fi
+     if test -z "$MAKE"; then
+-        AC_PATH_PROG(MAKE, make,, /usr/bin)
++        AC_PATH_PROG(MAKE, make,, )
+     fi
+     make=$MAKE
+     AC_SUBST(make)
+     AC_PACKAGE_NEED_UTILITY($1, "$make", make, [GNU make])
+ 
+     if test -z "$LIBTOOL"; then
+-	AC_PATH_PROG(LIBTOOL, glibtool,, /usr/bin)
++	AC_PATH_PROG(LIBTOOL, glibtool,, )
+     fi
+     if test -z "$LIBTOOL"; then
+-	AC_PATH_PROG(LIBTOOL, libtool,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
++	AC_PATH_PROG(LIBTOOL, libtool,, )
+     fi
+     libtool=$LIBTOOL
+     AC_SUBST(libtool)
+     AC_PACKAGE_NEED_UTILITY($1, "$libtool", libtool, [GNU libtool])
+ 
+     if test -z "$TAR"; then
+-        AC_PATH_PROG(TAR, tar,, /usr/freeware/bin:/bin:/usr/local/bin:/usr/bin)
++        AC_PATH_PROG(TAR, tar,, )
+     fi
+     tar=$TAR
+     AC_SUBST(tar)
+     if test -z "$ZIP"; then
+-        AC_PATH_PROG(ZIP, gzip,, /bin:/usr/bin:/usr/local/bin:/usr/freeware/bin)
++        AC_PATH_PROG(ZIP, gzip,, )
+     fi
+ 
+     zip=$ZIP
+@@ -266,25 +266,25 @@
+     AC_SUBST(makedepend)
+ 
+     if test -z "$AWK"; then
+-        AC_PATH_PROG(AWK, awk,, /bin:/usr/bin)
++        AC_PATH_PROG(AWK, awk,, )
+     fi
+     awk=$AWK
+     AC_SUBST(awk)
+ 
+     if test -z "$SED"; then
+-        AC_PATH_PROG(SED, sed,, /bin:/usr/bin)
++        AC_PATH_PROG(SED, sed,, )
+     fi
+     sed=$SED
+     AC_SUBST(sed)
+ 
+     if test -z "$ECHO"; then
+-        AC_PATH_PROG(ECHO, echo,, /bin:/usr/bin)
++        AC_PATH_PROG(ECHO, echo,, )
+     fi
+     echo=$ECHO
+     AC_SUBST(echo)
+ 
+     if test -z "$SORT"; then
+-        AC_PATH_PROG(SORT, sort,, /bin:/usr/bin)
++        AC_PATH_PROG(SORT, sort,, )
+     fi
+     sort=$SORT
+     AC_SUBST(sort)
+@@ -294,21 +294,21 @@
+ 
+     if test "$enable_gettext" = yes; then
+         if test -z "$MSGFMT"; then
+-                AC_PATH_PROG(MSGFMT, msgfmt,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
++                AC_PATH_PROG(MSGFMT, msgfmt,, )
+         fi
+         msgfmt=$MSGFMT
+         AC_SUBST(msgfmt)
+         AC_PACKAGE_NEED_UTILITY($1, "$msgfmt", msgfmt, gettext)
+ 
+         if test -z "$MSGMERGE"; then
+-                AC_PATH_PROG(MSGMERGE, msgmerge,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
++                AC_PATH_PROG(MSGMERGE, msgmerge,, )
+         fi
+         msgmerge=$MSGMERGE
+         AC_SUBST(msgmerge)
+         AC_PACKAGE_NEED_UTILITY($1, "$msgmerge", msgmerge, gettext)
+ 
+         if test -z "$XGETTEXT"; then
+-                AC_PATH_PROG(XGETTEXT, xgettext,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
++                AC_PATH_PROG(XGETTEXT, xgettext,, )
+         fi
+         xgettext=$XGETTEXT
+         AC_SUBST(xgettext)
+@@ -316,7 +316,7 @@
+     fi
+ 
+     if test -z "$RPM"; then
+-        AC_PATH_PROG(RPM, rpm,, /bin:/usr/bin:/usr/freeware/bin)
++        AC_PATH_PROG(RPM, rpm,, )
+     fi
+     rpm=$RPM
+     AC_SUBST(rpm)
+ôÏÌØËÏ × acl-2.2.45-orig/: configure
+diff -u -U3 -r acl-2.2.45-orig/m4/package_utilies.m4 acl-2.2.45-mod/m4/package_utilies.m4
+--- acl-2.2.45-orig/m4/package_utilies.m4	2007-12-23 16:16:11.000000000 +0300
++++ acl-2.2.45-mod/m4/package_utilies.m4	2007-12-23 18:01:28.000000000 +0300
+@@ -23,32 +23,26 @@
+     AC_PACKAGE_NEED_UTILITY($1, "$cc", cc, [C compiler])
+ 
+     if test -z "$MAKE"; then
+-        AC_PATH_PROG(MAKE, gmake,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
+     fi
+     if test -z "$MAKE"; then
+-        AC_PATH_PROG(MAKE, make,, /usr/bin)
+     fi
+     make=$MAKE
+     AC_SUBST(make)
+     AC_PACKAGE_NEED_UTILITY($1, "$make", make, [GNU make])
+ 
+     if test -z "$LIBTOOL"; then
+-	AC_PATH_PROG(LIBTOOL, glibtool,, /usr/bin)
+     fi
+     if test -z "$LIBTOOL"; then
+-	AC_PATH_PROG(LIBTOOL, libtool,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
+     fi
+     libtool=$LIBTOOL
+     AC_SUBST(libtool)
+     AC_PACKAGE_NEED_UTILITY($1, "$libtool", libtool, [GNU libtool])
+ 
+     if test -z "$TAR"; then
+-        AC_PATH_PROG(TAR, tar,, /usr/freeware/bin:/bin:/usr/local/bin:/usr/bin)
+     fi
+     tar=$TAR
+     AC_SUBST(tar)
+     if test -z "$ZIP"; then
+-        AC_PATH_PROG(ZIP, gzip,, /bin:/usr/bin:/usr/local/bin:/usr/freeware/bin)
+     fi
+ 
+     zip=$ZIP
+@@ -61,25 +55,21 @@
+     AC_SUBST(makedepend)
+ 
+     if test -z "$AWK"; then
+-        AC_PATH_PROG(AWK, awk,, /bin:/usr/bin)
+     fi
+     awk=$AWK
+     AC_SUBST(awk)
+ 
+     if test -z "$SED"; then
+-        AC_PATH_PROG(SED, sed,, /bin:/usr/bin)
+     fi
+     sed=$SED
+     AC_SUBST(sed)
+ 
+     if test -z "$ECHO"; then
+-        AC_PATH_PROG(ECHO, echo,, /bin:/usr/bin)
+     fi
+     echo=$ECHO
+     AC_SUBST(echo)
+ 
+     if test -z "$SORT"; then
+-        AC_PATH_PROG(SORT, sort,, /bin:/usr/bin)
+     fi
+     sort=$SORT
+     AC_SUBST(sort)
+@@ -89,21 +79,18 @@
+ 
+     if test "$enable_gettext" = yes; then
+         if test -z "$MSGFMT"; then
+-                AC_PATH_PROG(MSGFMT, msgfmt,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
+         fi
+         msgfmt=$MSGFMT
+         AC_SUBST(msgfmt)
+         AC_PACKAGE_NEED_UTILITY($1, "$msgfmt", msgfmt, gettext)
+ 
+         if test -z "$MSGMERGE"; then
+-                AC_PATH_PROG(MSGMERGE, msgmerge,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
+         fi
+         msgmerge=$MSGMERGE
+         AC_SUBST(msgmerge)
+         AC_PACKAGE_NEED_UTILITY($1, "$msgmerge", msgmerge, gettext)
+ 
+         if test -z "$XGETTEXT"; then
+-                AC_PATH_PROG(XGETTEXT, xgettext,, /usr/bin:/usr/local/bin:/usr/freeware/bin)
+         fi
+         xgettext=$XGETTEXT
+         AC_SUBST(xgettext)
+@@ -111,7 +98,6 @@
+     fi
+ 
+     if test -z "$RPM"; then
+-        AC_PATH_PROG(RPM, rpm,, /bin:/usr/bin:/usr/freeware/bin)
+     fi
+     rpm=$RPM
+     AC_SUBST(rpm)
+diff -u -U3 -r acl-2.2.45-orig/Makefile acl-2.2.45-mod/Makefile
+--- acl-2.2.45-orig/Makefile	2007-12-23 16:16:11.000000000 +0300
++++ acl-2.2.45-mod/Makefile	2007-12-23 18:01:28.000000000 +0300
+@@ -33,19 +33,6 @@
+ endif
+ 
+ $(CONFIGURE):
+-	autoconf
+-	./configure \
+-		--prefix=/ \
+-		--exec-prefix=/ \
+-		--sbindir=/bin \
+-		--bindir=/usr/bin \
+-		--libdir=/lib \
+-		--libexecdir=/usr/lib \
+-		--enable-lib64=yes \
+-		--includedir=/usr/include \
+-		--mandir=/usr/share/man \
+-		--datadir=/usr/share \
+-		$$LOCAL_CONFIGURE_OPTIONS
+ 	touch .census
+ 
+ aclocal.m4::
diff --git a/pkgs/development/libraries/tk/builder.sh b/pkgs/development/libraries/acl/builder.sh
index 999488a3531..4cabc84f828 100644
--- a/pkgs/development/libraries/tk/builder.sh
+++ b/pkgs/development/libraries/acl/builder.sh
@@ -1,10 +1,12 @@
 source $stdenv/setup
 
-configureFlags="--with-tcl=$tcl/lib"
 preConfigure() {
-  cd unix
+  rm configure
+  autoconf
 }
 
 preConfigure=preConfigure
 
+installFlags='install-lib install-dev'
+
 genericBuild
diff --git a/pkgs/development/libraries/acl/default.nix b/pkgs/development/libraries/acl/default.nix
new file mode 100644
index 00000000000..b9992af612e
--- /dev/null
+++ b/pkgs/development/libraries/acl/default.nix
@@ -0,0 +1,14 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "acl-2.2.45";
+
+  builder = ./builder.sh;
+  src = 
+	fetchurl {
+		url = ftp://oss.sgi.com/projects/xfs/cmd_tars/acl_2.2.45-1.tar.gz;
+		sha256 = "1bb2k5br494yk863w27k1h8gkdkq4kzakvajhj844hl1cixhhf1a";
+	};
+  buildInputs = [autoconf libtool gettext attr];
+  patches = [ ./acl-2.2.45-patch ];
+}
diff --git a/pkgs/development/libraries/apr-util/default.nix b/pkgs/development/libraries/apr-util/default.nix
index 7f2ce3e3882..967408e0cb4 100644
--- a/pkgs/development/libraries/apr-util/default.nix
+++ b/pkgs/development/libraries/apr-util/default.nix
@@ -4,14 +4,26 @@
 
 assert bdbSupport -> db4 != null;
 
-(stdenv.mkDerivation {
-  name = "apr-util-1.2.7";
+stdenv.mkDerivation {
+  name = "apr-util-1.2.12";
+  
   src = fetchurl {
-    url = http://archive.apache.org/dist/apr/apr-util-1.2.7.tar.bz2;
-    md5 = "a4c527f08ae2298e62a88472291bf066";
+    url = http://archive.apache.org/dist/apr/apr-util-1.2.12.tar.bz2;
+    sha256 = "152xwaxikp22acz7ypqsvlyjxhak6p40805wwbw7hcg1gyg2scyl";
   };
-  configureFlags = "
+  
+  configureFlags = ''
     --with-apr=${apr} --with-expat=${expat}
     ${if bdbSupport then "--with-berkeley-db=${db4}" else ""}
-  ";
-}) // {inherit bdbSupport;}
+  '';
+  
+  passthru = {
+    inherit bdbSupport;
+  };
+
+  meta = {
+    homepage = http://apr.apache.org/;
+    description = "A companion library to APR, the Apache Portable Runtime";
+  };
+}
+
diff --git a/pkgs/development/libraries/apr/default.nix b/pkgs/development/libraries/apr/default.nix
index a42699063c5..ceae8a1d12a 100644
--- a/pkgs/development/libraries/apr/default.nix
+++ b/pkgs/development/libraries/apr/default.nix
@@ -1,9 +1,15 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "apr-1.2.7";
+  name = "apr-1.2.12";
+  
   src = fetchurl {
-    url = http://archive.apache.org/dist/apr/apr-1.2.7.tar.bz2;
-    md5 = "e77887dbafc515c63feac84686bcb3bc";
+    url = http://archive.apache.org/dist/apr/apr-1.2.12.tar.bz2;
+    sha256 = "0d11wa2hlhb5lnny5rcazca056b35kgccx94cd38bazw1d6b68nv";
+  };
+
+  meta = {
+    homepage = http://apr.apache.org/;
+    description = "The Apache Portable Runtime library";
   };
 }
diff --git a/pkgs/development/libraries/aspell/default.nix b/pkgs/development/libraries/aspell/default.nix
index fdee6107716..baa95da785b 100644
--- a/pkgs/development/libraries/aspell/default.nix
+++ b/pkgs/development/libraries/aspell/default.nix
@@ -10,15 +10,15 @@ stdenv.mkDerivation {
   
   buildInputs = [perl];
 
-  patches = [
-    # A patch that allows additional dictionary directories to be set
-    # specified through the environment variable
-    # ASPELL_EXTRA_DICT_DIRS (comma-separated).
-    ./dict-path.patch
-  ];
+  # Note: Users should define the `ASPELL_CONF' environment variable to
+  # `dict-dir $HOME/.nix-profile/lib/aspell/' so that they can access
+  # dictionaries installed in their profile.
+  #
+  # We can't use `$out/etc/aspell.conf' for that purpose since Aspell
+  # doesn't expand environment variables such as `$HOME'.
 
   meta = {
-    description = "A spell checker for many languages";
+    description = "GNU Aspell, A spell checker for many languages";
     homepage = http://aspell.net/;
     license = "LGPL";
   };
diff --git a/pkgs/development/libraries/aspell/dict-path.patch b/pkgs/development/libraries/aspell/dict-path.patch
deleted file mode 100644
index c044c3d0eba..00000000000
--- a/pkgs/development/libraries/aspell/dict-path.patch
+++ /dev/null
@@ -1,30 +0,0 @@
-diff -rc aspell-0.60.5-orig/common/info.cpp aspell-0.60.5/common/info.cpp
-*** aspell-0.60.5-orig/common/info.cpp	2004-11-10 07:18:45.000000000 +0100
---- aspell-0.60.5/common/info.cpp	2007-10-23 17:30:47.000000000 +0200
-***************
-*** 209,214 ****
---- 209,215 ----
-  					   unsigned int name_size,
-  					   IStream & in)
-    {
-+     char * extra_dict_dirs = getenv("ASPELL_EXTRA_DICT_DIRS");
-      ModuleInfoNode * * prev = &head_;
-      ModuleInfoNode * to_add = new ModuleInfoNode();
-      to_add->c_struct.name = 0;
-***************
-*** 246,251 ****
---- 247,260 ----
-  	goto RETURN_ERROR;
-        }
-      }
-+ 
-+     // Add dictionaries from directories in
-+     // $ASPELL_EXTRA_DICT_DIRS. Maybe this isn't the right place to do
-+     // this, but it works.
-+     if (extra_dict_dirs) {
-+       to_add->c_struct.dict_dirs = &(to_add->dict_dirs);
-+       itemize(extra_dict_dirs, to_add->dict_dirs);
-+     }
-    
-      while (*prev != 0 && 
-  	   (*prev)->c_struct.order_num < to_add->c_struct.order_num)
diff --git a/pkgs/development/libraries/aspell/dictionaries.nix b/pkgs/development/libraries/aspell/dictionaries.nix
index 7be7b580656..97a8e961b41 100644
--- a/pkgs/development/libraries/aspell/dictionaries.nix
+++ b/pkgs/development/libraries/aspell/dictionaries.nix
@@ -5,7 +5,7 @@ let
   /* Function to compile an Aspell dictionary.  Fortunately, they all
      build in the exact same way. */
   buildDict =
-    {shortName, fullName, src}:
+    {shortName, fullName, src, postInstall ? ""}:
 
     stdenv.mkDerivation {
       name = "aspell-dict-${shortName}";
@@ -18,6 +18,8 @@ let
 
       preBuild = "makeFlagsArray=(dictdir=$out/lib/aspell datadir=$out/lib/aspell)";
 
+      inherit postInstall;
+
       meta = {
         description = "Aspell dictionary for ${fullName}";
       };
@@ -52,6 +54,15 @@ in {
     };
   };
     
+  eo = buildDict {
+    shortName = "eo-0.50-2";
+    fullName = "Esperanto";
+    src = fetchurl {
+      url = mirror://gnu/aspell/dict/eo/aspell-eo-0.50-2.tar.bz2;
+      sha256 = "19vhdm599ng98nq8jxspgvanv5hwryp0qri1vx6zsjl0jx1acqbc";
+    };
+  };
+
   fr = buildDict {
     shortName = "fr-0.50-3";
     fullName = "French";
@@ -77,6 +88,10 @@ in {
       url = mirror://gnu/aspell/dict/nl/aspell-nl-0.50-2.tar.bz2;
       sha256 = "0ffb87yjsh211hllpc4b9khqqrblial4pzi1h9r3v465z1yhn3j4";
     };
+    # Emacs expects a language called "nederlands".
+    postInstall = ''
+      echo "add nl.rws" > $out/lib/aspell/nederlands.multi
+    '';
   };
     
   ru = buildDict {
diff --git a/pkgs/development/libraries/aterm/2.4.2-fixes.nix b/pkgs/development/libraries/aterm/2.4.2-fixes.nix
index 3144154c9e6..7c70afc621b 100644
--- a/pkgs/development/libraries/aterm/2.4.2-fixes.nix
+++ b/pkgs/development/libraries/aterm/2.4.2-fixes.nix
@@ -6,6 +6,7 @@ stdenv.mkDerivation {
     url = http://losser.st-lab.cs.uu.nl/~eelco/dist/aterm-2.4.2-fixes-r2.tar.bz2;
     sha256 = "1w3bxdpc2hz29li5ssmdcz3x0fn47r7g62ns0v8nazxwf40vff4j";
   };
+  doCheck = true;
   meta = {
     homepage = http://www.cwi.nl/htbin/sen1/twiki/bin/view/SEN1/ATerm;
     license = "LGPL";
diff --git a/pkgs/development/libraries/aterm/2.5.nix b/pkgs/development/libraries/aterm/2.5.nix
new file mode 100644
index 00000000000..f30be007fa5
--- /dev/null
+++ b/pkgs/development/libraries/aterm/2.5.nix
@@ -0,0 +1,14 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "aterm-2.5";
+  src = fetchurl {
+    url = http://buildfarm.st.ewi.tudelft.nl/releases/meta-environment/aterm-2.5pre21238-l2q7rg38/aterm-2.5.tar.gz;
+    md5 = "33ddcb1a229baf406ad1f603eb1d5995";
+  };
+  meta = {
+    homepage = http://www.cwi.nl/htbin/sen1/twiki/bin/view/SEN1/ATerm;
+    license = "LGPL";
+    description = "Library for manipulation of term data structures in C";
+  };
+}
diff --git a/pkgs/development/libraries/attr/builder.sh b/pkgs/development/libraries/attr/builder.sh
index af71890f0c0..78f10591142 100644
--- a/pkgs/development/libraries/attr/builder.sh
+++ b/pkgs/development/libraries/attr/builder.sh
@@ -6,4 +6,6 @@ preConfigure() {
 
 preConfigure=preConfigure
 
+installFlags='install-lib install-dev'
+
 genericBuild
diff --git a/pkgs/development/libraries/audiofile/default.nix b/pkgs/development/libraries/audiofile/default.nix
index a10ec7a95c3..de02110aeeb 100644
--- a/pkgs/development/libraries/audiofile/default.nix
+++ b/pkgs/development/libraries/audiofile/default.nix
@@ -1,9 +1,9 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "audiofile-0.2.3";
+  name = "audiofile-0.2.6";
   src = fetchurl {
-    url = http://www.68k.org/~michael/audiofile/audiofile-0.2.5.tar.gz;
-    md5 = "fd07c62a17ceafa317929e55e51e26c5";
+    url = http://www.68k.org/~michael/audiofile/audiofile-0.2.6.tar.gz;
+    sha256 = "1a921w6jwcnkmx3vm091qrj7109jzri6kw4ygjq6ym91dssnfqab";
   };
 }
diff --git a/pkgs/development/libraries/avahi/0.6.21.nix b/pkgs/development/libraries/avahi/0.6.21.nix
new file mode 100644
index 00000000000..26f03ca58bf
--- /dev/null
+++ b/pkgs/development/libraries/avahi/0.6.21.nix
@@ -0,0 +1,2 @@
+args:
+import ./common.nix "0q954lwhr6xnv7chhi4bqlmkn4nx9shyw0mbdr3n26018dgw65yq" args
diff --git a/pkgs/development/libraries/avahi/0.6.22.nix b/pkgs/development/libraries/avahi/0.6.22.nix
new file mode 100644
index 00000000000..93b7184cdae
--- /dev/null
+++ b/pkgs/development/libraries/avahi/0.6.22.nix
@@ -0,0 +1,2 @@
+args:
+import ./common.nix "0lnxzsdhihb3kjwd3vcrl9pq6ykfbp0vy9ja0mch01ffnrqgiilx" args
diff --git a/pkgs/development/libraries/avahi/common.nix b/pkgs/development/libraries/avahi/common.nix
new file mode 100644
index 00000000000..1ebadc26e26
--- /dev/null
+++ b/pkgs/development/libraries/avahi/common.nix
@@ -0,0 +1,18 @@
+sha256: args: with args;
+
+stdenv.mkDerivation rec {
+  name = "avahi-" + version;
+  src = fetchurl {
+    url = "${meta.homepage}/download/${name}.tar.gz";
+    inherit sha256;
+  };
+
+  buildInputs = [pkgconfig libdaemon dbus perl perlXMLParser glib qt4];
+
+  configureFlags = "--disable-qt3 --disable-gdbm --disable-gtk --disable-mono
+    --with-distro=none --enable-shared --disable-static --disable-python";
+
+  meta = {
+    homepage = http://avahi.org;
+  };
+}
diff --git a/pkgs/development/libraries/avahi/default.nix b/pkgs/development/libraries/avahi/default.nix
deleted file mode 100644
index 52051725e22..00000000000
--- a/pkgs/development/libraries/avahi/default.nix
+++ /dev/null
@@ -1,14 +0,0 @@
-{stdenv, fetchurl, pkgconfig}:
-
-stdenv.mkDerivation {
-  name = "avahi-0.6.11";
-  src = fetchurl {
-    url = http://avahi.org/download/avahi-0.6.11.tar.gz;
-    md5 = "91fd8cc0c2bae638848faad36cf1c032";
-  };
-
-  #buildInputs = [pkgconfig glib gtk libpng libglade];
-  buildInputs = [pkgconfig];
-
-  configureFlags = "--disable-glib --disable-qt3 --disable-qt4 --disable-gtk --disable-dbus --disable-expat --disable-gdbm --disable-libdaemon --disable-python --disable-mono";
-}
diff --git a/pkgs/development/libraries/boehm-gc/default.nix b/pkgs/development/libraries/boehm-gc/default.nix
index d46b1fe7016..ba81b16bcf6 100644
--- a/pkgs/development/libraries/boehm-gc/default.nix
+++ b/pkgs/development/libraries/boehm-gc/default.nix
@@ -1,9 +1,13 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "boehm-gc-6.8";
+  name = "boehm-gc-7.0";
   src = fetchurl {
-    url = http://www.hpl.hp.com/personal/Hans_Boehm/gc/gc_source/gc6.8.tar.gz;
-    md5 = "418d38bd9c66398386a372ec0435250e";
+    url = http://www.hpl.hp.com/personal/Hans_Boehm/gc/gc_source/gc-7.0.tar.gz;
+    sha256 = "0nqy0462ainp79fjmx5lgr89s2d433fggr3n9d1p09xq77lwc2nj";
+  };
+  meta = {
+    description = "A garbage collector for C and C++";
+    homepage = http://www.hpl.hp.com/personal/Hans_Boehm/gc/;
   };
 }
diff --git a/pkgs/development/libraries/boost/default.nix b/pkgs/development/libraries/boost/default.nix
index 5040a763ab8..fe4cdcf0337 100644
--- a/pkgs/development/libraries/boost/default.nix
+++ b/pkgs/development/libraries/boost/default.nix
@@ -10,5 +10,6 @@ stdenv.mkDerivation {
   preConfigure="
     sed -e 's@^BJAM_CONFIG=\"\"@BJAM_CONFIG=\"--layout=system release threading=multi link=shared\"@g' -i configure
   ";
+  patches = [./gcc-4.2.patch];
   configureFlags="--with-icu=${icu}";
 }
diff --git a/pkgs/development/libraries/boost/gcc-4.2.patch b/pkgs/development/libraries/boost/gcc-4.2.patch
new file mode 100644
index 00000000000..6c2210d831d
--- /dev/null
+++ b/pkgs/development/libraries/boost/gcc-4.2.patch
@@ -0,0 +1,11 @@
+Index: trunk/tools/jam/src/build.jam

+===================================================================

+--- trunk/tools/jam/src/build.jam (revision 40095)

++++ trunk/tools/jam/src/build.jam (revision 41036)

+@@ -176,5 +176,5 @@

+ ## GCC 2.x, 3.x, 4.x

+ toolset gcc gcc : "-o " : -D

+-    : -pedantic

++    : -pedantic -fno-strict-aliasing

+     [ opt --release : [ opt --symbols : -g : -s ] -O3 ]

+     [ opt --debug : -g -O0 -fno-inline ]

diff --git a/pkgs/development/libraries/cairomm/default.nix b/pkgs/development/libraries/cairomm/default.nix
new file mode 100644
index 00000000000..a22788c288e
--- /dev/null
+++ b/pkgs/development/libraries/cairomm/default.nix
@@ -0,0 +1,15 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "cairomm-1.4.6";
+
+  src = fetchurl {
+    url = "http://cairographics.org/releases/${name}.tar.gz";
+    sha256 = "1zd5pq5jd507w1v994awpsl7m26g4dfl0rwgrxig2823hl3rqmrp";
+  };
+
+  buildInputs = [pkgconfig];
+  propagatedBuildInputs = [cairo x11 fontconfig freetype];
+
+  configureFlags = "--enable-shared --disable-static";
+}
diff --git a/pkgs/development/libraries/cfitsio/default.nix b/pkgs/development/libraries/cfitsio/default.nix
new file mode 100644
index 00000000000..5fb672b8ff1
--- /dev/null
+++ b/pkgs/development/libraries/cfitsio/default.nix
@@ -0,0 +1,13 @@
+args: with args;
+stdenv.mkDerivation {
+	name = "cfitsio-3.060";
+	src = fetchurl {
+		url = ftp://heasarc.gsfc.nasa.gov/software/fitsio/c/cfitsio3060.tar.gz;
+		sha256 = "0ijbjpl5v35m538sa3c82qgja697kddjbj7yxx64ka7pdsdnfx9l";
+	};
+# Shared-only build
+	buildFlags = "shared";
+	patchPhase = ''
+	sed -e '/^install:/s/libcfitsio.a //' -e 's@/bin/@@g' -i Makefile.in
+	'';
+}
diff --git a/pkgs/development/libraries/chmlib/builder.sh b/pkgs/development/libraries/chmlib/builder.sh
deleted file mode 100644
index ccdbfc17a76..00000000000
--- a/pkgs/development/libraries/chmlib/builder.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-source $stdenv/setup
-
-unpackCmd="tar xvfj $src"
-
-makeFlags="-f Makefile.simple CC=gcc LD=gcc INSTALLPREFIX=$out"
-
-postConfigure=postConfigure
-postConfigure() {
-    cd src
-}
-
-preInstall=preInstall
-preInstall() {
-    mkdir $out
-    mkdir $out/lib
-    mkdir $out/include
-}
-
-genericBuild
\ No newline at end of file
diff --git a/pkgs/development/libraries/chmlib/default.nix b/pkgs/development/libraries/chmlib/default.nix
index 096f2e0e229..bd593aaea0a 100644
--- a/pkgs/development/libraries/chmlib/default.nix
+++ b/pkgs/development/libraries/chmlib/default.nix
@@ -1,9 +1,16 @@
-{stdenv, fetchurl}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "chmlib-0.38";
+stdenv.mkDerivation rec {
+  name = "chmlib-0.39";
   src = fetchurl {
-    url = http://66.93.236.84/~jedwin/projects/chmlib/chmlib-0.38.tar.bz2;
-    md5 = "d72661526aaea377ed30e9f58a086964";
+    url = "${meta.homepage}/${name}.tar.bz2";
+	sha256 = "0hgzw121ffmk79wbpkd0394y5ah99c3i85z6scp958mmkr25sc6j";
+  };
+
+  meta = {
+	  homepage = http://www.jedrea.com/chmlib;
+	  license = "LGPL";
+	  description = "CHLIB is a library for dealing with Microsoft ITSS/CHM
+	  format files";
   };
 }
diff --git a/pkgs/development/libraries/clucene-contrib/default.nix b/pkgs/development/libraries/clucene-contrib/default.nix
deleted file mode 100644
index 8938256dec4..00000000000
--- a/pkgs/development/libraries/clucene-contrib/default.nix
+++ /dev/null
@@ -1,18 +0,0 @@
-{ stdenv, fetchurl, cluceneCore}:
-
-stdenv.mkDerivation {
-  name = "clucene-contrib-0.9.16a";
-
-  src = fetchurl {
-    url = ftp://ftp.chg.ru/pub/sourceforge/c/cl/clucene/clucene-contrib-0.9.16a.tar.bz2;
-    sha256 = "1apk867pggxsflhgvsnhcmy5vz2cvc1b914g4inkcj6s5vn1a1jx";
-  };
-  inherit cluceneCore;
-  buildInputs=[cluceneCore];
-  configureFlags = "--disable-static --with-clucene=${cluceneCore}";
-
-  meta = {
-    description = "CLucene is a port of the very popular Java Lucene text search engine API. Contrib package.";
-    homepage = http://clucene.sourceforge.net;
-  };
-}
diff --git a/pkgs/development/libraries/clucene-core/default.nix b/pkgs/development/libraries/clucene-core/default.nix
index 3d5734d6c2d..24e133a5de3 100644
--- a/pkgs/development/libraries/clucene-core/default.nix
+++ b/pkgs/development/libraries/clucene-core/default.nix
@@ -1,16 +1,15 @@
-{ stdenv, fetchurl }:
+args: with args;
+stdenv.mkDerivation rec {
+	name = "clucene-core-0.9.20";
 
-stdenv.mkDerivation {
-  name = "clucene-core-0.9.16a";
+	src = fetchurl {
+		url = "mirror://sf/clucene/${name}.tar.bz2";
+		sha256 = "1hwq3b4qp1dgygmypgpg3blj68wnksq2rbqkwyxvl5dldn12q7rg";
+	};
+	configureFlags = "--disable-static";
 
-  src = fetchurl {
-    url = ftp://ftp.chg.ru/pub/sourceforge/c/cl/clucene/clucene-core-0.9.16a.tar.bz2;
-    sha256 = "0hv7sp1lbicnj2984hiki8qwrvz5zwn1zhj6azhavgjklanhihjr";
-  };
-
-  meta = {
-    description = "CLucene is a port of the very popular Java Lucene text search engine API. Core package.";
-    homepage = http://clucene.sourceforge.net;
-  };
-  configureFlags = "--disable-static";
+	meta = {
+		description = "CLucene is a port of the very popular Java Lucene text search engine API. Core package.";
+		homepage = http://clucene.sourceforge.net;
+	};
 }
diff --git a/pkgs/development/libraries/coredumper/default.nix b/pkgs/development/libraries/coredumper/default.nix
index d6943affbed..f62289ea181 100644
--- a/pkgs/development/libraries/coredumper/default.nix
+++ b/pkgs/development/libraries/coredumper/default.nix
@@ -1,9 +1,9 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "coredumper-0.2";
+  name = "coredumper-1.1";
   src = fetchurl {
-    url = mirror://sourceforge/goog-coredumper/coredumper-0.2.tar.gz;
-    md5 = "024f8e4afe73c4cc4f4a0b0ef585e9b7";
+    url = http://google-coredumper.googlecode.com/files/coredumper-1.1.tar.gz;
+    sha256 = "1phl1zg2n17rp595dyzz9iw01gfdpsdh0l6wy2hfb5shi71h63rx";
   };
 }
diff --git a/pkgs/development/libraries/cracklib/default.nix b/pkgs/development/libraries/cracklib/default.nix
index 678d595703e..baa509eadb0 100644
--- a/pkgs/development/libraries/cracklib/default.nix
+++ b/pkgs/development/libraries/cracklib/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "cracklib-2.8.9";
+  name = "cracklib-2.8.12";
   builder = ./builder.sh;
   src = fetchurl {
-    url = mirror://sourceforge/cracklib/cracklib-2.8.9.tar.gz;
-    md5 = "9a8c9eb26b48787c84024ac779f64bb2";
+    url = mirror://sourceforge/cracklib/cracklib-2.8.12.tar.gz;
+    sha256 = "0l9kar7h80kkvs394dyzbn02jkd8hzynh9kxyqrlacj1wp35rmah";
   };
   dicts = fetchurl {
     url = http://nix.cs.uu.nl/dist/tarballs/cracklib-words.gz;
diff --git a/pkgs/development/libraries/ctl/default.nix b/pkgs/development/libraries/ctl/default.nix
new file mode 100644
index 00000000000..6e1c212703c
--- /dev/null
+++ b/pkgs/development/libraries/ctl/default.nix
@@ -0,0 +1,23 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "ctl-1.4.1";
+
+  src = fetchurl {
+    url = http://surfnet.dl.sourceforge.net/sourceforge/ampasctl/ctl-1.4.1.tar.gz;
+    sha256 = "16lzgbpxdyhykdwndj1i9vx3h4bfkxqqcrvasvgg70gb5raxj0mj";
+  };
+
+  propagatedBuildInputs =  [ilmbase];
+  configureFlags="--with-ilmbase-prefix=${ilmbase}";
+  #configurePhase = "
+    #export CXXFLAGS=\"-I${ilmbase}/include -L${ilmbase}/lib\"
+    #echo $CXXFLAGS
+    #unset configurePhase; configurePhase
+  #";
+
+  meta = {
+      description = "Color Transformation Language";
+      homepage = http://ampasctl.sourceforge.net;
+      license = "SOME OPEN SOURCE LICENSE"; # TODO which exactly is this?
+  };
+}
diff --git a/pkgs/development/libraries/db4/db4-4.4.nix b/pkgs/development/libraries/db4/db4-4.4.nix
index 270f5359d95..2746d812723 100644
--- a/pkgs/development/libraries/db4/db4-4.4.nix
+++ b/pkgs/development/libraries/db4/db4-4.4.nix
@@ -4,7 +4,10 @@ stdenv.mkDerivation ({
   name = "db4-4.4.20";
   builder = ./builder.sh;
   src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/db-4.4.20.NC.tar.gz;
+    urls = [
+      http://download.oracle.com/berkeley-db/db-4.4.20.NC.tar.gz
+      http://nix.cs.uu.nl/dist/tarballs/db-4.4.20.NC.tar.gz
+    ];
     md5 = "afd9243ea353bbaa04421488d3b37900";
   };
   configureFlags = [
diff --git a/pkgs/development/libraries/dbus-glib/default.nix b/pkgs/development/libraries/dbus-glib/default.nix
index fb206f9a6f6..9a9851521b4 100644
--- a/pkgs/development/libraries/dbus-glib/default.nix
+++ b/pkgs/development/libraries/dbus-glib/default.nix
@@ -1,12 +1,19 @@
-{stdenv, fetchurl, pkgconfig, gettext, dbus, glib, expat}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "dbus-glib-0.73";
+stdenv.mkDerivation rec {
+  name = "dbus-glib-0.74";
   src = fetchurl {
-    url = http://dbus.freedesktop.org/releases/dbus-glib/dbus-glib-0.73.tar.gz;
-    sha256 = "14ndjhbn6q4m7wrml8s57wghnjbm6a6fqb5jgazjxcn6748gkmyn";
+    url = "${meta.homepage}/releases/dbus-glib/${name}.tar.gz";
+    sha256 = "1qmbnd9xgg7vahlfywd8sfd9yqhx8jdyczz3cshfsd4qc76xhw78";
+  };
+  buildInputs = [pkgconfig expat gettext];
+  propagatedBuildInputs = [dbus.libs glib];
+  configureFlags = "--enable-shared --disable-static";
+  passthru = { inherit dbus glib; };
+
+  meta = {
+	  homepage = http://dbus.freedesktop.org;
+	  license = "AFL-2.1 or GPL-2";
+	  description = "GLib bindings for D-Bus lightweight IPC mechanism";
   };
-  inherit dbus glib;
-  buildInputs = [pkgconfig gettext glib expat];
-  propagatedBuildInputs = [dbus];
 }
diff --git a/pkgs/development/libraries/dbus/default.nix b/pkgs/development/libraries/dbus/default.nix
index cd4b8f49e05..b60705f21f6 100644
--- a/pkgs/development/libraries/dbus/default.nix
+++ b/pkgs/development/libraries/dbus/default.nix
@@ -1,22 +1,42 @@
-{stdenv, fetchurl, pkgconfig, expat}:
-
-stdenv.mkDerivation {
-  name = "dbus-1.0.2";
+args: with args;
+let
+  version = "1.0.2";
   src = fetchurl {
-    url = http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz;
+    url = "http://dbus.freedesktop.org/releases/dbus/dbus-${version}.tar.gz";
     sha256 = "1jn652zb81mczsx4rdcwrrzj3lfhx9d107zjfnasc4l5yljl204a";
   };
-  buildInputs = [pkgconfig expat];
-  configureFlags = "--without-x --localstatedir=/var";
+  configureFlags = "--disable-static --localstatedir=/var --with-session-socket-dir=/tmp";
+in rec {
+  libs = stdenv.mkDerivation {
+    name = "dbus-library-" + version;
+    buildInputs = [pkgconfig expat];
+    inherit src configureFlags;
+    patchPhase = ''
+      sed -i /mkinstalldirs.*localstatedir/d bus/Makefile.in
+      sed -i '/SUBDIRS/s/ tools//' Makefile.in
+    '';
+  };
+
+  tools = stdenv.mkDerivation {
+    name = "dbus-tools-" + version;
+    inherit src configureFlags;
+    buildInputs = [pkgconfig expat libs]
+      ++ (if useX11 then [libX11 libICE libSM] else []);
+    postConfigure = "cd tools";
 
-  # Awful hack: `make install' wants to write in /var, but it
-  # can't.  So redirect it with a DESTDIR.
-  preInstall = "
-    installFlagsArray=(DESTDIR=$out/destdir)
-  ";
+    NIX_LDFLAGS = "-ldbus-1";
+    makeFlags = "DBUS_DAEMONDIR=${daemon}/bin";
+
+    patchPhase = ''
+      sed -i 's@ $(top_builddir)/dbus/libdbus-1.la@@' tools/Makefile.in
+      sed -i '/mkdir.*localstate/d' tools/Makefile.in
+    '';
+  };
 
-  postInstall = "
-    mv $out/destdir/$out/* $out
-    rm -rf $out/destdir
-  ";
+# I'm too lazy to separate daemon and libs now.
+  daemon = libs;
+  
+  # FIXME TODO
+  # After merger it will be better to correct upstart-job instead.
+  outPath = daemon.outPath;
 }
diff --git a/pkgs/development/libraries/dbus_x/default.nix b/pkgs/development/libraries/dbus_x/default.nix
deleted file mode 100644
index dfe3ea0ee7e..00000000000
--- a/pkgs/development/libraries/dbus_x/default.nix
+++ /dev/null
@@ -1,13 +0,0 @@
-args: with args;
-
-stdenv.mkDerivation {
-  name = "dbus-1.0.2";
-  src = fetchurl {
-    url = http://dbus.freedesktop.org/releases/dbus/dbus-1.0.2.tar.gz;
-    sha256 = "1jn652zb81mczsx4rdcwrrzj3lfhx9d107zjfnasc4l5yljl204a";
-  };
-  buildInputs = [pkgconfig expat libX11 libICE libSM];
-
-  configureFlags = "--with-x --disable-static --localstatedir=/var --with-session-socket-dir=/tmp";
-  patchPhase = "sed -e /mkinstalldirs.*localstatedir/d -i bus/Makefile.in";
-}
diff --git a/pkgs/development/libraries/enchant/1.3.0.nix b/pkgs/development/libraries/enchant/1.3.0.nix
new file mode 100644
index 00000000000..e503366087e
--- /dev/null
+++ b/pkgs/development/libraries/enchant/1.3.0.nix
@@ -0,0 +1,14 @@
+args: with args;
+stdenv.mkDerivation rec {
+  name = "enchant-" + version;
+  src = fetchurl {
+    url = "http://www.abisource.com/downloads/enchant/${version}/${name}.tar.gz";
+    sha256 = "1vwqwsadnp4rf8wj7d4rglvszjzlcli0jyxh06h8inka1sm1al76";
+  };
+  buildInputs = [aspell pkgconfig glib];
+  configureFlags = "--enable-shared --disable-static";
+
+  meta = {
+    homepage = http://www.abisource.com/enchant;
+  };
+}
diff --git a/pkgs/development/libraries/enchant/default.nix b/pkgs/development/libraries/enchant/default.nix
deleted file mode 100644
index 74fe33cba8c..00000000000
--- a/pkgs/development/libraries/enchant/default.nix
+++ /dev/null
@@ -1,10 +0,0 @@
-args: with args;
-stdenv.mkDerivation {
-	name = "enchant-1.3.0";
-	src = fetchurl {
-		url = http://FIXME/enchant-1.3.0.tar.gz;
-		sha256 = "1vwqwsadnp4rf8wj7d4rglvszjzlcli0jyxh06h8inka1sm1al76";
-	};
-	buildInputs = [aspell pkgconfig glib];
-	configureFlags = "--enable-shared --disable-static";
-}
diff --git a/pkgs/development/libraries/expat/default.nix b/pkgs/development/libraries/expat/default.nix
index 48753842245..cd546a58169 100644
--- a/pkgs/development/libraries/expat/default.nix
+++ b/pkgs/development/libraries/expat/default.nix
@@ -1,7 +1,7 @@
 {stdenv, fetchurl}: stdenv.mkDerivation {
-  name = "expat-2.0.0";
+  name = "expat-2.0.1";
   src = fetchurl {
-    url = mirror://sourceforge/expat/expat-2.0.0.tar.gz;
-    md5 = "d945df7f1c0868c5c73cf66ba9596f3f";
+    url = mirror://sourceforge/expat/expat-2.0.1.tar.gz;
+    sha256 = "14sy5qx9hgjyfs743iq8ywldhp5w4n6cscqf2p4hgrw6vys60xl4";
   };
 }
diff --git a/pkgs/development/libraries/facile/default.nix b/pkgs/development/libraries/facile/default.nix
new file mode 100644
index 00000000000..1890c6d0563
--- /dev/null
+++ b/pkgs/development/libraries/facile/default.nix
@@ -0,0 +1,19 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "facile-1.1";
+	src = fetchurl {
+		url = "${meta.homepage}/distrib/${name}.tar.gz";
+		sha256 = "1jp59ankjds8mh4vm0b5h4fd1lcbfn0rd6n151cgh14ihsknnym8";
+	};
+	dontAddPrefix = 1;
+	patchPhase = "sed -e 's@mkdir@mkdir -p@' -i Makefile";
+	postConfigure = "make -C src .depend";
+	makeFlags = "FACILEDIR=\${out}/lib/ocaml/facile";
+	buildInputs = [ocaml];
+
+	meta = {
+		homepage = http://www.recherche.enac.fr/log/facile;
+		license = "LGPL";
+		description = "A Functional Constraint Library";
+	};
+}
diff --git a/pkgs/development/libraries/fcgi/default.nix b/pkgs/development/libraries/fcgi/default.nix
new file mode 100644
index 00000000000..0af3e4f5537
--- /dev/null
+++ b/pkgs/development/libraries/fcgi/default.nix
@@ -0,0 +1,18 @@
+args:
+args.stdenv.mkDerivation rec {
+  name = "fcgi-2.4.0";
+
+  src = args.fetchurl {
+    name = name + ".tar.gz";
+    url = http://www.fastcgi.com/dist/fcgi.tar.gz;
+    sha256 = "1f857wnl1d6jfrgfgfpz3zdaj8fch3vr13mnpcpvy8bang34bz36";
+  };
+
+  buildInputs =(with args; []);
+
+  meta = { 
+      description = "FastCGI  is a language independent, scalable, open extension to CG";
+      homepage = http://www.fastcgi.com/;
+      license = "FastCGI see LICENSE.TERMS";
+  };
+}
diff --git a/pkgs/development/libraries/ffmpeg_svn_snapshot/default.nix b/pkgs/development/libraries/ffmpeg_svn_snapshot/default.nix
index 3719f1301a3..980b04a9d61 100644
--- a/pkgs/development/libraries/ffmpeg_svn_snapshot/default.nix
+++ b/pkgs/development/libraries/ffmpeg_svn_snapshot/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "ffmpeg-svn";
+  name = "ffmpeg-svn-pre-r11901";
   src = fetchurl {
-    url = http://ffmpeg.mplayerhq.hu/ffmpeg-export-snapshot.tar.bz2;
-    sha256 = "040a35f0c004323af14329c09ad3cff8d040e2cf9797d97cde3d9d83d02b4d87";
+    url = http://nix.cs.uu.nl/dist/tarballs/ffmpeg-svn-r11901.tar.bz2;
+    sha256 = "0l5207gnfaz57pvlxpxyjphyz0mp9plnxzd0aghy0nz3hmqh4rs7";
   };
   # !!! Hm, what are the legal consequences of --enable-gpl?
   configureFlags = "--enable-shared --enable-pp --enable-gpl --disable-ffserver --disable-ffplay";
diff --git a/pkgs/development/libraries/fftw/default.nix b/pkgs/development/libraries/fftw/default.nix
index 3f712544303..3f5d13b09fb 100644
--- a/pkgs/development/libraries/fftw/default.nix
+++ b/pkgs/development/libraries/fftw/default.nix
@@ -1,5 +1,5 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs { 
 		src = 
 			fetchurl {
 				url = ftp://ftp.fftw.org/pub/fftw/fftw-3.1.2.tar.gz;
@@ -8,10 +8,11 @@ args : with args;
 		buildInputs = [];
 		configureFlags = ["--enable-float --enable-shared"];
 	} null;
+	in with localDefs;
 stdenv.mkDerivation {
 	name = "fftw-3.1.2";
 	builder = writeScript "fftw-3.1.2-builder"
-		(textClosure [doConfigure doMakeInstall doForceShare]);
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare]);
 	meta = {
 		description = "
 	Fastest Fourier Transform in the West library.
diff --git a/pkgs/development/libraries/fltk/default.nix b/pkgs/development/libraries/fltk/default.nix
index 0b35b3e34b0..25b8379e379 100644
--- a/pkgs/development/libraries/fltk/default.nix
+++ b/pkgs/development/libraries/fltk/default.nix
@@ -1,45 +1,37 @@
 args:
-with args;
-with args.lib; 
-let 
-  co = chooseOptionsByFlags {
-    inherit args;
-    flagDescr = 
-      { mandatory = { cfgOption = " --prefix=\$out"; 
-                      buildInputs=["libX11" "libXext"]; 
-                      blocks = ["cygwin" "quartz"]; } # cgywin quartz and much more not yet tested
-      ; cygwin = { cfgOption = "--enable-cygwin"; } #         use the CygWin libraries default=no
-      ; debug = { cfgOption = "--enable-debug"; } #          turn on debugging default=no
-      ; gl = { cfgOption = "--enable-gl"; buildInputs = [ "mesa" "mesa-heaaders"]; } #             turn on OpenGL support default=yes
-      ; shared = { cfgOption = "--enable-shared"; } #         turn on shared libraries default=no
-      ; threads = { cfgOption = "--enable-threads"; } #        enable multi-threading support
-      ; quartz = { cfgOption = "--enable-quartz"; buildInputs = "quartz"; } # don't konw yet what quartz is #         use Quartz instead of Quickdraw (default=no)
-      ; largefile = { cfgOption = "--disable-largefile"; } #     omit support for large files
-      ; useNixLibs = { implies = [ "nixjpeg" "nixpng" "nixzlib" ]; } # use nix libraries only
-      ; nixjpeg = { cfgOption = "--disable-localjpeg"; buildInputs = "libjpeg"; } #      use local JPEG library, default=auto
-      ; nixzlib = { cfgOption = "--disable-localzlib"; buildInputs = "zlib"; } #      use local ZLIB library, default=auto
-      ; nixpng = { cfgOption = "--disable-localpng"; buildInputs = "libpng"; } #       use local PNG library, default=auto
-      ; xinerama = { cfgOption = "--enable-xinerama"; buildInputs = "xinerama"; } #       turn on Xinerama support default=no
-      ; xft = { cfgOption = "--enable-xft"; buildInputs="xft"; } #            turn on Xft support default=no
-      ; xdbe = { cfgOption = "--enable-xdbe"; } #           turn on Xdbe support default=no
-      ;};
-    };
-in
-args.stdenv.mkDerivation {
-  inherit (co) /* flags */ buildInputs;
-  name = "fltk-2.0.x-r5940";
+( args.mkDerivationByConfiguration {
+    flagConfig = {
+      mandatory = { propagatedBuildInputs=["x11"]; 
+                    blocks = ["cygwin" "quartz"]; }; # cgywin quartz and much more not yet tested
+      cygwin = { cfgOption = "--enable-cygwin"; }; #         use the CygWin libraries default=no
+      debug = { cfgOption = "--enable-debug"; }; #          turn on debugging default=no
+      gl = { cfgOption = "--enable-gl"; buildInputs = [ "mesa" ]; }; #             turn on OpenGL support default=yes
+      shared = { cfgOption = "--enable-shared"; }; #         turn on shared libraries default=no
+      threads = { cfgOption = "--enable-threads"; }; #        enable multi-threading support
+      quartz = { cfgOption = "--enable-quartz"; buildInputs = "quartz"; }; # don't konw yet what quartz is #         use Quartz instead of Quickdraw (default=no)
+      largefile = { cfgOption = "--disable-largefile"; }; #     omit support for large files
+      useNixLibs = { implies = [ "nixjpeg" "nixpng" "nixzlib" ]; }; # use nix libraries only
+      nixjpeg = { cfgOption = "--disable-localjpeg"; buildInputs = "libjpeg"; }; #      use local JPEG library, default=auto
+      nixzlib = { cfgOption = "--disable-localzlib"; buildInputs = "zlib"; }; #      use local ZLIB library, default=auto
+      nixpng = { cfgOption = "--disable-localpng"; buildInputs = "libpng"; }; #       use local PNG library, default=auto
+      xinerama = { cfgOption = "--enable-xinerama"; buildInputs = "xinerama"; }; #       turn on Xinerama support default=no
+      xft = { cfgOption = "--enable-xft"; buildInputs="xft"; }; #            turn on Xft support default=no
+      xdbe = { cfgOption = "--enable-xdbe"; }; #           turn on Xdbe support default=no
+    }; 
 
-  configurePhase = "./configure " + co.configureFlags;
+    extraAttrs = co : {
+      name = "fltk-2.0.x-r5940";
 
-  src = fetchurl {
-    url = http://mirror.switch.ch/mirror/gentoo/distfiles/fltk-1.1.7-source.tar.bz2;
-    sha256 = "855a97e35da823f205253b865758715872cd2c7720e4dcf134a3b6dc18bfb96a";
-  };
+    src = args.fetchurl {
+      #url = http://mirror.switch.ch/mirror/gentoo/distfiles/fltk-1.1.7-source.tar.bz2;
+      #sha256 = "855a97e35da823f205253b865758715872cd2c7720e4dcf134a3b6dc18bfb96a";
+      url = ftp://ftp.easysw.com/pub/fltk/snapshots/fltk-1.1.x-r5989.tar.bz2;
+      sha256 = "1zk5qh9133zd53hsn03bc4h6j4vjy61y92j4zxxw94z8y3jkc8yw";
+    };
 
-  meta = { 
-      description = "a C++ cross platform lightweight gui library binding";
-      homepage = http://www.fltk.org;
+    meta = { 
+        description = "a C++ cross platform lightweight gui library binding";
+        homepage = http://www.fltk.org;
+    };
   };
-  
-  dummy=2;
-}
+} ) args
diff --git a/pkgs/development/libraries/freeglut/default.nix b/pkgs/development/libraries/freeglut/default.nix
index 704dc0005fb..19720b9d677 100644
--- a/pkgs/development/libraries/freeglut/default.nix
+++ b/pkgs/development/libraries/freeglut/default.nix
@@ -9,4 +9,5 @@ stdenv.mkDerivation {
   };
 
   buildInputs = [x11 mesa];
+  patches = ./freeglut-gcc-4.2.patch;
 }
diff --git a/pkgs/development/libraries/freeglut/freeglut-gcc-4.2.patch b/pkgs/development/libraries/freeglut/freeglut-gcc-4.2.patch
new file mode 100644
index 00000000000..1642affba91
--- /dev/null
+++ b/pkgs/development/libraries/freeglut/freeglut-gcc-4.2.patch
@@ -0,0 +1,13 @@
+diff -urN freeglut-2.4.0.old/src/freeglut_joystick.c freeglut-2.4.0/src/freeglut_joystick.c
+--- freeglut-2.4.0.old/src/freeglut_joystick.c	2007-06-16 03:51:41.000000000 +0000
++++ freeglut-2.4.0/src/freeglut_joystick.c	2007-06-16 03:54:27.000000000 +0000
+@@ -1682,9 +1682,6 @@
+ 
+   fgInitialiseJoysticks ();
+ 
+-  if ( !fgJoystick )
+-    return 0;
+-
+   if ( !fgState.JoysticksInitialised )
+     return 0;
+ 
diff --git a/pkgs/development/libraries/gamin/default.nix b/pkgs/development/libraries/gamin/default.nix
new file mode 100644
index 00000000000..a6ae0bacb22
--- /dev/null
+++ b/pkgs/development/libraries/gamin/default.nix
@@ -0,0 +1,12 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "gamin-0.1.9";
+
+	src = fetchurl {
+		url = "http://www.gnome.org/~veillard/gamin/sources/${name}.tar.gz";
+		sha256 = "0fgjfyr0nlkpdxj94a4qfm82wypljdyv1b6l56v7i9jdx0hcdqhr";
+	};
+
+	buildInputs = [python pkgconfig glib];
+	configureFlags = "--enable-shared --disable-static --disable-debug";
+}
diff --git a/pkgs/development/libraries/geos/default.nix b/pkgs/development/libraries/geos/default.nix
new file mode 100644
index 00000000000..bcfe8f757a2
--- /dev/null
+++ b/pkgs/development/libraries/geos/default.nix
@@ -0,0 +1,42 @@
+args:
+( args.mkDerivationByConfiguration {
+
+    flagConfig = {
+      mandatory = { implies = "python"; 
+                    buildInputs = [ "which" ]; # which is needed for the autogen.sh
+                  };
+    # python and ruby untested 
+      python =            { cfgOption = "--enable-python"; #Enable build of python module
+                            buildInputs=["python"] ++ (if args.use_svn then ["libtool" "autoconf" "automake" "swig"] else []); 
+                          };
+      ruby =              { cfgOption = "--enable-ruby"; };  #Enable build of ruby module
+    }; 
+
+    extraAttrs = co : {
+      name = "geos-3.0.0rc4";
+
+      src = if (args.use_svn) then
+        args.fetchsvn { 
+            url = http://svn.osgeo.org/geos/trunk; 
+            md5 = "b46f5ea517a337064006bab92f3090d4";
+        } else args.fetchurl {
+          url = http://geos.refractions.net/geos-3.0.0rc4.tar.bz2;
+          sha256 = "0pgwwv8q4p234r2jwdkaxcf68z2fwgmkc74c6dnmms2sdwkb5lbw";
+        };
+
+      configurePhase = "
+        [ -f configure ] || \\
+        LIBTOOLIZE=libtoolize ./autogen.sh
+        #{ automake --add-missing; autoconf; }
+        unset configurePhase; configurePhase
+        ";
+
+      meta = {
+          description = "C++ port of the Java Topology Suite (JTS)"
+            + "- all the OpenGIS \"Simple Features for SQL\" spatial predicate functions and spatial operators,"
+            + " as well as specific JTS topology functions such as IsValid";
+          homepage = http://geos.refractions.net/;
+          license = "GPL";
+      };
+  };
+} ) args
diff --git a/pkgs/development/libraries/gettext/0.14.6.nix b/pkgs/development/libraries/gettext/0.14.6.nix
index fefa8dbe5c7..bceacd318ec 100644
--- a/pkgs/development/libraries/gettext/0.14.6.nix
+++ b/pkgs/development/libraries/gettext/0.14.6.nix
@@ -1,4 +1,5 @@
-{stdenv, fetchurl}: stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "gettext-0.14.6";
   src = fetchurl {
     url = mirror://gnu/gettext/gettext-0.14.6.tar.gz;
diff --git a/pkgs/development/libraries/gettext/0.15.nix b/pkgs/development/libraries/gettext/0.15.nix
index fec9c348afc..0c417aafe50 100644
--- a/pkgs/development/libraries/gettext/0.15.nix
+++ b/pkgs/development/libraries/gettext/0.15.nix
@@ -1,4 +1,5 @@
-{stdenv, fetchurl}: stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "gettext-0.15";
   src = fetchurl {
     url = mirror://gnu/gettext/gettext-0.15.tar.gz;
diff --git a/pkgs/development/libraries/gettext/0.16.x.nix b/pkgs/development/libraries/gettext/0.16.x.nix
index 9e832889e42..d9b8cabef1d 100644
--- a/pkgs/development/libraries/gettext/0.16.x.nix
+++ b/pkgs/development/libraries/gettext/0.16.x.nix
@@ -1,4 +1,5 @@
-{stdenv, fetchurl}: stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "gettext-0.16.1";
   src = fetchurl {
     url = mirror://gnu/gettext/gettext-0.16.1.tar.gz;
diff --git a/pkgs/development/libraries/gettext/default.nix b/pkgs/development/libraries/gettext/default.nix
deleted file mode 100644
index 54a0d36cf76..00000000000
--- a/pkgs/development/libraries/gettext/default.nix
+++ /dev/null
@@ -1,8 +0,0 @@
-args:
-rec {
-	recurseForDerivations = true;
-	default = v_0_14_6;
-	v_0_14_6 = (import ./0.14.6.nix) args;
-	v_0_15 = (import ./0.15.nix) args;
-	v_0_16_x = (import ./0.16.x.nix) args;
-}
diff --git a/pkgs/development/libraries/giflib/default.nix b/pkgs/development/libraries/giflib/default.nix
new file mode 100644
index 00000000000..35d66b3647b
--- /dev/null
+++ b/pkgs/development/libraries/giflib/default.nix
@@ -0,0 +1,10 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "giflib-4.1.6";
+  src = fetchurl {
+    url = mirror://sourceforge/giflib/giflib-4.1.6.tar.bz2;
+    sha256 = "1v9b7ywz7qg8hli0s9vv1b8q9xxb2xvqq2mg1zpr73xwqpcwxhg1";
+  };
+}
+
diff --git a/pkgs/development/libraries/libungif/default.nix b/pkgs/development/libraries/giflib/libungif.nix
index b0bbb46eaf5..f3302f8f333 100644
--- a/pkgs/development/libraries/libungif/default.nix
+++ b/pkgs/development/libraries/giflib/libungif.nix
@@ -3,7 +3,7 @@
 stdenv.mkDerivation {
   name = "libungif-4.1.4";
   src = fetchurl {
-    url = mirror://sourceforge/libungif/libungif-4.1.4.tar.gz;
+    url = mirror://sourceforge/giflib/libungif-4.1.4.tar.gz;
     md5 = "efdfcf8e32e35740288a8c5625a70ccb";
   };
 }
diff --git a/pkgs/development/libraries/glew/default.nix b/pkgs/development/libraries/glew/default.nix
new file mode 100644
index 00000000000..82925d144b5
--- /dev/null
+++ b/pkgs/development/libraries/glew/default.nix
@@ -0,0 +1,19 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "glew-1.5.0";
+
+  src = fetchurl {
+    url = http://dfn.dl.sourceforge.net/sourceforge/glew/glew-1.5.0-src.tgz;
+    sha256 = "1kjr1fchnl785wsg11vzc03q3pm12lh20n1i593zr1xqfjgx2b4h";
+  };
+
+  buildInputs = [mesa x11 libXmu libXi];
+
+  meta = { 
+      description = "cross-platform open-source C/C++ extension loading library";
+      homepage = http://glew.sourceforge.net/;
+      license = ["BSD" "GLX" "SGI-B" "GPL2"]; # License description copied from gentoo-1.4.0 
+  };
+
+  installPhase="GLEW_DEST=\$out make install";
+}
diff --git a/pkgs/development/libraries/glibc/builder.sh b/pkgs/development/libraries/glibc-2.5/builder.sh
index 8d5d6908f04..8d5d6908f04 100644
--- a/pkgs/development/libraries/glibc/builder.sh
+++ b/pkgs/development/libraries/glibc-2.5/builder.sh
diff --git a/pkgs/development/libraries/glibc/default.nix b/pkgs/development/libraries/glibc-2.5/default.nix
index e4720cf56d5..e4720cf56d5 100644
--- a/pkgs/development/libraries/glibc/default.nix
+++ b/pkgs/development/libraries/glibc-2.5/default.nix
diff --git a/pkgs/development/libraries/glibc-nptl/glibc-getcwd-param-MAX.patch b/pkgs/development/libraries/glibc-2.5/glibc-getcwd-param-MAX.patch
index 8543dbbf1d7..8543dbbf1d7 100644
--- a/pkgs/development/libraries/glibc-nptl/glibc-getcwd-param-MAX.patch
+++ b/pkgs/development/libraries/glibc-2.5/glibc-getcwd-param-MAX.patch
diff --git a/pkgs/development/libraries/glibc-nptl/glibc-pwd.patch b/pkgs/development/libraries/glibc-2.5/glibc-pwd.patch
index 07039718477..07039718477 100644
--- a/pkgs/development/libraries/glibc-nptl/glibc-pwd.patch
+++ b/pkgs/development/libraries/glibc-2.5/glibc-pwd.patch
diff --git a/pkgs/development/libraries/glibc-nptl/builder.sh b/pkgs/development/libraries/glibc-2.7/builder.sh
index 3e874ed891c..f9b9c6b87aa 100644
--- a/pkgs/development/libraries/glibc-nptl/builder.sh
+++ b/pkgs/development/libraries/glibc-2.7/builder.sh
@@ -12,8 +12,9 @@ preConfigure=preConfigure
 preConfigure() {
 
     for i in configure io/ftwtest-sh; do
-        substituteInPlace "$i" \
-            --replace "@PWD@" "pwd"
+        # Can't use substituteInPlace here because replace hasn't been
+        # built yet in the bootstrap.
+        sed -i "$i" -e "s^/bin/pwd^$PWD_P^g"
     done
 
     # In the glibc 2.6/2.7 tarballs C-translit.h is a little bit older
diff --git a/pkgs/development/libraries/glibc-nptl/default.nix b/pkgs/development/libraries/glibc-2.7/default.nix
index 8a5a84bd2c6..f33f95fda9f 100644
--- a/pkgs/development/libraries/glibc-nptl/default.nix
+++ b/pkgs/development/libraries/glibc-2.7/default.nix
@@ -12,8 +12,6 @@ stdenv.mkDerivation {
     sha256 = "06j5q20l11x8kcrl9bg15xgb1pw0w82pazikxf4zvq2fmhiaa922";
   };
 
-  patches = [ ./glibc-pwd.patch ./glibc-getcwd-param-MAX.patch ];
-
   inherit kernelHeaders installLocales;
 
   inherit (stdenv) is64bit;
diff --git a/pkgs/development/libraries/glibc/glibc-getcwd-param-MAX.patch b/pkgs/development/libraries/glibc-2.7/glibc-getcwd-param-MAX.patch
index 8543dbbf1d7..8543dbbf1d7 100644
--- a/pkgs/development/libraries/glibc/glibc-getcwd-param-MAX.patch
+++ b/pkgs/development/libraries/glibc-2.7/glibc-getcwd-param-MAX.patch
diff --git a/pkgs/development/libraries/glibc/glibc-pwd.patch b/pkgs/development/libraries/glibc-2.7/glibc-pwd.patch
index 07039718477..07039718477 100644
--- a/pkgs/development/libraries/glibc/glibc-pwd.patch
+++ b/pkgs/development/libraries/glibc-2.7/glibc-pwd.patch
diff --git a/pkgs/development/libraries/gmp/default.nix b/pkgs/development/libraries/gmp/default.nix
index 364cb73bbb7..b8d915d1fac 100644
--- a/pkgs/development/libraries/gmp/default.nix
+++ b/pkgs/development/libraries/gmp/default.nix
@@ -1,11 +1,20 @@
 {stdenv, fetchurl, m4}:
 
 stdenv.mkDerivation {
-  name = "gmp-4.2.1";
+  name = "gmp-4.2.2";
+
   src = fetchurl {
-    url = mirror://gnu/gmp/gmp-4.2.1.tar.bz2;
-    md5 = "091c56e0e1cca6b09b17b69d47ef18e3";
+    url = mirror://gnu/gmp/gmp-4.2.2.tar.bz2;
+    sha256 = "0yv593sk62ypn21gg2x570g955lmsi4i6f2bc3s43p52myn0lb1b";
   };
+
   buildInputs = [m4];
+
   doCheck = true;
+
+  meta = {
+    description = "A free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers";
+    homepage = http://gmplib.org/;
+    license = "LGPL";
+  };
 }
diff --git a/pkgs/development/libraries/gpgme/default.nix b/pkgs/development/libraries/gpgme/default.nix
index 68bbbc40904..64f1a746b03 100644
--- a/pkgs/development/libraries/gpgme/default.nix
+++ b/pkgs/development/libraries/gpgme/default.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl, libgpgerror, gnupg}:
+args: with args;
 
 stdenv.mkDerivation {
   name = "gpgme-1.1.4";
@@ -6,5 +6,5 @@ stdenv.mkDerivation {
     url = ftp://ftp.gnupg.org/gcrypt/gpgme/gpgme-1.1.4.tar.bz2;
     sha256 = "0ncrv7p33rjq1avkxpp9x0gz6wna9y3b3dmw6nv366n5mgvxmpg8";
   };
-  buildInputs = [libgpgerror gnupg];
+  buildInputs = [libgpgerror gnupg gnupg2 pkgconfig glib pth];
 }
diff --git a/pkgs/development/libraries/gsl/default.nix b/pkgs/development/libraries/gsl/default.nix
new file mode 100644
index 00000000000..19655f97b0d
--- /dev/null
+++ b/pkgs/development/libraries/gsl/default.nix
@@ -0,0 +1,15 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "gsl-1.9";
+
+  src = fetchurl {
+    url = ftp://ftp.gnu.org/gnu/gsl/gsl-1.9.tar.gz;
+    sha256 = "0l12js65c1qf3s7gmgay6gj5nbs6635py41dj8nk3hlp95wcdlgw";
+  };
+
+  meta = { 
+      description = "numerical library (>1000 functions)";
+      homepage = http://www.gnu.org/software/gsl;
+      license = "GPL2";
+  };
+}
diff --git a/pkgs/development/libraries/gtk-libs-2.10/default.nix b/pkgs/development/libraries/gtk-libs-2.10/default.nix
deleted file mode 100644
index ed5ae35f05d..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.10/default.nix
+++ /dev/null
@@ -1,26 +0,0 @@
-{ xineramaSupport ? false
-, stdenv, fetchurl, pkgconfig, gettext, perl, x11
-, libtiff, libjpeg, libpng, cairo, libXinerama ? null, libXrandr
-}:
-
-rec {
-
-  glib = (import ./glib) {
-    inherit fetchurl stdenv pkgconfig gettext perl;
-  };
-
-  atk = (import ./atk) {
-    inherit fetchurl stdenv pkgconfig glib perl;
-  };
-
-  pango = (import ./pango) {
-    inherit fetchurl stdenv pkgconfig glib x11 cairo libpng;
-  };
-
-  gtk = (import ./gtk+) {
-    inherit fetchurl stdenv pkgconfig glib atk pango perl
-            libtiff libjpeg libpng x11 cairo libXinerama
-            xineramaSupport libXrandr;
-  };
-
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.10/gtk+/default.nix b/pkgs/development/libraries/gtk-libs-2.10/gtk+/default.nix
deleted file mode 100644
index 474c6499380..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.10/gtk+/default.nix
+++ /dev/null
@@ -1,22 +0,0 @@
-{ xineramaSupport ? false
-, stdenv, fetchurl, pkgconfig, x11, glib, atk
-, pango, perl, libtiff, libjpeg, libpng, cairo, libXinerama ? null, libXrandr
-}:
-
-assert x11.buildClientLibs;
-assert xineramaSupport -> libXinerama != null;
-
-
-stdenv.mkDerivation {
-  name = "gtk+-2.10.14";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.10/gtk+-2.10.14.tar.bz2;
-    sha256 = "1qjdx9kdc533dajdy1kv3ssxzh7gz7j7vzgw0ax910q4klil88yh";
-  };
-  buildInputs = [
-    pkgconfig perl libtiff libjpeg libpng cairo libXrandr
-    (if xineramaSupport then libXinerama else null)
-  ];
-  propagatedBuildInputs = [x11 glib atk pango];
-  inherit libtiff libjpeg libpng;
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.2/atk/default.nix b/pkgs/development/libraries/gtk-libs-2.2/atk/default.nix
deleted file mode 100644
index 1089f571099..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.2/atk/default.nix
+++ /dev/null
@@ -1,13 +0,0 @@
-{stdenv, fetchurl, pkgconfig, glib, perl}:
-
-assert pkgconfig != null && glib != null && perl != null;
-
-stdenv.mkDerivation {
-  name = "atk-1.2.4";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.2/atk-1.2.4.tar.bz2;
-    md5 = "2d6d50df31abe0e8892b5d3e7676a02d";
-  };
-  buildInputs = [pkgconfig perl];
-  propagatedBuildInputs = [glib];
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.2/glib/default.nix b/pkgs/development/libraries/gtk-libs-2.2/glib/default.nix
deleted file mode 100644
index 22d01d0d86f..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.2/glib/default.nix
+++ /dev/null
@@ -1,12 +0,0 @@
-{stdenv, fetchurl, pkgconfig, gettext, perl}:
-
-assert pkgconfig != null && gettext != null && perl != null;
-
-stdenv.mkDerivation {
-  name = "glib-2.2.3";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.2/glib-2.2.3.tar.bz2;
-    md5 = "aa214a10d873b68ddd67cd9de2ccae55";
-  };
-  buildInputs = [pkgconfig gettext perl];
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.2/gtk+/default.nix b/pkgs/development/libraries/gtk-libs-2.2/gtk+/default.nix
deleted file mode 100644
index e1eef805803..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.2/gtk+/default.nix
+++ /dev/null
@@ -1,21 +0,0 @@
-{ stdenv, fetchurl, pkgconfig, x11, glib, atk
-, pango, perl, libtiff, libjpeg, libpng}:
-
-assert pkgconfig != null && x11 != null && glib != null && atk != null
-  && pango != null && perl != null && perl != null && libtiff != null
-  && libjpeg != null && libpng != null;
-assert x11.buildClientLibs;
-#assert glib == atk.glib;
-#assert glib == pango.glib;
-#assert x11 == pango.x11;
-
-stdenv.mkDerivation {
-  name = "gtk+-2.2.4";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.2/gtk+-2.2.4.tar.bz2;
-    md5 = "605332199533e73bc6eec481fb4f1671";
-  };
-  buildInputs = [pkgconfig perl libtiff libjpeg libpng];
-  propagatedBuildInputs = [x11 glib atk pango];
-  inherit libtiff libjpeg libpng;
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.2/pango/default.nix b/pkgs/development/libraries/gtk-libs-2.2/pango/default.nix
deleted file mode 100644
index 5d5e5184dda..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.2/pango/default.nix
+++ /dev/null
@@ -1,14 +0,0 @@
-{stdenv, fetchurl, pkgconfig, x11, glib}:
-
-assert pkgconfig != null && x11 != null && glib != null;
-assert x11.buildClientLibs;
-
-stdenv.mkDerivation {
-  name = "pango-1.2.5";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.2/pango-1.2.5.tar.bz2;
-    md5 = "df00fe3e71cd297010f24f439b6c8ee6";
-  };
-  buildInputs = [pkgconfig];
-  propagatedBuildInputs = [x11 glib];
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.4/atk/default.nix b/pkgs/development/libraries/gtk-libs-2.4/atk/default.nix
deleted file mode 100644
index 095ff32b2aa..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.4/atk/default.nix
+++ /dev/null
@@ -1,13 +0,0 @@
-{stdenv, fetchurl, pkgconfig, glib, perl}:
-
-assert pkgconfig != null && glib != null && perl != null;
-
-stdenv.mkDerivation {
-  name = "atk-1.6.1";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.4/atk-1.6.1.tar.bz2;
-    md5 = "f77be7e128c957bd3056c2e270b5f283";
-  };
-  buildInputs = [pkgconfig perl];
-  propagatedBuildInputs = [glib];
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.4/default.nix b/pkgs/development/libraries/gtk-libs-2.4/default.nix
deleted file mode 100644
index dc01a534d81..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.4/default.nix
+++ /dev/null
@@ -1,23 +0,0 @@
-{ stdenv, fetchurl, pkgconfig, gettext, perl, x11
-, libtiff, libjpeg, libpng}:
-
-rec {
-
-  glib = (import ./glib) {
-    inherit fetchurl stdenv pkgconfig gettext perl;
-  };
-
-  atk = (import ./atk) {
-    inherit fetchurl stdenv pkgconfig glib perl;
-  };
-
-  pango = (import ./pango) {
-    inherit fetchurl stdenv pkgconfig glib x11;
-  };
-
-  gtk = (import ./gtk+) {
-    inherit fetchurl stdenv pkgconfig glib atk pango perl
-            libtiff libjpeg libpng x11;
-  };
-
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.4/glib/default.nix b/pkgs/development/libraries/gtk-libs-2.4/glib/default.nix
deleted file mode 100644
index 58f91b3f83c..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.4/glib/default.nix
+++ /dev/null
@@ -1,12 +0,0 @@
-{stdenv, fetchurl, pkgconfig, gettext, perl}:
-
-assert pkgconfig != null && gettext != null && perl != null;
-
-stdenv.mkDerivation {
-  name = "glib-2.4.7";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.4/glib-2.4.7.tar.bz2;
-    md5 = "eff6fec89455addf8b0dee5a19e343be";
-  };
-  buildInputs = [pkgconfig gettext perl];
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.4/gtk+/default.nix b/pkgs/development/libraries/gtk-libs-2.4/gtk+/default.nix
deleted file mode 100644
index 56a6e41e731..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.4/gtk+/default.nix
+++ /dev/null
@@ -1,21 +0,0 @@
-{ stdenv, fetchurl, pkgconfig, x11, glib, atk
-, pango, perl, libtiff, libjpeg, libpng}:
-
-assert pkgconfig != null && x11 != null && glib != null && atk != null
-  && pango != null && perl != null && perl != null && libtiff != null
-  && libjpeg != null && libpng != null;
-assert x11.buildClientLibs;
-#assert glib == atk.glib;
-#assert glib == pango.glib;
-#assert x11 == pango.x11;
-
-stdenv.mkDerivation {
-  name = "gtk+-2.4.13";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.4/gtk+-2.4.13.tar.bz2;
-    md5 = "3a438e1010704b11acaf060c9ba0fd7b";
-  };
-  buildInputs = [pkgconfig perl libtiff libjpeg libpng];
-  propagatedBuildInputs = [x11 glib atk pango];
-  inherit libtiff libjpeg libpng;
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.4/pango/default.nix b/pkgs/development/libraries/gtk-libs-2.4/pango/default.nix
deleted file mode 100644
index 986891b98b9..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.4/pango/default.nix
+++ /dev/null
@@ -1,14 +0,0 @@
-{stdenv, fetchurl, pkgconfig, x11, glib}:
-
-assert pkgconfig != null && x11 != null && glib != null;
-assert x11.buildClientLibs;
-
-stdenv.mkDerivation {
-  name = "pango-1.4.1";
-  src = fetchurl {
-    url = ftp://ftp.gtk.org/pub/gtk/v2.4/pango-1.4.1.tar.bz2;
-    md5 = "39868e0da250fd4c00b2970e4eb84389";
-  };
-  buildInputs = [pkgconfig];
-  propagatedBuildInputs = [x11 glib];
-}
diff --git a/pkgs/development/libraries/gtk-libs-2.6/default.nix b/pkgs/development/libraries/gtk-libs-2.6/default.nix
deleted file mode 100644
index dc01a534d81..00000000000
--- a/pkgs/development/libraries/gtk-libs-2.6/default.nix
+++ /dev/null
@@ -1,23 +0,0 @@
-{ stdenv, fetchurl, pkgconfig, gettext, perl, x11
-, libtiff, libjpeg, libpng}:
-
-rec {
-
-  glib = (import ./glib) {
-    inherit fetchurl stdenv pkgconfig gettext perl;
-  };
-
-  atk = (import ./atk) {
-    inherit fetchurl stdenv pkgconfig glib perl;
-  };
-
-  pango = (import ./pango) {
-    inherit fetchurl stdenv pkgconfig glib x11;
-  };
-
-  gtk = (import ./gtk+) {
-    inherit fetchurl stdenv pkgconfig glib atk pango perl
-            libtiff libjpeg libpng x11;
-  };
-
-}
diff --git a/pkgs/development/libraries/gtk-libs-1.x/default.nix b/pkgs/development/libraries/gtk-libs/1.x/default.nix
index 0e86abd788b..0e86abd788b 100644
--- a/pkgs/development/libraries/gtk-libs-1.x/default.nix
+++ b/pkgs/development/libraries/gtk-libs/1.x/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-1.x/gdk-pixbuf/default.nix b/pkgs/development/libraries/gtk-libs/1.x/gdk-pixbuf/default.nix
index 4e28a78930f..4e28a78930f 100644
--- a/pkgs/development/libraries/gtk-libs-1.x/gdk-pixbuf/default.nix
+++ b/pkgs/development/libraries/gtk-libs/1.x/gdk-pixbuf/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-1.x/glib/default.nix b/pkgs/development/libraries/gtk-libs/1.x/glib/default.nix
index 8aa5005b617..8aa5005b617 100644
--- a/pkgs/development/libraries/gtk-libs-1.x/glib/default.nix
+++ b/pkgs/development/libraries/gtk-libs/1.x/glib/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-1.x/glib/gcc34.patch b/pkgs/development/libraries/gtk-libs/1.x/glib/gcc34.patch
index 13d35c82209..13d35c82209 100644
--- a/pkgs/development/libraries/gtk-libs-1.x/glib/gcc34.patch
+++ b/pkgs/development/libraries/gtk-libs/1.x/glib/gcc34.patch
diff --git a/pkgs/development/libraries/gtk-libs-1.x/gtk+/builder.sh b/pkgs/development/libraries/gtk-libs/1.x/gtk+/builder.sh
index da9b8dc6128..da9b8dc6128 100644
--- a/pkgs/development/libraries/gtk-libs-1.x/gtk+/builder.sh
+++ b/pkgs/development/libraries/gtk-libs/1.x/gtk+/builder.sh
diff --git a/pkgs/development/libraries/gtk-libs-1.x/gtk+/default.nix b/pkgs/development/libraries/gtk-libs/1.x/gtk+/default.nix
index 7762ee57b77..7762ee57b77 100644
--- a/pkgs/development/libraries/gtk-libs-1.x/gtk+/default.nix
+++ b/pkgs/development/libraries/gtk-libs/1.x/gtk+/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.10/atk/default.nix b/pkgs/development/libraries/gtk-libs/2.10/atk/default.nix
index 34d23bc6daa..1dae480423f 100644
--- a/pkgs/development/libraries/gtk-libs-2.10/atk/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.10/atk/default.nix
@@ -1,6 +1,4 @@
-{stdenv, fetchurl, pkgconfig, glib, perl}:
-
-assert pkgconfig != null && glib != null && perl != null;
+args: with args;
 
 stdenv.mkDerivation {
   name = "atk-1.12.4";
diff --git a/pkgs/development/libraries/gtk-libs/2.10/default.nix b/pkgs/development/libraries/gtk-libs/2.10/default.nix
new file mode 100644
index 00000000000..0fc77dde627
--- /dev/null
+++ b/pkgs/development/libraries/gtk-libs/2.10/default.nix
@@ -0,0 +1,16 @@
+args: with args;
+
+rec {
+
+  glib = (import ./glib) args;
+
+  atk = (import ./atk) (args // { inherit glib; });
+
+  pango = (import ./pango) (args // { inherit glib; });
+
+  gtk = (import ./gtk+) (args // { inherit glib atk pango; } );
+
+  glibmm = (import ./glibmm) (args // { inherit glib; });
+
+  gtkmm = (import ./gtkmm) (args // { inherit gtk atk glibmm; });
+}
diff --git a/pkgs/development/libraries/gtk-libs-2.10/glib/default.nix b/pkgs/development/libraries/gtk-libs/2.10/glib/default.nix
index b29f6b62f93..9af2ab959b1 100644
--- a/pkgs/development/libraries/gtk-libs-2.10/glib/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.10/glib/default.nix
@@ -1,6 +1,4 @@
-{stdenv, fetchurl, pkgconfig, gettext, perl}:
-
-assert pkgconfig != null && gettext != null && perl != null;
+args: with args;
 
 stdenv.mkDerivation {
   name = "glib-2.12.13"; # <- sic! gtk 2.10 needs glib 2.12
diff --git a/pkgs/development/libraries/gtk-libs-2.10/glibmm/default.nix b/pkgs/development/libraries/gtk-libs/2.10/glibmm/default.nix
index e1d275b9974..bbdde49b75d 100644
--- a/pkgs/development/libraries/gtk-libs-2.10/glibmm/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.10/glibmm/default.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl, pkgconfig, glib, libsigcxx}:
+args: with args;
 
 stdenv.mkDerivation {
   name = "glibmm-2.12.10";
@@ -7,6 +7,7 @@ stdenv.mkDerivation {
     sha256 = "02rjjdh0f6kafa1sn4y5ykvm4f2qn3yh4kr4lngcv7vzasqn1dr1";
   };
 
-  buildInputs = [pkgconfig glib libsigcxx];
+  buildInputs = [pkgconfig];
+  propagatedBuildInputs = [glib libsigcxx];
 }
 
diff --git a/pkgs/development/libraries/gtk-libs/2.10/gtk+/default.nix b/pkgs/development/libraries/gtk-libs/2.10/gtk+/default.nix
new file mode 100644
index 00000000000..a819c1fc275
--- /dev/null
+++ b/pkgs/development/libraries/gtk-libs/2.10/gtk+/default.nix
@@ -0,0 +1,13 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "gtk+-2.10.14";
+  src = fetchurl {
+    url = ftp://ftp.gtk.org/pub/gtk/v2.10/gtk+-2.10.14.tar.bz2;
+    sha256 = "1qjdx9kdc533dajdy1kv3ssxzh7gz7j7vzgw0ax910q4klil88yh";
+  };
+  buildInputs = [ pkgconfig perl ];
+  propagatedBuildInputs = [x11 glib atk pango libtiff libjpeg libpng cairo
+    libXrandr (if xineramaSupport then libXinerama else null)];
+  passthru = { inherit libtiff libjpeg libpng; };
+}
diff --git a/pkgs/development/libraries/gtk-libs-2.10/gtkmm/default.nix b/pkgs/development/libraries/gtk-libs/2.10/gtkmm/default.nix
index 4f476f73d50..9a44e9a6ba2 100644
--- a/pkgs/development/libraries/gtk-libs-2.10/gtkmm/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.10/gtkmm/default.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchurl, pkgconfig, gtk, atk, glibmm, libsigcxx}:
+args: with args;
 
 stdenv.mkDerivation {
   name = "gtkmm-2.10.11";
@@ -7,6 +7,7 @@ stdenv.mkDerivation {
     sha256 = "1bri9r0k69dmi5xgzrlfllp3adfzhz8dh9zkcvi6sjkgfwi594vx";
   };
 
-  buildInputs = [pkgconfig gtk atk glibmm libsigcxx];
+  buildInputs = [pkgconfig];
+  propagatedBuildInputs = [glibmm gtk atk cairomm];
 }
 
diff --git a/pkgs/development/libraries/gtk-libs-2.10/pango/default.nix b/pkgs/development/libraries/gtk-libs/2.10/pango/default.nix
index 25d4aa17e91..faf5ffb4724 100644
--- a/pkgs/development/libraries/gtk-libs-2.10/pango/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.10/pango/default.nix
@@ -1,6 +1,4 @@
-{stdenv, fetchurl, pkgconfig, x11, glib, cairo, libpng}:
-
-assert x11.buildClientLibs;
+args: with args;
 
 stdenv.mkDerivation {
   name = "pango-1.14.10";
@@ -8,6 +6,6 @@ stdenv.mkDerivation {
     url = ftp://ftp.gtk.org/pub/pango/1.14/pango-1.14.10.tar.bz2;
     md5 = "e9fc2f8168e74e2fa0aa8238ee0e9c06";
   };
-  buildInputs = [pkgconfig libpng];
-  propagatedBuildInputs = [x11 glib cairo];
+  buildInputs = [pkgconfig];
+  propagatedBuildInputs = [x11 glib cairo libpng];
 }
diff --git a/pkgs/development/libraries/gtk-libs-2.6/atk/default.nix b/pkgs/development/libraries/gtk-libs/2.6/atk/default.nix
index 66720d4dbeb..66720d4dbeb 100644
--- a/pkgs/development/libraries/gtk-libs-2.6/atk/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.6/atk/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.2/default.nix b/pkgs/development/libraries/gtk-libs/2.6/default.nix
index dc01a534d81..dc01a534d81 100644
--- a/pkgs/development/libraries/gtk-libs-2.2/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.6/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.6/glib/default.nix b/pkgs/development/libraries/gtk-libs/2.6/glib/default.nix
index 1dc3407a76e..1dc3407a76e 100644
--- a/pkgs/development/libraries/gtk-libs-2.6/glib/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.6/glib/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.6/glibmm/default.nix b/pkgs/development/libraries/gtk-libs/2.6/glibmm/default.nix
index 957c596fc7b..957c596fc7b 100644
--- a/pkgs/development/libraries/gtk-libs-2.6/glibmm/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.6/glibmm/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.6/gtk+/default.nix b/pkgs/development/libraries/gtk-libs/2.6/gtk+/default.nix
index 06e37f070da..06e37f070da 100644
--- a/pkgs/development/libraries/gtk-libs-2.6/gtk+/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.6/gtk+/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.6/gtkmm/default.nix b/pkgs/development/libraries/gtk-libs/2.6/gtkmm/default.nix
index ebc1e881c47..ebc1e881c47 100644
--- a/pkgs/development/libraries/gtk-libs-2.6/gtkmm/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.6/gtkmm/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.6/pango/default.nix b/pkgs/development/libraries/gtk-libs/2.6/pango/default.nix
index 6b9391e0a0b..6b9391e0a0b 100644
--- a/pkgs/development/libraries/gtk-libs-2.6/pango/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.6/pango/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.8/atk/default.nix b/pkgs/development/libraries/gtk-libs/2.8/atk/default.nix
index 07537567520..07537567520 100644
--- a/pkgs/development/libraries/gtk-libs-2.8/atk/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.8/atk/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.8/default.nix b/pkgs/development/libraries/gtk-libs/2.8/default.nix
index ee5abd562b1..ee5abd562b1 100644
--- a/pkgs/development/libraries/gtk-libs-2.8/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.8/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.8/glib/default.nix b/pkgs/development/libraries/gtk-libs/2.8/glib/default.nix
index f73a1f388f4..f73a1f388f4 100644
--- a/pkgs/development/libraries/gtk-libs-2.8/glib/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.8/glib/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.8/glibmm/default.nix b/pkgs/development/libraries/gtk-libs/2.8/glibmm/default.nix
index 957c596fc7b..957c596fc7b 100644
--- a/pkgs/development/libraries/gtk-libs-2.8/glibmm/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.8/glibmm/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.8/gtk+/default.nix b/pkgs/development/libraries/gtk-libs/2.8/gtk+/default.nix
index c5a012d9baa..c5a012d9baa 100644
--- a/pkgs/development/libraries/gtk-libs-2.8/gtk+/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.8/gtk+/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.8/gtkmm/default.nix b/pkgs/development/libraries/gtk-libs/2.8/gtkmm/default.nix
index ebc1e881c47..ebc1e881c47 100644
--- a/pkgs/development/libraries/gtk-libs-2.8/gtkmm/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.8/gtkmm/default.nix
diff --git a/pkgs/development/libraries/gtk-libs-2.8/pango/default.nix b/pkgs/development/libraries/gtk-libs/2.8/pango/default.nix
index 9e3296e00a1..9e3296e00a1 100644
--- a/pkgs/development/libraries/gtk-libs-2.8/pango/default.nix
+++ b/pkgs/development/libraries/gtk-libs/2.8/pango/default.nix
diff --git a/pkgs/development/libraries/haskell/Crypto/default.nix b/pkgs/development/libraries/haskell/Crypto/default.nix
new file mode 100644
index 00000000000..9cb465e50b3
--- /dev/null
+++ b/pkgs/development/libraries/haskell/Crypto/default.nix
@@ -0,0 +1,11 @@
+{cabal}:
+
+cabal.mkDerivation (self : {
+  pname = "Crypto";
+  version = "4.1.0";
+  sha256 = "0984c833c5dfa6f4d56fd6fb284db7b7cef6676dc7999a1436aa856becba2b8f";
+  meta = {
+    description = "Several encryption algorithms for Haskell";
+  };
+})  
+
diff --git a/pkgs/development/libraries/haskell/HDBC/HDBC-1.1.4.nix b/pkgs/development/libraries/haskell/HDBC/HDBC-1.1.4.nix
new file mode 100644
index 00000000000..429407d25d2
--- /dev/null
+++ b/pkgs/development/libraries/haskell/HDBC/HDBC-1.1.4.nix
@@ -0,0 +1,10 @@
+{cabal}:
+
+cabal.mkDerivation (self : {
+  pname = "HDBC";
+  version = "1.1.4";
+  sha256 = "de03020874b532f7aa734f093caf0709e7d33d0d64c59ce0a003b2269fc85597";
+  meta = {
+    description = "HDBC provides an abstraction layer between Haskell programs and SQL relational databases";
+  };
+})
diff --git a/pkgs/development/libraries/haskell/HDBC/HDBC-postgresql-1.1.4.0.nix b/pkgs/development/libraries/haskell/HDBC/HDBC-postgresql-1.1.4.0.nix
new file mode 100644
index 00000000000..d9a1985839c
--- /dev/null
+++ b/pkgs/development/libraries/haskell/HDBC/HDBC-postgresql-1.1.4.0.nix
@@ -0,0 +1,12 @@
+{cabal, HDBC, postgresql}:
+
+cabal.mkDerivation (self : {
+  pname = "HDBC-postgresql";
+  version = "1.1.4.0";
+  sha256 = "039eae03693330fee0e4083e22d502f94865969b243744a939786f598aec34ad";
+  meta = {
+    description = "This package provides a PostgreSQL driver for HDBC";
+  };
+  propagatedBuildInputs = [HDBC postgresql];
+})
+
diff --git a/pkgs/development/libraries/haskell/HDBC/HDBC-sqlite3-1.1.4.0.nix b/pkgs/development/libraries/haskell/HDBC/HDBC-sqlite3-1.1.4.0.nix
new file mode 100644
index 00000000000..b0c7eb27e6a
--- /dev/null
+++ b/pkgs/development/libraries/haskell/HDBC/HDBC-sqlite3-1.1.4.0.nix
@@ -0,0 +1,12 @@
+{cabal, HDBC, sqlite}:
+
+cabal.mkDerivation (self : {
+  pname = "HDBC-sqlite3";
+  version = "1.1.4.0";
+  sha256 = "328fed8d4cdba4311efd50d9d60591a81481317ddba10c58fbaa2ec7f418f788";
+  meta = {
+    description = "This is the Sqlite v3 driver for HDBC, the generic database access system for Haskell";
+  };
+  propagatedBuildInputs = [HDBC sqlite];
+})
+
diff --git a/pkgs/development/libraries/haskell/X11/default.nix b/pkgs/development/libraries/haskell/X11/default.nix
new file mode 100644
index 00000000000..39fb5628467
--- /dev/null
+++ b/pkgs/development/libraries/haskell/X11/default.nix
@@ -0,0 +1,13 @@
+{cabal, libX11, xineramaSupport ? true, libXinerama ? null, libXext ? null}:
+
+assert xineramaSupport -> (libXinerama != null && libXext != null);
+
+cabal.mkDerivation (self : {
+  pname = "X11";
+  version = "1.4.1";
+  sha256 = "e51038541415686f0e278ccdbc0b2373cd11f212de99023b7b8f8e776aa09f79";
+  propagatedBuildInputs = [libX11] ++ (if xineramaSupport then [libXinerama libXext] else []);
+  meta = {
+    description = "A Haskell binding to the X11 graphics library";
+  };
+})
diff --git a/pkgs/development/libraries/haskell/binary/default.nix b/pkgs/development/libraries/haskell/binary/default.nix
new file mode 100644
index 00000000000..081779fd312
--- /dev/null
+++ b/pkgs/development/libraries/haskell/binary/default.nix
@@ -0,0 +1,11 @@
+{cabal}:
+
+cabal.mkDerivation (self : {
+  pname = "binary";
+  version = "0.4.1";
+  sha256 = "bb74824306843da25f6d97c271e2a06ee3a7e05fc529156fb81d7c576688e549";
+  meta = {
+    description = "Efficient, pure binary serialisation using lazy ByteStrings";
+  };
+})  
+
diff --git a/pkgs/development/libraries/haskell/cabal/cabal.nix b/pkgs/development/libraries/haskell/cabal/cabal.nix
new file mode 100644
index 00000000000..bafcedced63
--- /dev/null
+++ b/pkgs/development/libraries/haskell/cabal/cabal.nix
@@ -0,0 +1,95 @@
+# generic builder for Cabal packages
+
+attrs :
+{
+  mkDerivation =
+    transform :
+    let dtransform =
+          self : {
+
+            # pname should be defined by the client to be the package basename
+            # version should be defined by the client to be the package version
+ 
+            # fname is the internal full name of the package
+            fname = "${self.pname}-${self.version}";
+
+	    # name is the external full name of the package; usually we prefix
+	    # all packages with haskell- to avoid name clashes for libraries;
+	    # if that is not desired (for applications), name can be set to
+	    # fname.
+            name = "haskell-${self.fname}"; 
+
+            # the default download location for Cabal packages is Hackage,
+            # you still have to specify the checksum
+            src = attrs.fetchurl {
+              url = "http://hackage.haskell.org/packages/archive/${self.pname}/${self.version}/${self.fname}.tar.gz";
+              inherit (self) sha256;
+            };
+
+            # default buildInputs are just ghc, if more buildInputs are required
+            # buildInputs can be extended by the client by using extraBuildInputs,
+            # but often propagatedBuildInputs is preferable anyway
+            buildInputs = [attrs.ghc] ++ self.extraBuildInputs;
+            extraBuildInputs = [];
+
+            # we make sure that propagatedBuildInputs is defined, so that we don't
+            # have to check for its existence
+            propagatedBuildInputs = [];
+
+            # library directories that have to be added to the Cabal files
+            extraLibDirs = map (x : x + "/lib") self.propagatedBuildInputs;
+
+            # file(s) that have to be patched with information about extra libraries;
+            # can be redefined to the empty list by the client if this is not desired
+            patchLibFiles = [ "${self.pname}.cabal" ];
+
+            # patches files, compiles Setup, and configures
+            configurePhase = ''
+              eval "$preConfigure"
+
+              for i in ${toString self.patchLibFiles}; do
+                echo "patching $i"
+                test -f $i && sed -i '/[eE]xtra-[lL]ibraries/ { s|\( *\)[eE]xtra-[lL]ibraries.*|&\n\1extra-lib-dirs: ${toString self.extraLibDirs}| }' $i
+              done
+              for i in Setup.hs Setup.lhs; do
+                test -f $i && ghc --make $i
+              done
+              ./Setup configure --verbose --prefix="$out"
+
+              eval "$postConfigure"
+            '';
+
+            # builds via Cabal
+            buildPhase = ''
+              eval "$preBuild"
+
+              ./Setup build
+
+              eval "$postBuild"
+            '';
+
+	    # installs via Cabal; creates a registration file for nix-support
+	    # so that the package can be used in other Haskell-builds; also
+	    # creates a register-${name}.sh in userspace that can be used to
+	    # register the library in a user environment (but this scheme
+	    # should sooner or later be deprecated in favour of using a
+	    # ghc-wrapper).
+            installPhase = ''
+              eval "$preInstall"
+
+              ./Setup copy
+              ./Setup register --gen-script
+              mkdir -p $out/nix-support
+              if test -f register.sh; then
+                sed -i 's/|.*\(ghc-pkg update\)/| \1/' register.sh
+                cp register.sh $out/nix-support/register-ghclib.sh
+                sed -i 's/\(ghc-pkg update\)/\1 --user/' register.sh
+                mkdir -p $out/bin
+                cp register.sh $out/bin/register-${self.name}.sh
+              fi
+
+              eval "$postInstall"
+            '';
+          };
+    in  attrs.stdenv.mkDerivation ((rec { f = dtransform f // transform f; }).f);
+} 
diff --git a/pkgs/development/libraries/haskell/gtk2hs/default.nix b/pkgs/development/libraries/haskell/gtk2hs/default.nix
new file mode 100644
index 00000000000..e49f4d7113e
--- /dev/null
+++ b/pkgs/development/libraries/haskell/gtk2hs/default.nix
@@ -0,0 +1,20 @@
+{stdenv, fetchurl, pkgconfig, ghc, gtk, cairo, GConf, libglade
+, glib, libgtkhtml, gtkhtml}:
+
+stdenv.mkDerivation (rec {
+  pname = "gtk2hs";
+  version = "0.9.12.1";
+  fname = "${pname}-${version}";
+  name = "haskell-${fname}";
+  src = fetchurl {
+    url = "mirror://sourceforge/${pname}/${fname}.tar.gz";
+    sha256 = "110z6v9gzhg6nzlz5gs8aafmipbva6rc50b8z1jgq0k2g25hfy22";
+  };
+
+  buildInputs = [pkgconfig ghc gtk glib cairo GConf libglade libgtkhtml gtkhtml];
+
+  configureFlags = [
+    "--enable-cairo"
+  ];
+
+})
diff --git a/pkgs/development/libraries/haskell/pcre-light/default.nix b/pkgs/development/libraries/haskell/pcre-light/default.nix
new file mode 100644
index 00000000000..1542bb7968a
--- /dev/null
+++ b/pkgs/development/libraries/haskell/pcre-light/default.nix
@@ -0,0 +1,12 @@
+{cabal, pcre}:
+
+cabal.mkDerivation (self : {
+  pname = "pcre-light";
+  version = "0.3";
+  sha256 = "a8cfec1c265530388efbb187426368e280331d9829fa93d8f49f16db3c3e7794";
+  propagatedBuildInputs = [pcre];
+  meta = {
+    description = "A small, efficient and portable regex library for Perl 5 compatible regular expressions";
+  };
+})  
+
diff --git a/pkgs/development/libraries/haskell/uulib-ghc-6.6/builder.sh b/pkgs/development/libraries/haskell/uulib-ghc-6.6/builder.sh
deleted file mode 100644
index bbe21eac49e..00000000000
--- a/pkgs/development/libraries/haskell/uulib-ghc-6.6/builder.sh
+++ /dev/null
@@ -1,21 +0,0 @@
-source $stdenv/setup
-
-
-tar xzf "$src" &&
-cd uulib-* &&
-
-
-autoconf &&
-./configure --prefix=$out &&
-
-
-ghc --make Setup.hs -o setup -package Cabal &&
-./setup configure --prefix=$out --with-hc-pkg=ghc-pkg &&
-
-
-./setup build &&
-./setup install &&
-./setup register --gen-script &&
-
-mkdir -p $out/nix-support/ &&
-cp register.sh $out/nix-support/register-ghclib.sh
diff --git a/pkgs/development/libraries/haskell/uulib-ghc-6.6/default.nix b/pkgs/development/libraries/haskell/uulib-ghc-6.6/default.nix
deleted file mode 100644
index 1c315b1cffa..00000000000
--- a/pkgs/development/libraries/haskell/uulib-ghc-6.6/default.nix
+++ /dev/null
@@ -1,11 +0,0 @@
-{stdenv, fetchurl, autoconf, ghc}:
-
-stdenv.mkDerivation
-{
-  name = "uulib-0.9.2-ghc-6.6";
-  src = fetchurl { url = http://www.cs.uu.nl/~ariem/uulib-2006-10-30-src.tar.gz;
-                   md5 = "d26059447d45fa91f54eca38680be7b7";
-                 };
-  builder = ./builder.sh;
-  buildInputs = [ autoconf ghc ];
-}
diff --git a/pkgs/development/libraries/haskell/uulib/builder.sh b/pkgs/development/libraries/haskell/uulib/builder.sh
deleted file mode 100644
index bdb0e81430e..00000000000
--- a/pkgs/development/libraries/haskell/uulib/builder.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-source $stdenv/setup
-
-
-export HOME=$(pwd)/fake-home
-
-
-#add ghc to search path
-test -n "$ghc" && PATH=$PATH:$ghc/bin
-
-#unpack
-tar xzf "$src" &&
-cd uulib-* &&
-
-#configure
-ghc --make Setup.hs -o setup -package Cabal &&
-./setup configure --prefix=$out &&
-
-#make
-./setup build &&
-
-#install
-./setup copy &&
-
-# Create package database. If we can find the ghc version we might install the
-# package, like ghc does, in $out/lib/ghc-version/package.conf.
-
-support=$out/nix-support &&
-packages_db=$out/nix-support/package.conf &&
-
-mkdir $support &&
-cp $ghc/lib/ghc-*/package.conf $packages_db &&
-chmod +w $packages_db &&
-#echo '[]' > $packages_db &&
-
-# We save a modified version of a register script. This gives a dependency on
-# ghc, but this should not be a problem as long as $out is a static library.
-
-./setup register --gen-script &&
-sed '/ghc-pkg/ s|update -|-f "$1" update -|' register.sh > register-pkg.sh &&
-sed '/ghc-pkg/ s|--auto-ghci-libs||' register-pkg.sh > $support/register.sh &&
-
-# The package and its direct cabal dependencies are registered. This may result
-# in duplicate registrations attempts but hopefully that will not result in
-# errors.
-
-# uulib has no dependencies on other ghc libraries
-for dep in ; do
-	sh $dep/nix-support/register.sh $packages_db || exit 1
-done &&
-sh register-pkg.sh $packages_db &&
-rm -f $package_db.old
diff --git a/pkgs/development/libraries/haskell/uulib/default.nix b/pkgs/development/libraries/haskell/uulib/default.nix
index c8bcf25dcc4..0e5e517d7c5 100644
--- a/pkgs/development/libraries/haskell/uulib/default.nix
+++ b/pkgs/development/libraries/haskell/uulib/default.nix
@@ -1,12 +1,10 @@
-{stdenv, fetchurl, ghc}:
+{cabal}:
 
-stdenv.mkDerivation {
-  name = "uulib-0.9.2";
-  src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/uulib-0.9.2-src.tar.gz;
-    md5 = "0cc9acc6a268e2bc5c8a954e67406e2d";
+cabal.mkDerivation (self : {
+  pname = "uulib";
+  version = "0.9.5";
+  sha256 = "38415725133af464de582dadc7d7e60b1aeb96344b18b239d176bf2181f98563";
+  meta = {
+    description = "Fast Parser Combinators and Pretty Printing Combinators";
   };
-  builder = ./builder.sh;
-  #buildInputs = [ ghc ];
-  inherit ghc;
-}
+})
diff --git a/pkgs/development/libraries/haskell/vty/default.nix b/pkgs/development/libraries/haskell/vty/default.nix
new file mode 100644
index 00000000000..930e19ae89c
--- /dev/null
+++ b/pkgs/development/libraries/haskell/vty/default.nix
@@ -0,0 +1,13 @@
+{cabal}:
+
+cabal.mkDerivation (self : {
+  pname = "vty";
+  version = "3.0.0";
+  sha256 = "44ae53d06b8b45c14cd3861e860a38730ed9995ed56b1b3d9aba6641771f1947";
+  meta = {
+    description = "vty is a *very* simplistic library in the niche of ncurses";
+  };
+  preConfigure = ''
+    sed -i 's|^Build-Depends:.*$|&, bytestring, containers|' ${self.pname}.cabal
+  '';
+})
diff --git a/pkgs/development/libraries/haskell/zlib/default.nix b/pkgs/development/libraries/haskell/zlib/default.nix
new file mode 100644
index 00000000000..268a43b5ea3
--- /dev/null
+++ b/pkgs/development/libraries/haskell/zlib/default.nix
@@ -0,0 +1,11 @@
+{cabal, zlib}:
+
+cabal.mkDerivation (self : {
+  pname = "zlib";
+  version = "0.4.0.2";
+  sha256 = "e6e9e51ca5b7f1685eb031f826f7865acc10cc2c8d0dfad975e0e81fd17f17ed";
+  propagatedBuildInputs = [zlib];
+  meta = {
+    description = "Compression and decompression in the gzip and zlib formats";
+  };
+})
diff --git a/pkgs/development/libraries/ilbc/default.nix b/pkgs/development/libraries/ilbc/default.nix
new file mode 100644
index 00000000000..360644cf911
--- /dev/null
+++ b/pkgs/development/libraries/ilbc/default.nix
@@ -0,0 +1,17 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "ilbc-rfc3951";
+
+# I'm too lazy to extract .c source from rfc3951. So, I'm using autotools stuff
+# from linphone project
+  src = stdenv.mkDerivation {
+    name = "ilbc-rfc3951.tar.gz";
+    src = msilbc.src;
+	outputHashAlgo = "sha256";
+    outputHash = "0f6scsp72bz2ifscd8c0x57ipcxi2i4a9b4nwlnwx7a7a0hrazhj";
+    phases = "unpackPhase installPhase";
+    installPhase = "cp ilbc-rfc3951.tar.gz \${out}";
+  };
+
+  configureFlags = "--enable-shared --disable-static";
+}
diff --git a/pkgs/development/libraries/ilmbase/default.nix b/pkgs/development/libraries/ilmbase/default.nix
index 49fae13aec8..0ab548bef86 100644
--- a/pkgs/development/libraries/ilmbase/default.nix
+++ b/pkgs/development/libraries/ilmbase/default.nix
@@ -1,9 +1,9 @@
 args: with args;
 stdenv.mkDerivation {
-	name = "ilmbase-1.0.0";
+	name = "ilmbase-1.0.1";
 	src = fetchurl {
-		url = http://FIXME/ilmbase-1.0.0.tar.gz;
-		sha256 = "1dpgi3hbff9nflg95r2smb6ssg5bh5g8mj9dxh896w29nh08ipnz";
+		url = http://download.savannah.nongnu.org/releases/openexr/ilmbase-1.0.1.tar.gz;
+		sha256 = "0z9r3r0bxyhgwhkdwln0dg1lnxz691qnjygrqlg3jym34rxzq52g";
 	};
 	configureFlags = "--enable-shared --disable-static";
 }
diff --git a/pkgs/development/libraries/indilib/default.nix b/pkgs/development/libraries/indilib/default.nix
new file mode 100644
index 00000000000..651cb630944
--- /dev/null
+++ b/pkgs/development/libraries/indilib/default.nix
@@ -0,0 +1,16 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "indilib-0.5";
+
+  src = fetchurl {
+    url = mirror://sf/indi/indilib-0.5.tar.gz;
+    sha256 = "02km37m3d2l8c9wnab24zm2k6a3l8h2fali74jhm4z3khwr277ad";
+  };
+
+  propagatedBuildInputs = [cfitsio libusb zlib];
+  configureFlags = "--enable-shared --disable-static";
+
+  meta = {
+    homepage = http://indi.sf.net;
+  };
+}
diff --git a/pkgs/development/libraries/iniparser/default.nix b/pkgs/development/libraries/iniparser/default.nix
new file mode 100644
index 00000000000..46fe5b6ef03
--- /dev/null
+++ b/pkgs/development/libraries/iniparser/default.nix
@@ -0,0 +1,34 @@
+args: with args;
+stdenv.mkDerivation rec{
+	name = "iniparser-3.0b";
+
+	src = fetchurl {
+		url = "${meta.homepage}/iniparser3.0b.tar.gz";
+		sha256 = "09klyddnqlpbgkv4cmh6ww9q5pv6nf1vfmzw4z256p51rnnlqqwa";
+	};
+
+	patches = ./no-usr.patch;
+
+	buildFlags = "libiniparser.so";
+
+	installPhase = ''
+	ensureDir $out/lib
+	cp libiniparser.so.0 $out/lib
+	ln -s libiniparser.so.0 $out/lib/libiniparser.so
+
+	ensureDir $out/include
+	cp src/*.h $out/include
+
+	ensureDir $out/share/doc/${name}
+	for i in AUTHORS INSTALL LICENSE README; do
+		bzip2 -c -9 $i > $out/share/doc/${name}/$i.bz2;
+	done;
+	cp -r html $out/share/doc/${name}
+	'';
+
+	meta = {
+		homepage = http://ndevilla.free.fr/iniparser;
+		description = "Free standalone ini file parsing library";
+		license = "MIT";
+	};
+}
diff --git a/pkgs/development/libraries/iniparser/no-usr.patch b/pkgs/development/libraries/iniparser/no-usr.patch
new file mode 100644
index 00000000000..28be099b8ee
--- /dev/null
+++ b/pkgs/development/libraries/iniparser/no-usr.patch
@@ -0,0 +1,14 @@
+diff -urN iniparser3.0b.orig/Makefile iniparser3.0b/Makefile
+--- iniparser3.0b.orig/Makefile	2008-01-16 19:56:08.000000000 +0100
++++ iniparser3.0b/Makefile	2008-01-16 19:56:49.000000000 +0100
+@@ -11,8 +11,8 @@
+ ARFLAGS = rcv
+ 
+ SHLD = ${CC} ${CFLAGS}
+-LDSHFLAGS = -shared -Wl,-Bsymbolic  -Wl,-rpath -Wl,/usr/lib -Wl,-rpath,/usr/lib
+-LDFLAGS = -Wl,-rpath -Wl,/usr/lib -Wl,-rpath,/usr/lib
++LDSHFLAGS = -shared
++LDFLAGS =
+ 
+ # Set RANLIB to ranlib on systems that require it (Sun OS < 4, Mac OSX)
+ # RANLIB  = ranlib
diff --git a/pkgs/development/libraries/jasper/default.nix b/pkgs/development/libraries/jasper/default.nix
new file mode 100644
index 00000000000..192e22add6e
--- /dev/null
+++ b/pkgs/development/libraries/jasper/default.nix
@@ -0,0 +1,18 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "jasper-1.900.1";
+
+	src = fetchurl {
+		url = "http://www.ece.uvic.ca/~mdadams/jasper/software/${name}.zip";
+		sha256 = "154l7zk7yh3v8l2l6zm5s2alvd2fzkp6c9i18iajfbna5af5m43b";
+	};
+
+	buildInputs = [ unzip libjpeg xproto libX11 libICE freeglut mesa libXmu
+		libXi libXext libXt ];
+	configureFlags = "--enable-shared --disable-static --with-x";
+
+	meta = {
+		homepage = http://www.ece.uvic.ca/~mdadams/jasper/;
+		description = "JasPer JPEG2000 Library";
+	};
+}
diff --git a/pkgs/development/libraries/kerberos/heimdal.nix b/pkgs/development/libraries/kerberos/heimdal.nix
new file mode 100644
index 00000000000..12cc50e3505
--- /dev/null
+++ b/pkgs/development/libraries/kerberos/heimdal.nix
@@ -0,0 +1,12 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "heimdal-1.0.2";
+
+	src = fetchurl {
+		url = "http://ftp.pdc.kth.se/pub/heimdal/src/${name}.tar.gz";
+		sha256 = "1h4x41lpv2abpv5l3yjd58pfzs0kkp5sbnih9iykhwd6sii1iig5";
+	};
+
+	configureFlags = "--enable-shared --disable-static --with-openldap=${openldap}";
+	propagatedBuildInputs = [ readline db4 openssl openldap cyrus_sasl ];
+}
diff --git a/pkgs/development/libraries/libaal/default.nix b/pkgs/development/libraries/libaal/default.nix
new file mode 100644
index 00000000000..596b8e2e84c
--- /dev/null
+++ b/pkgs/development/libraries/libaal/default.nix
@@ -0,0 +1,19 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "libaal-1.0.5";
+
+  src = fetchurl {
+    url = http://chichkin_i.zelnet.ru/namesys/libaal-1.0.5.tar.gz;
+    sha256 = "109f464hxwms90mpczc7h7lmrdlcmlglabkzh86h25xrlxxdn6pz";
+  };
+
+  preInstall = ''
+    substituteInPlace Makefile --replace ./run-ldconfig true
+  '';
+
+  meta = {
+    homepage = http://www.namesys.com/;
+    description = "Support library for Reiser4";
+  };
+}
diff --git a/pkgs/development/libraries/libao/default.nix b/pkgs/development/libraries/libao/default.nix
new file mode 100644
index 00000000000..cb42848585b
--- /dev/null
+++ b/pkgs/development/libraries/libao/default.nix
@@ -0,0 +1,19 @@
+{stdenv, fetchurl, pkgconfig}:
+
+stdenv.mkDerivation {
+  name = "libao-0.8.8";
+  src = fetchurl {
+    url = http://downloads.xiph.org/releases/ao/libao-0.8.8.tar.gz;
+    sha256 = "e52e05af6b10f42d2ee9845df1a581bf2b352060eabf7946aee0a600c3878954";
+  };
+
+  buildInputs = [pkgconfig];
+
+  meta = {
+    description = ''Libao is Xiph.org's cross-platform audio
+                    library that allows programs to output audio
+		    using a simple API on a wide variety of platforms.'';
+    homepage = http://xiph.org/ao/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/development/libraries/libarchive/2.4.11.nix b/pkgs/development/libraries/libarchive/2.4.11.nix
new file mode 100644
index 00000000000..e75d59ec18a
--- /dev/null
+++ b/pkgs/development/libraries/libarchive/2.4.11.nix
@@ -0,0 +1,2 @@
+args:
+import ./common.nix "1iq5hs4hbqyl6sqiqlaj3j89vpfqx6zv974c965nxjvmwy816dbz" args
diff --git a/pkgs/development/libraries/libarchive/2.4.12.nix b/pkgs/development/libraries/libarchive/2.4.12.nix
new file mode 100644
index 00000000000..9765ec61cd7
--- /dev/null
+++ b/pkgs/development/libraries/libarchive/2.4.12.nix
@@ -0,0 +1,2 @@
+args:
+import ./common.nix "133kxx1wfangrhy6rcpqlqib7i45qxj8pcp3i9n574cwfx41swy4" args
diff --git a/pkgs/development/libraries/libarchive/common.nix b/pkgs/development/libraries/libarchive/common.nix
new file mode 100644
index 00000000000..9f031e4f2c2
--- /dev/null
+++ b/pkgs/development/libraries/libarchive/common.nix
@@ -0,0 +1,18 @@
+sha256: args: with args;
+stdenv.mkDerivation rec {
+	name = "libarchive-" + version;
+
+	src = fetchurl {
+		url = "${meta.homepage}/src/${name}.tar.gz";
+    inherit sha256;
+	};
+
+	propagatedBuildInputs = [zlib bzip2 e2fsprogs];
+  buildInputs = [sharutils];
+  configureFlags = "--enable-shared --disable-static";
+
+	meta = {
+		description = "A library for reading and writing streaming archives";
+    homepage = http://people.freebsd.org/~kientzle/libarchive;
+	};
+}
diff --git a/pkgs/development/libraries/libassuan/default.nix b/pkgs/development/libraries/libassuan/default.nix
new file mode 100644
index 00000000000..ef0df518452
--- /dev/null
+++ b/pkgs/development/libraries/libassuan/default.nix
@@ -0,0 +1,16 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "libassuan-1.0.4";
+
+	src = fetchurl {
+		url = "ftp://ftp.gnupg.org/gcrypt/libassuan/${name}.tar.bz2";
+		sha256 = "1milkb5128nkgvfvfc9yi3qq8d1bvci7b3qmzfibmyh7qga6pwpw";
+	};
+
+	propagatedBuildInputs = [pth];
+
+	meta = {
+		description = "Libassuan  is the IPC library used by some GnuPG related software";
+		homepage = http://www.gnupg.org;
+	};
+}
diff --git a/pkgs/development/libraries/libavc1394/default.nix b/pkgs/development/libraries/libavc1394/default.nix
new file mode 100644
index 00000000000..672ca202354
--- /dev/null
+++ b/pkgs/development/libraries/libavc1394/default.nix
@@ -0,0 +1,18 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "libavc1394-0.5.3";
+
+  src = fetchurl {
+    url = mirror://sourceforge/libavc1394/libavc1394-0.5.3.tar.gz;
+    sha256 = "19i40i3722ilhziknfds3a6w5xzv66fvc68gvbir1p2fvwi6ij93";
+  };
+
+  buildInputs = [pkgconfig];
+  propagatedBuildInputs = [libraw1394];
+
+  meta = { 
+      description = "programming interface for the 1394 Trade Association AV/C (Audio/Video Control) Digital Interface Command Set";
+      homepage = http://sourceforge.net/projects/libavc1394/;
+      license = [ "GPL" "LGPL" ];
+  };
+}
diff --git a/pkgs/development/libraries/libcaca/default.nix b/pkgs/development/libraries/libcaca/default.nix
index 080c1efbc73..95e99710c6e 100644
--- a/pkgs/development/libraries/libcaca/default.nix
+++ b/pkgs/development/libraries/libcaca/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, ncurses}:
 
 stdenv.mkDerivation {
-  name = "libcaca-0.99-beta11";
+  name = "libcaca-0.99-beta13b";
   src = fetchurl {
-    url = http://libcaca.zoy.org/files/libcaca-0.99.beta11.tar.gz;
-    sha256 = "1kj0rkfbmq8kc3pi3p323ifx5yp9pcmbnxln7phxj5k4v7ngyld7";
+    url = http://libcaca.zoy.org/files/libcaca-0.99.beta13b.tar.gz;
+    sha256 = "0xy8pcnljnj5la97bzbwwyzyqa7dr3v9cyw8gdjzdfgqywvac1vg";
   };
   configureFlags = "--disable-x11 --disable-imlib2 --disable-doc";
   propagatedBuildInputs = [ncurses];
diff --git a/pkgs/development/libraries/libdbi-drivers/0.8.2-1.nix b/pkgs/development/libraries/libdbi-drivers/0.8.2-1.nix
new file mode 100644
index 00000000000..8c3975c8da2
--- /dev/null
+++ b/pkgs/development/libraries/libdbi-drivers/0.8.2-1.nix
@@ -0,0 +1,40 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+			fetchurl {
+				url = mirror://sourceforge/libdbi-drivers/libdbi-drivers-0.8.2-1.tar.gz;
+				sha256 = "1bflwl1k3rf1h8clx3zv5pxnm5hbhq6izikv0phkss3qxkjm61ap";
+			};
+
+		buildInputs = [libdbi]  
+		++(if args ? mysql then [args.mysql] else [])
+		++(if args ? sqlite then [args.sqlite] else [])
+		;
+		configureFlags = [
+			" --enable-libdbi "
+			" --with-dbi-incdir=${libdbi}/include " 
+			" --with-dbi-libdir=${libdbi}/lib " 
+		]
+		++ (if args ? mysql then [
+			" --with-mysql "
+			" --with-mysql-incdir=${mysql}/include/mysql " 
+			" --with-mysql-libdir=${mysql}/lib/mysql " 
+		] else [])
+		++ (if args ? sqlite then [
+			" --with-sqlite "
+			" --with-sqlite-incdir=${sqlite}/include/sqlite " 
+			" --with-sqlite-libdir=${sqlite}/lib/sqlite " 
+		] else [])
+		;
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "libdbi"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	DB independent interface to DB; DB drivers (mysql only for now).
+";
+	};
+}
diff --git a/pkgs/development/libraries/libdbi/0.8.2.nix b/pkgs/development/libraries/libdbi/0.8.2.nix
new file mode 100644
index 00000000000..e80c0196650
--- /dev/null
+++ b/pkgs/development/libraries/libdbi/0.8.2.nix
@@ -0,0 +1,22 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+			fetchurl {
+				url = mirror://sourceforge/libdbi/libdbi-0.8.2.tar.gz;
+				sha256 = "01zlfv9hd4iv9v1xlh64ajdgx95jb0sjpazavapqc0zwiagwcg4d";
+			};
+
+		buildInputs = [];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "libdbi"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	DB independent interface to DB.	
+";
+	};
+}
diff --git a/pkgs/development/libraries/libdv/default.nix b/pkgs/development/libraries/libdv/default.nix
new file mode 100644
index 00000000000..4b0e05acf98
--- /dev/null
+++ b/pkgs/development/libraries/libdv/default.nix
@@ -0,0 +1,30 @@
+args:
+let edf = args.lib.enableDisableFeature; in
+( args.mkDerivationByConfiguration {
+    flagConfig = { }
+      # TODO! implement flags
+      # I want to get kino and cinelerra working. That's why I don't spend more time on this now
+      // edf "libtool_lock" "libtool_lock" { } #avoid locking (might break parallel builds)
+      // edf "asm" "asm" { } #disable use of architecture specific assembly code
+      // edf "sdl" "sdl" { } #enable use of SDL for display
+      // edf "gtk" "gtk" { } #disable use of gtk for display
+      // edf "xv" "xv" { } #disable use of XVideo extension for display
+      // edf "gprof" "gprof" { } #enable compiler options for gprof profiling
+    ;
+
+    extraAttrs = co : {
+      name = "libdv-1.0.0";
+
+      src = args.fetchurl {
+        url = mirror://sourceforge/libdv/libdv-1.0.0.tar.gz;
+        sha256 = "1fl96f2xh2slkv1i1ix7kqk576a0ak1d33cylm0mbhm96d0761d3";
+      };
+
+    meta = { 
+      description = "software decoder for DV format video, as defined by the IEC 61834 and SMPTE 314M standards";
+      homepage = http://sourceforge.net/projects/libdv/;
+      # you can choose one of the following licenses: 
+      license = [];
+    };
+  };
+} ) args
diff --git a/pkgs/development/libraries/libexif/default.nix b/pkgs/development/libraries/libexif/default.nix
index 0a63ffda2af..76434d2c30b 100644
--- a/pkgs/development/libraries/libexif/default.nix
+++ b/pkgs/development/libraries/libexif/default.nix
@@ -1,12 +1,12 @@
-{stdenv, fetchurl}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "libexif-0.6.14";
+stdenv.mkDerivation rec {
+  name = "libexif-0.6.16";
 
   src = fetchurl {
-    url = mirror://sourceforge/libexif/libexif-0.6.14.tar.bz2;
-    sha256 = "0pza5ysvbvvliz7al2i8l3yai64w09xwc6ivy2v5cl7k43almz84";
+    url = "mirror://sourceforge/libexif/${name}.tar.bz2";
+    sha256 = "0hxc3aik3sn8xq4mbmxxb8ycx2lwffmhi5xvz0zjffhfwkaqas6v";
   };
 
-  patches = [./no-po.patch];
+  buildInputs = [gettext];
 }
diff --git a/pkgs/development/libraries/libextractor/0.5.18.nix b/pkgs/development/libraries/libextractor/0.5.18.nix
new file mode 100644
index 00000000000..6fc5e852448
--- /dev/null
+++ b/pkgs/development/libraries/libextractor/0.5.18.nix
@@ -0,0 +1,22 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://gnunet.org/libextractor/download/libextractor-0.5.18.tar.gz;
+			sha256 = "09y869zmnr6n2953ra4y7z9m9nj23prlqa4nr4rwcb50dzdmil1k";
+		};
+
+		buildInputs = [ zlib];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "libextractor"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	Libextractor - extracts metadata from files.
+";
+	};
+}
diff --git a/pkgs/development/libraries/libgcrypt/default.nix b/pkgs/development/libraries/libgcrypt/default.nix
index bb71e8f8499..8ea05dc73a3 100644
--- a/pkgs/development/libraries/libgcrypt/default.nix
+++ b/pkgs/development/libraries/libgcrypt/default.nix
@@ -1,10 +1,13 @@
-{stdenv, fetchurl, libgpgerror}:
+args: with args;
 
 stdenv.mkDerivation {
-  name = "libgcrypt-1.2.4";
+  name = "libgcrypt-1.3.1";
   src = fetchurl {
-    url = ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.2.4.tar.gz;
-    sha256 = "1v6rbx2jpwvh9jwf8n91da2p66v2gzmym6s3h1fidfdy7qqkyg6g";
+    urls = [
+      ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.3.1.tar.bz2
+      ftp://ftp.gnupg.org/gcrypt/alpha/libgcrypt/libgcrypt-1.3.1.tar.bz2
+    ];
+    sha256 = "0ip0bjhnn12lvb050j91x64wfhmpk7xlc3p93mxi9g2qczg413nz";
   };
 
   buildInputs = [libgpgerror];
diff --git a/pkgs/development/libraries/libgphoto2/default.nix b/pkgs/development/libraries/libgphoto2/default.nix
index 78372330a94..6e332117a2d 100644
--- a/pkgs/development/libraries/libgphoto2/default.nix
+++ b/pkgs/development/libraries/libgphoto2/default.nix
@@ -1,14 +1,15 @@
-{stdenv, fetchurl, pkgconfig, libusb}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "libgphoto2-2.2.1";
+stdenv.mkDerivation rec {
+  name = "libgphoto2-2.4.0";
 
   src = fetchurl {
-    url = mirror://sourceforge/gphoto/libgphoto2-2.2.1.tar.bz2;
-    md5 = "69827311733e39fafa9f77bb05e55b77";
+    url = "mirror://sourceforge/gphoto/${name}.tar.bz2";
+    sha256 = "0yfvpgfly774jnjrfqjf89h99az3sgvzkfpb9diygpk8hmx6phhd";
   };
-  buildInputs = [pkgconfig libusb];
+  buildInputs = [pkgconfig libusb libtool libexif libjpeg gettext];
 
-  ## remove this patch when 2.2.2 is released
-  patches = [./libgphoto2-2.2.1.patch];
+  meta = {
+	  license = "LGPL-2";
+  };
 }
diff --git a/pkgs/development/libraries/libgsf/default.nix b/pkgs/development/libraries/libgsf/default.nix
index 41f946e6606..6131314a22c 100644
--- a/pkgs/development/libraries/libgsf/default.nix
+++ b/pkgs/development/libraries/libgsf/default.nix
@@ -1,10 +1,17 @@
-{stdenv, fetchurl, perl, perlXMLParser, pkgconfig, libxml2, glib, gettext}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "libgsf-1.14.1";
+stdenv.mkDerivation rec {
+  name = "libgsf-1.14.7";
   src = fetchurl {
-    url = http://ftp.gnome.org/pub/gnome/sources/libgsf/1.14/libgsf-1.14.1.tar.bz2;
-    md5 = "00de00b99382d0b7e034e0fffd8951d4";
+    url = "http://ftp.gnome.org/pub/gnome/sources/libgsf/1.14/${name}.tar.bz2";
+	sha256 = "0vd8arjaavb3qywd9cm2gdn6ngrlyd99nlsj72par8fm60k48bhq";
+  };
+  buildInputs = [perl perlXMLParser pkgconfig libxml2 glib gettext bzip2
+  gnomevfs libbonobo python];
+
+  meta = {
+	  homepage = http://www.gnome.org/projects/libgsf;
+	  license = "LGPL";
+	  description = "GNOME Structured File Library";
   };
-  buildInputs = [perl perlXMLParser pkgconfig libxml2 glib gettext];
 }
diff --git a/pkgs/development/libraries/libid3tag/default.nix b/pkgs/development/libraries/libid3tag/default.nix
new file mode 100644
index 00000000000..c29d3d29558
--- /dev/null
+++ b/pkgs/development/libraries/libid3tag/default.nix
@@ -0,0 +1,17 @@
+{stdenv, fetchurl, zlib}:
+
+stdenv.mkDerivation {
+  name = "libid3tag-0.15.1b";
+  src = fetchurl {
+    url = mirror://sourceforge/mad/libid3tag-0.15.1b.tar.gz;
+    sha256 = "63da4f6e7997278f8a3fef4c6a372d342f705051d1eeb6a46a86b03610e26151";
+  };
+
+  buildInputs = [zlib];
+
+  meta = {
+    description = "An ID3 tag manipulation library.";
+    homepage = http://mad.sourceforge.net/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/development/libraries/libiec61883/default.nix b/pkgs/development/libraries/libiec61883/default.nix
new file mode 100644
index 00000000000..6fe199f5b91
--- /dev/null
+++ b/pkgs/development/libraries/libiec61883/default.nix
@@ -0,0 +1,18 @@
+args: with args;
+stdenv.mkDerivation rec {
+  name = "libiec61883-1.1.0";
+
+  src = fetchurl {
+    url = "${meta.homepage}/dl/${name}.tar.gz";
+    sha256 = "09f0ca7bp6lqlz6601gnyl04mfabv0azg49n1cmjyqpzh35cgxkq";
+  };
+
+  buildInputs = [pkgconfig];
+  propagatedBuildInputs = [libraw1394];
+
+  meta = { 
+      description = "TODO";
+      homepage = http://www.linux1394.org;
+      license = "LGPL";
+    };
+}
diff --git a/pkgs/development/libraries/libjingle/0.3.11.nix b/pkgs/development/libraries/libjingle/0.3.11.nix
new file mode 100644
index 00000000000..b9d0b82df5e
--- /dev/null
+++ b/pkgs/development/libraries/libjingle/0.3.11.nix
@@ -0,0 +1,10 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "libjingle-" + version;
+	src = fetchurl {
+		url = "mirror://sf/tapioca-voip/${name}.tar.gz";
+		sha256 = "1x5l2jwxpkyxvnq0cagq40p6x61v23vxngnnsxr15lyh1zwzk1yj";
+	};
+
+  propagatedBuildInputs = [ mediastreamer ];
+}
diff --git a/pkgs/development/libraries/libjingle/0.4.0.nix b/pkgs/development/libraries/libjingle/0.4.0.nix
new file mode 100644
index 00000000000..93bacd00929
--- /dev/null
+++ b/pkgs/development/libraries/libjingle/0.4.0.nix
@@ -0,0 +1,10 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "libjingle-" + version;
+
+  src = fetchurl {
+    url = "mirror://sf/libjingle/${name}.tar.gz";
+    sha256 = "0izg1i4nmhysvkqmsl2xqp0x6lwz2jjyavvhv196hsdsr2w0iwvi";
+  };
+}
diff --git a/pkgs/development/libraries/libksba/default.nix b/pkgs/development/libraries/libksba/default.nix
new file mode 100644
index 00000000000..573064f2889
--- /dev/null
+++ b/pkgs/development/libraries/libksba/default.nix
@@ -0,0 +1,19 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "libksba-1.0.2";
+
+	src = fetchurl {
+		url = "ftp://ftp.gnupg.org/gcrypt/libksba/${name}.tar.bz2";
+		sha256 = "1jkjh1daaykkrfq0s4vv8ddf0w8agdvspg9qm0ghjidlrfnsfiwh";
+	};
+
+	propagatedBuildInputs = [libgpgerror];
+
+	configureFlags = "--enable-shared --disable-static";
+
+	meta = {
+		homepage = http://www.gnupg.org;
+		description = "Libksba  is a CMS and X.509 access library under
+		development";
+	};
+}
diff --git a/pkgs/development/libraries/libmad/default.nix b/pkgs/development/libraries/libmad/default.nix
index 6db5bf798d9..458945e102d 100644
--- a/pkgs/development/libraries/libmad/default.nix
+++ b/pkgs/development/libraries/libmad/default.nix
@@ -3,7 +3,14 @@
 stdenv.mkDerivation {
   name = "libmad-0.15.1b";
   src = fetchurl {
-    url = ftp://ftp.mars.org/pub/mpeg/libmad-0.15.1b.tar.gz;
-    md5 = "1be543bc30c56fb6bea1d7bf6a64e66c";
+    url = mirror://sourceforge/mad/libmad-0.15.1b.tar.gz;
+    sha256 = "bbfac3ed6bfbc2823d3775ebb931087371e142bb0e9bb1bee51a76a6e0078690";
+  };
+
+  buildInputs = [];
+
+  meta = {
+    description = "MAD, a high-quality, fixed-point, MPEG audio decoder
+                   supporting MPEG-1 and MPEG-2.";
   };
 }
diff --git a/pkgs/development/libraries/libnotify/default.nix b/pkgs/development/libraries/libnotify/default.nix
new file mode 100644
index 00000000000..8b58fe857e9
--- /dev/null
+++ b/pkgs/development/libraries/libnotify/default.nix
@@ -0,0 +1,17 @@
+args: with args;
+ 
+stdenv.mkDerivation {
+  name = "libnotify-0.4.4";
+  #builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://www.galago-project.org/files/releases/source/libnotify/libnotify-0.4.4.tar.gz;
+    sha256 = "2389a9b8220f776033f728a8d46352cfee5c8705066e34887bfb188f9f0d3856";
+  };
+
+  buildInputs = [
+    pkgconfig dbus.libs dbus_glib gtk glib
+  ];
+
+  configureFlags="";
+}
diff --git a/pkgs/development/libraries/libnova/default.nix b/pkgs/development/libraries/libnova/default.nix
new file mode 100644
index 00000000000..805a1f44452
--- /dev/null
+++ b/pkgs/development/libraries/libnova/default.nix
@@ -0,0 +1,15 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "libnova-0.12.1";
+	
+	src = fetchurl {
+		url = "mirror://sf/libnova/${name}.tar.gz";
+		sha256 = "0bs6c45q4qkrns36qndl8vns5gvhgpd90hi68bhah4r4hrg48lw0";
+	};
+	configureFlags = "--enable-shared --disable-static";
+
+	meta = {
+		description = "Celestial Mechanics, Astrometry and Astrodynamics Library";
+		homepage = http://libnova.sf.net;
+	};
+}
diff --git a/pkgs/development/libraries/liboop/default.nix b/pkgs/development/libraries/liboop/default.nix
new file mode 100644
index 00000000000..2009e92a54d
--- /dev/null
+++ b/pkgs/development/libraries/liboop/default.nix
@@ -0,0 +1,17 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "liboop";
+  src = fetchurl {
+    url = http://download.ofb.net/liboop/liboop.tar.gz;
+    sha256 = "34d83c6e0f09ee15cb2bc3131e219747c3b612bb57cf7d25318ab90da9a2d97c";
+  };
+
+  buildInputs = [];
+
+  meta = {
+    description = "`liboop', an event loop library.";
+    homepage = http://liboop.ofb.net/;
+    license = "LGPL";
+  };
+}
diff --git a/pkgs/development/libraries/libpcap/default.nix b/pkgs/development/libraries/libpcap/default.nix
index 25d1105eac6..95fbbbbfbab 100644
--- a/pkgs/development/libraries/libpcap/default.nix
+++ b/pkgs/development/libraries/libpcap/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, flex, bison}:
 
 stdenv.mkDerivation {
-  name = "libpcap-0.9.5";
+  name = "libpcap-0.9.8";
   src = fetchurl {
-      url = http://www.tcpdump.org/release/libpcap-0.9.5.tar.gz;
-      md5 = "b0626ad59004fe5767ddd2ce743a2271";
+      url = http://www.tcpdump.org/release/libpcap-0.9.8.tar.gz;
+      sha256 = "1yb2hg8jd1bzq3lbrff1sps4757krvj2c9pm2ixn44a4vsc865f4";
   };
   buildInputs = [flex bison];
   configureFlags = "
diff --git a/pkgs/development/libraries/libpng/default.nix b/pkgs/development/libraries/libpng/default.nix
index b600cf0840b..f6252c794ce 100644
--- a/pkgs/development/libraries/libpng/default.nix
+++ b/pkgs/development/libraries/libpng/default.nix
@@ -3,10 +3,10 @@
 assert zlib != null;
 
 stdenv.mkDerivation {
-  name = "libpng-1.2.18";
+  name = "libpng-1.2.24";
   src = fetchurl {
-    url = mirror://sourceforge/libpng/libpng-1.2.18.tar.bz2;
-    sha256 = "0qhcy8r0r8280wahs91xi4p79gm2cb021x9bcww1r5bywvwn5kkg";
+    url = mirror://sourceforge/libpng/libpng-1.2.24.tar.bz2;
+    sha256 = "0kd0qkakc5zh2inrzw5r0h02761v1s9q223lv7za7iaxyl4byash";
   };
   propagatedBuildInputs = [zlib];
   inherit zlib;
diff --git a/pkgs/development/libraries/libraw1394/default.nix b/pkgs/development/libraries/libraw1394/default.nix
new file mode 100644
index 00000000000..2ca8c543fa9
--- /dev/null
+++ b/pkgs/development/libraries/libraw1394/default.nix
@@ -0,0 +1,15 @@
+args: with args;
+stdenv.mkDerivation rec {
+  name = "libraw1394-1.3.0";
+
+  src = fetchurl {
+    url = "${meta.homepage}/dl/${name}.tar.gz";
+    sha256 = "035mrca9fhg4kq8r1s5yjgzg3vrn1nc3ndy13yg3chhqgx4dzzr0";
+  };
+
+  meta = { 
+      description = "library providing direct access to the IEEE 1394 bus through the Linux 1394 subsystem's raw1394 user space interface";
+      homepage = "http://www.linux1394.org";
+      license = ["GPL" "LGPL"];
+  };
+}
diff --git a/pkgs/development/libraries/libsamplerate/default.nix b/pkgs/development/libraries/libsamplerate/default.nix
index 895772d7fc0..2ea959528a8 100644
--- a/pkgs/development/libraries/libsamplerate/default.nix
+++ b/pkgs/development/libraries/libsamplerate/default.nix
@@ -1,5 +1,5 @@
 args:
-( args.mkDerivationByConfigruation {
+( args.mkDerivationByConfiguration {
     flagConfig = {
       mandatory = { buildInputs = ["pkgconfig"];};
     # are these options of interest? We'll see
diff --git a/pkgs/development/libraries/libsexy/default.nix b/pkgs/development/libraries/libsexy/default.nix
new file mode 100644
index 00000000000..81a38d39973
--- /dev/null
+++ b/pkgs/development/libraries/libsexy/default.nix
@@ -0,0 +1,17 @@
+{ stdenv, fetchurl, pkgconfig, libxml2, glib, gtk, pango
+}:
+ 
+stdenv.mkDerivation {
+  name = "libsexy-0.1.11";
+  #builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://releases.chipx86.com/libsexy/libsexy/libsexy-0.1.11.tar.gz;
+    sha256 = "8c4101a8cda5fccbba85ba1a15f46f2cf75deaa8b3c525ce5b135b9e1a8fe49e";
+  };
+
+  buildInputs = [ pkgconfig libxml2 glib gtk pango
+  ];
+
+  #configureFlags="";  
+}
diff --git a/pkgs/development/libraries/libsigsegv/2.5.nix b/pkgs/development/libraries/libsigsegv/2.5.nix
new file mode 100644
index 00000000000..11f69753dc8
--- /dev/null
+++ b/pkgs/development/libraries/libsigsegv/2.5.nix
@@ -0,0 +1,14 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "libsigsegv-" + version;
+  src = fetchurl {
+    url = "mirror://gnu/libsigsegv/${name}.tar.gz";
+    sha256 = "0fvcsq9msi63vrbpvks6mqkrnls5cfy6bzww063sqhk2h49vsyyg";
+  };
+
+  meta = {
+    homepage = http://libsigsegv.sf.net;
+    description = "A library for handling page faults in user mode";
+  };
+}
diff --git a/pkgs/development/libraries/libsigsegv/default.nix b/pkgs/development/libraries/libsigsegv/default.nix
deleted file mode 100644
index 07d4bdaacc8..00000000000
--- a/pkgs/development/libraries/libsigsegv/default.nix
+++ /dev/null
@@ -1,9 +0,0 @@
-{stdenv, fetchurl}:
-
-stdenv.mkDerivation {
-  name = "libsigsegv-2.1";
-  src = fetchurl {
-    url = mirror://gnu/libsigsegv/libsigsegv-2.1.tar.gz;
-    md5 = "6d75ca3fede5fbfd72a78bc918d9e174";
-  };
-}
diff --git a/pkgs/development/libraries/libtheora/default.nix b/pkgs/development/libraries/libtheora/default.nix
index f0c637d0f23..2a6f2254c14 100644
--- a/pkgs/development/libraries/libtheora/default.nix
+++ b/pkgs/development/libraries/libtheora/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, libogg, libvorbis}:
 
 stdenv.mkDerivation {
-  name = "libtheora-1.0alpha7";
+  name = "libtheora-1.0beta2";
   src = fetchurl {
-    url = http://downloads.xiph.org/releases/theora/libtheora-1.0alpha7.tar.bz2;
-    md5 = "1bc851e39e4b16977131d5e5f769f48b";
+    url = http://downloads.xiph.org/releases/theora/libtheora-1.0beta2.tar.gz;
+    sha256 = "0iwwprpi4s9y37c5yvlb572wd5gb2s635pxrkz5589266g1j1dcg";
   };
   propagatedBuildInputs = [libogg libvorbis];
 }
diff --git a/pkgs/development/libraries/libunwind/default.nix b/pkgs/development/libraries/libunwind/default.nix
new file mode 100644
index 00000000000..52ed30c0ae9
--- /dev/null
+++ b/pkgs/development/libraries/libunwind/default.nix
@@ -0,0 +1,14 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "libunwind-0.98.6";
+	src = fetchurl {
+		url = "http://download.savannah.nongnu.org/releases/libunwind/${name}.tar.gz";
+		sha256 = "1qfxqkyx4r5dmwajyhvsyyl8zwxs6n2rcg7a61fgfdfp0gxvpzgx";
+	};
+	configureFlags = "--enable-shared --disable-static";
+	meta = {
+		homepage = http://www.nongnu.org/libunwind;
+		description = "The primary goal of this project is to define a portable
+		and efficient API to determine the call-chain of a program";
+	};
+}
diff --git a/pkgs/development/libraries/libvorbis/default.nix b/pkgs/development/libraries/libvorbis/default.nix
index cdcee814917..1b3a7c81146 100644
--- a/pkgs/development/libraries/libvorbis/default.nix
+++ b/pkgs/development/libraries/libvorbis/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, libogg}:
 
 stdenv.mkDerivation {
-  name = "libvorbis-1.1.2";
+  name = "libvorbis-1.2.0";
   src = fetchurl {
-    url = http://downloads.xiph.org/releases/vorbis/libvorbis-1.1.2.tar.gz;
-    md5 = "37847626b8e1b53ae79a34714c7b3211";
+    url = http://downloads.xiph.org/releases/vorbis/libvorbis-1.2.0.tar.bz2;
+    sha256 = "0nq62b8y2rhhgxxyiw6b4wchic61q5v649fdl8dd7090nxxcbx4y";
   };
   buildInputs = [libogg];
 }
diff --git a/pkgs/development/libraries/libwmf/default.nix b/pkgs/development/libraries/libwmf/default.nix
index ea2eecd90d2..6f580613b16 100644
--- a/pkgs/development/libraries/libwmf/default.nix
+++ b/pkgs/development/libraries/libwmf/default.nix
@@ -1,15 +1,14 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "libwmf-0.2.8.4";
 
-  src = args.
-	fetchurl {
+  src = fetchurl {
 		url = mirror://sourceforge/wvware/libwmf-0.2.8.4.tar.gz;
 		sha256 = "1y3wba4q8pl7kr51212jwrsz1x6nslsx1gsjml1x0i8549lmqd2v";
 	};
 
-  buildInputs =(with args; [zlib imagemagick libpng
-	pkgconfig glib freetype libjpeg libxml2]);
+  buildInputs = [zlib imagemagick libpng
+	pkgconfig glib freetype libjpeg libxml2];
 
   meta = {
     description = "
diff --git a/pkgs/development/libraries/libwpd/default.nix b/pkgs/development/libraries/libwpd/default.nix
index 13723fdeb85..c2b89c1361f 100644
--- a/pkgs/development/libraries/libwpd/default.nix
+++ b/pkgs/development/libraries/libwpd/default.nix
@@ -1,10 +1,9 @@
-{stdenv, fetchurl, pkgconfig, glib, libgsf, libxml2}:
-
+args: with args;
 stdenv.mkDerivation {
-  name = "libwpd-0.8.5";
+  name = "libwpd-0.8.13";
   src = fetchurl {
-    url = mirror://sourceforge/libwpd/libwpd-0.8.5.tar.gz;
-    md5 = "6b679e205a2805c3d23f41c65b35e266";
+    url = mirror://sourceforge/libwpd/libwpd-0.8.13.tar.gz;
+    sha256 = "08mb8bp0d3387l1snii4c0ighfhkby7qx2b3wymqb4a0l76rlzfn";
   };
-  buildInputs = [pkgconfig glib libgsf libxml2];
+  buildInputs = [pkgconfig glib libgsf libxml2 bzip2];
 }
diff --git a/pkgs/development/libraries/libxklavier/3.4.nix b/pkgs/development/libraries/libxklavier/3.4.nix
new file mode 100644
index 00000000000..38fa91cfeb0
--- /dev/null
+++ b/pkgs/development/libraries/libxklavier/3.4.nix
@@ -0,0 +1,21 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "libxklavier-" + version;
+
+  src = fetchurl {
+    url = "mirror://sf/gswitchit/${name}.tar.gz";
+    sha256 = "07pq74ygmnr3vgfp86dbjnqsp3v67fww6d3a1vqbif9wzbk70195";
+  };
+
+# TODO: enable xmodmap support, needs xmodmap DB
+  propagatedBuildInputs = [libX11 xkeyboard_config libxml2 libICE glib libxkbfile];
+  buildInputs = [pkgconfig];
+  configureFlags = "--enable-shared --disable-static
+    --with-xkb-base=${xkeyboard_config}/etc/X11/xkb
+    --disable-xmodmap-support";
+
+  meta = {
+    homepage = http://freedesktop.org/wiki/Software/LibXklavier;
+  };
+}
diff --git a/pkgs/development/libraries/log4cxx/default.nix b/pkgs/development/libraries/log4cxx/default.nix
index 49544796612..63f32c05bc7 100644
--- a/pkgs/development/libraries/log4cxx/default.nix
+++ b/pkgs/development/libraries/log4cxx/default.nix
@@ -6,6 +6,6 @@ stdenv.mkDerivation {
 		url = http://archive.apache.org/dist/logging/log4cxx/log4cxx-0.9.7.tar.gz;
 		sha256 = "1ikyxd8jgf7b2cqjk5lidl7cffs114iiblaczaqbv5bm4vyb4hav";
 	};
-	buildInputs = [ autoconf automake libtool libxml2 cppunit ];
+	buildInputs = [ autoconf automake libtool libxml2 cppunit boost ];
 	patchPhase = "sh autogen.sh; sed -e 's/DOMConfigurator::subst/subst/' -i include/log4cxx/xml/domconfigurator.h";
 }
diff --git a/pkgs/development/libraries/loudmouth/default.nix b/pkgs/development/libraries/loudmouth/default.nix
new file mode 100644
index 00000000000..87d613efd30
--- /dev/null
+++ b/pkgs/development/libraries/loudmouth/default.nix
@@ -0,0 +1,14 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "loudmouth-1.3.3";
+
+	src = fetchurl {
+		url = "http://ftp.imendio.com/pub/imendio/loudmouth/src/${name}.tar.bz2";
+		sha256 = "0f3xpp3pf5bxcp0kcmqa0g28vfl5gg8mj0hxhs2cx75hwgikd26x";
+	};
+
+	propagatedBuildInputs = [gnutls libidn glib];
+	buildInputs = [pkgconfig];
+
+	configureFlags = "--enable-shared --disable-static";
+}
diff --git a/pkgs/development/libraries/mediastreamer/2.2.0-cvs20080207.nix b/pkgs/development/libraries/mediastreamer/2.2.0-cvs20080207.nix
new file mode 100644
index 00000000000..6391ce4dd6c
--- /dev/null
+++ b/pkgs/development/libraries/mediastreamer/2.2.0-cvs20080207.nix
@@ -0,0 +1,22 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "mediastreamer2-" + version;
+
+# This url is not related to mediastreamer. fetchcvs doesn't work on my laptop,
+# so I've created cvs snapshot and put it to my server.
+  src = fetchurl {
+    url = "http://www.loegria.net/misc/" + name + ".tar.bz2";
+    sha256 = "1nmvyqh4x3nsw4qbj754jwagj9ia183kvp8valdr7m44my0sw5p1";
+  };
+
+  buildInputs = [automake libtool autoconf pkgconfig];
+
+  propagatedBuildInputs = [alsaLib ffmpeg speex ortp];
+
+  preConfigure = "./autogen.sh";
+
+  patches = [ ./h264.patch ./plugins.patch ];
+
+  configureFlags = "--enable-external-ortp --enable-shared --disable-static";
+}
diff --git a/pkgs/development/libraries/mediastreamer/h264.patch b/pkgs/development/libraries/mediastreamer/h264.patch
new file mode 100644
index 00000000000..0c6dc9e9109
--- /dev/null
+++ b/pkgs/development/libraries/mediastreamer/h264.patch
@@ -0,0 +1,12 @@
+diff --git a/tests/mediastream.c b/tests/mediastream.c
+index 12e1605..cdc8cd1 100644
+--- a/tests/mediastream.c
++++ b/tests/mediastream.c
+@@ -144,7 +144,6 @@ int main(int argc, char * argv[])
+ 	rtp_profile_set_payload(&av_profile,97,&payload_type_theora);
+ 	rtp_profile_set_payload(&av_profile,99,&payload_type_mp4v);
+ 	rtp_profile_set_payload(&av_profile,100,&payload_type_x_snow);
+-	rtp_profile_set_payload(&av_profile,102,&payload_type_h264);
+ #endif
+ 	if (argc<4) {
+ 		printf(usage);
diff --git a/pkgs/development/libraries/mediastreamer/plugins.patch b/pkgs/development/libraries/mediastreamer/plugins.patch
new file mode 100644
index 00000000000..e82b85035f0
--- /dev/null
+++ b/pkgs/development/libraries/mediastreamer/plugins.patch
@@ -0,0 +1,49 @@
+diff --git a/src/mscommon.c b/src/mscommon.c
+index 1a12b2f..2399444 100644
+--- a/src/mscommon.c
++++ b/src/mscommon.c
+@@ -428,6 +428,7 @@ static MSSndCardDesc * ms_snd_card_descs[]={
+ void ms_init(){
+ 	int i;
+ 	MSSndCardManager *cm;
++	char *ms_plugin_path;
+ 
+ #ifdef __APPLE__
+ 	NSApplicationLoad();
+@@ -451,7 +452,35 @@ void ms_init(){
+ 	}
+ 
+ 	ms_message("Loading plugins");
+-	ms_load_plugins(PACKAGE_PLUGINS_DIR);
++	ms_plugin_path = getenv("MS_PLUGIN_PATH");
++	do
++		{
++			if (!ms_plugin_path)
++				{
++					ms_load_plugins(PACKAGE_PLUGINS_DIR);
++					break;
++				}
++			char *dup_plugins_path = strdup (ms_plugin_path);
++			char *cur_plugins_dir = dup_plugins_path;
++			if (!dup_plugins_path)
++				{
++					ms_message("Failed to duplicate plugins path, not loading plugins");
++					break;
++				}
++			while (1)
++				{
++					char *next_delimiter = strchr(cur_plugins_dir, ":");
++					if (next_delimiter)
++						next_delimiter[0] = '\0';
++					ms_load_plugins(cur_plugins_dir);
++					if (!next_delimiter)
++						break;
++					cur_plugins_dir = next_delimiter + 1;
++				}
++			free(dup_plugins_path);
++		}
++	while (0);
++
+ 	ms_message("ms_init() done");
+ }
+ 
diff --git a/pkgs/development/libraries/msilbc/2.0.0.nix b/pkgs/development/libraries/msilbc/2.0.0.nix
new file mode 100644
index 00000000000..8bc8f2a6c1d
--- /dev/null
+++ b/pkgs/development/libraries/msilbc/2.0.0.nix
@@ -0,0 +1,24 @@
+args: with args;
+stdenv.mkDerivation rec {
+  name = "msilbc-" + version;
+  src = fetchurl {
+    url = "http://download.savannah.gnu.org/releases/linphone/plugins/sources/${name}.tar.gz";
+    sha256 = "0ifydb7qmpync56l4hbrp36n5wrb7gadb76isp643s6wsg7l743j";
+  };
+
+  patchPhase = "sed -i /MS_FILTER_SET_FMTP/d ilbc.c";
+
+  propagatedBuildInputs = [ilbc mediastreamer];
+  buildInputs = [pkgconfig];
+
+  buildPhase = ''
+    cc -fPIC -c -pthread -o ilbc.o ilbc.c `pkg-config --cflags mediastreamer`
+    echo "next"
+    cc `pkg-config --libs mediastreamer` -shared -pthread -o libilbc.so
+  '';
+
+  installPhase = "
+    ensureDir \${out}/lib/mediastreamer/plugins
+    cp libilbc.so \${out}/lib/mediastreamer/plugins
+  ";
+}
diff --git a/pkgs/development/libraries/openalSoft/default.nix b/pkgs/development/libraries/openalSoft/default.nix
new file mode 100644
index 00000000000..f0bce75e07a
--- /dev/null
+++ b/pkgs/development/libraries/openalSoft/default.nix
@@ -0,0 +1,21 @@
+args: with args;
+stdenv.mkDerivation {
+#The current release is still in a testing phase, though it should be stable
+# (neither the ABI or API will break). Please try it out and let me know how it
+#  works. :-)
+
+  name = "openal-soft-1.1.93";
+
+  src = fetchurl {
+    url = http://kcat.strangesoft.net/openal-releases/openal-soft-1.1.93.tar.bz2;
+    sha256 = "162nyv4jy6qzi7s5q3wpdawfph6npyn1n4wjf21haxdxq0mmp6l7";
+  };
+
+  buildInputs = [cmake alsaLib];
+  
+  meta = {
+      description = "openal alternative";
+      homepage = http://kcat.strangesoft.net/openal.html;
+      license = "GPL2";
+  };
+}
diff --git a/pkgs/development/libraries/openexr/default.nix b/pkgs/development/libraries/openexr/default.nix
index e30f25d9778..4d4aefc9581 100644
--- a/pkgs/development/libraries/openexr/default.nix
+++ b/pkgs/development/libraries/openexr/default.nix
@@ -1,11 +1,15 @@
 args: with args;
 
 stdenv.mkDerivation {
-  name = "openexr-1.6.0";
+  inherit version;
+  name = "openexr-${version}";
   src = fetchurl {
-    url = http://FIXME/openexr-1.6.0.tar.gz;
-	sha256 = "0mzbwavkbj26g43ar5jhdrqlvw9nq1mxh9l2044sqlcyharcnfq4";
+    url = "http://download.savannah.nongnu.org/releases/openexr/openexr-${version}.tar.gz";
+    sha256 = if (version == "1.6.1") then "0l2rdbx9lg4qk2ms98hwbsnzpggdrx3pbjl6pcvrrpjqp5m905n6"
+             else if (version == "1.4.0") then "1y3dxakpg9651dgbj2xp6r4044b5gi74g23w3sr5cs6xi7cywv7m"
+               else abort "not supported version";
   };
+  buildInputs = [pkgconfig zlib] ++ (lib.optional (args ? ctl) (args.ctl));
   propagatedBuildInputs = [pkgconfig zlib ilmbase];
   configureFlags = "--enable-shared --disable-static --enable-imfexamples";
 }
diff --git a/pkgs/development/libraries/openexr_ctl/default.nix b/pkgs/development/libraries/openexr_ctl/default.nix
new file mode 100644
index 00000000000..288067a4bf2
--- /dev/null
+++ b/pkgs/development/libraries/openexr_ctl/default.nix
@@ -0,0 +1,24 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "openexr_ctl-1.0.1";
+
+  src = fetchurl {
+    url = http://kent.dl.sourceforge.net/sourceforge/ampasctl/openexr_ctl-1.0.1.tar.gz;
+    sha256 = "1jg9smpaplal8l14djp184wzk11nwd3dvm4lhkp69kjgw8jdd21d";
+  };
+
+  propagatedBuildInputs = [ilmbase];
+  buildInputs = [openexr ctl];
+  configureFlags="--with-ilmbase-prefix=${ilmbase}";
+  #configurePhase = "
+    #export CXXFLAGS=\"-I${ilmbase}/include -L${ilmbase}/lib\"
+    #echo $CXXFLAGS
+    #unset configurePhase; configurePhase
+  #";
+
+  meta = {
+      description = "Color Transformation Language";
+      homepage = http://ampasctl.sourceforge.net;
+      license = "SOME OPEN SOURCE LICENSE"; # TODO which exactly is this?
+  };
+}
diff --git a/pkgs/development/libraries/openssl/default.nix b/pkgs/development/libraries/openssl/default.nix
index e1dbc274aed..a4f09612f9b 100644
--- a/pkgs/development/libraries/openssl/default.nix
+++ b/pkgs/development/libraries/openssl/default.nix
@@ -1,4 +1,4 @@
-args: with args; stdenv.mkDerivation {
+{stdenv, fetchurl, perl}: stdenv.mkDerivation {
   name = "openssl-0.9.8g";
   builder = ./builder.sh;
   src = fetchurl {
@@ -6,5 +6,4 @@ args: with args; stdenv.mkDerivation {
     sha256 = "1w0wj3pgg9ga0hay3jdxs9sl17bfw307b6qvkxn735fy8ml8h9hf";
   };
   buildInputs = [perl];
-  propagatedBuildInputs = [gmp];
 }
diff --git a/pkgs/development/libraries/ortp/0.13.1.nix b/pkgs/development/libraries/ortp/0.13.1.nix
new file mode 100644
index 00000000000..ea1cd64b3d2
--- /dev/null
+++ b/pkgs/development/libraries/ortp/0.13.1.nix
@@ -0,0 +1,16 @@
+args: with args;
+stdenv.mkDerivation rec {
+  name = "ortp-" + version;
+
+  src = fetchurl {
+    url = "mirror://savannah/linphone/ortp/sources/${name}.tar.gz";
+    sha256 = "0k2963v4b15xnf4cpkpgjhsb8ckxpf6vdr8dnw7z3mzilji7391b";
+  };
+
+  configureFlags = "--enable-shared --disable-static";
+
+  meta = {
+    description = "a Real-Time Transport Protocol (RFC3550) stack under LGPL";
+    homepage = http://www.linphone.org/index.php/eng/code_review/ortp;
+  };
+}
diff --git a/pkgs/development/libraries/ortp/0.7.1.nix b/pkgs/development/libraries/ortp/0.7.1.nix
new file mode 100644
index 00000000000..7bedf39f8be
--- /dev/null
+++ b/pkgs/development/libraries/ortp/0.7.1.nix
@@ -0,0 +1,16 @@
+args: with args;
+stdenv.mkDerivation rec {
+  name = "ortp-" + version;
+
+  src = fetchurl {
+    url = "mirror://savannah/linphone/ortp/sources/${name}.tar.gz";
+    sha256 = "0gyl0yzfg78sjhbwnwc2g8yn4riwd1wcv183qihgan6z2d5cfbrg";
+  };
+
+  configureFlags = "--enable-shared --disable-static";
+
+  meta = {
+    description = "a Real-Time Transport Protocol (RFC3550) stack under LGPL";
+    homepage = http://www.linphone.org/index.php/eng/code_review/ortp;
+  };
+}
diff --git a/pkgs/development/libraries/pcre/default.nix b/pkgs/development/libraries/pcre/default.nix
index 1b4d7fc9093..cba26fae76c 100644
--- a/pkgs/development/libraries/pcre/default.nix
+++ b/pkgs/development/libraries/pcre/default.nix
@@ -1,14 +1,14 @@
-args: with args;
+{stdenv, fetchurl, unicodeSupport ? false, cplusplusSupport ? true}:
 
-stdenv.mkDerivation ({
-  name = "pcre-7.1";
+stdenv.mkDerivation {
+  name = "pcre-7.4";
   src = fetchurl {
-    url = ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.1.tar.bz2;
-    sha256 = "0rpkcw07jas3fw6ava3ni5zcrmbncwa8xlsa0lzq6z2iph5510li";
+    url = ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.4.tar.bz2;
+    sha256 = "1rdks2h5f3p2d71c4jnxaic1c9gmgsfky80djnafcdbdrhzkiyx5";
   };
+  configureFlags =
+    (if unicodeSupport then
+      "--enable-unicode-properties --enable-shared --disable-static"
+    else "") +
+    (if !cplusplusSupport then "--disable-cpp" else "");
 }
-// (if unicodeSupport then
-{
-  configureFlags = "--enable-unicode-properties --enable-shared --disable-static";
-}
-else {}))
diff --git a/pkgs/development/libraries/popt/popt-1.7.nix b/pkgs/development/libraries/popt/popt-1.7.nix
index 1170760c828..9ae06b0ed26 100644
--- a/pkgs/development/libraries/popt/popt-1.7.nix
+++ b/pkgs/development/libraries/popt/popt-1.7.nix
@@ -5,7 +5,10 @@ assert gettext != null;
 stdenv.mkDerivation {
   name = "popt-1.7";
   src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/popt-1.7.tar.gz;
+    urls = [
+      ftp://distro.ibiblio.org/pub/linux/distributions/pdaxrom/src/popt-1.7.tar.gz
+      http://nix.cs.uu.nl/dist/tarballs/popt-1.7.tar.gz
+    ];
     md5 = "5988e7aeb0ae4dac8d83561265984cc9";
   };
   buildInputs = [gettext];
diff --git a/pkgs/development/libraries/proj.4/default.nix b/pkgs/development/libraries/proj.4/default.nix
new file mode 100644
index 00000000000..ffb3bed5054
--- /dev/null
+++ b/pkgs/development/libraries/proj.4/default.nix
@@ -0,0 +1,15 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "proj-4.5.0";
+
+  src = fetchurl {
+    url = ftp://ftp.remotesensing.org/proj/proj-4.5.0.tar.gz;
+    sha256 = "1d2qz0vgp13hkfgaz7hkblhb9w2fh2blbjqz73xdinwc08cmflqv";
+  };
+
+  meta = { 
+      description = "Cartographic Projections Library";
+      homepage = http://proj.maptools.org;
+      license = "MIT";
+  };
+}
diff --git a/pkgs/development/libraries/pth/default.nix b/pkgs/development/libraries/pth/default.nix
new file mode 100644
index 00000000000..631a7622406
--- /dev/null
+++ b/pkgs/development/libraries/pth/default.nix
@@ -0,0 +1,14 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "pth-2.0.7";
+	
+	src = fetchurl {
+		url = "mirror://gnu/pth/${name}.tar.gz";
+		sha256 = "0ckjqw5kz5m30srqi87idj7xhpw6bpki43mj07bazjm2qmh3cdbj";
+	};
+
+	meta = {
+		description = "The GNU Portable Threads";
+		homepage = http://www.gnu.org/software/pth;
+	};
+}
diff --git a/pkgs/development/libraries/qt-4/builder.sh b/pkgs/development/libraries/qt-4/builder.sh
deleted file mode 100755
index 5cd4164a7c2..00000000000
--- a/pkgs/development/libraries/qt-4/builder.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-source $stdenv/setup
-
-ensureDir $out/nix-support
-substitute "$hook" "$out/nix-support/setup-hook" --subst-var out
-
-# !!! TODO: -system-libmng
-configureFlags="-prefix $out $configureFlags"
-
-genericBuild
diff --git a/pkgs/development/libraries/qt-4/default.nix b/pkgs/development/libraries/qt-4/default.nix
index 20893e8d8d9..046ebde99a1 100644
--- a/pkgs/development/libraries/qt-4/default.nix
+++ b/pkgs/development/libraries/qt-4/default.nix
@@ -4,11 +4,11 @@ rec {
   setupHook = ./setup-hook.sh;  
   propagatedBuildInputs = [libXft libXrender libXrandr randrproto xextproto
   libXinerama xineramaproto libXcursor zlib libjpeg mysql libpng which mesa
-  libXmu openssl dbus cups pkgconfig libXext freetype fontconfig inputproto
+  libXmu openssl dbus.libs cups pkgconfig libXext freetype fontconfig inputproto
   fixesproto libXfixes glib libtiff];
   prefixKey = "-prefix ";
   configureFlags = "
-    -v -no-separate-debug-info -release -nomake examples -nomake demos
+    -v -no-separate-debug-info -release
     -system-zlib -system-libpng -system-libjpeg -fast
     -qt-gif -confirm-license
     -opengl -xrender -xrandr -xinerama -xcursor -qt-sql-mysql
@@ -18,10 +18,10 @@ rec {
 }; in
 rec {
 	trolltech = stdenv.mkDerivation (common // {
-	  name = "qt-4.3.1";
+	  name = "qt-4.3.3";
 	  src = fetchurl {
-		url = ftp://ftp.trolltech.com/qt/source/qt-x11-opensource-src-4.3.1.tar.gz;
-		sha256 = "0qg6apy2r7jbbfinxh0v1jm08yv890r40hhmy5cysn239v3x0nad";
+		url = ftp://ftp.trolltech.com/qt/source/qt-x11-opensource-src-4.3.3.tar.gz;
+		sha256 = "0w0mfm0wwmbj1vnjn27rza1r9wj8k47mn9ril8swprffqnn4p4w9";
 	  };
 	  patchPhase = common.patchPhase;
 	});
@@ -29,8 +29,8 @@ rec {
 	  name = "qt-kde-4.3svn";
 	  src = fetchsvn {
 		  url = svn://anonsvn.kde.org/home/kde/trunk/qt-copy;
-		  rev = "732646";
-		  md5 = "9757de3dce16b483f2f358d287c848ee";
+		  rev = "761061";
+		  sha256 = "0i98kh435dj29ln1lnidxwivcha1m553s4l8c1h2b3yd4950w8x4";
 	  };
 	  patchPhase = "mkdir .svn; bash apply_patches;" + common.patchPhase;
 	});
diff --git a/pkgs/development/libraries/readline/readline5.nix b/pkgs/development/libraries/readline/readline5.nix
index f5271f01bcc..96ec1ffea79 100644
--- a/pkgs/development/libraries/readline/readline5.nix
+++ b/pkgs/development/libraries/readline/readline5.nix
@@ -1,10 +1,12 @@
-{ stdenv, fetchurl, ncurses }:
+args: with args;
 
 stdenv.mkDerivation {
   name = "readline-5.2";
   src = fetchurl {
     url = mirror://gnu/readline/readline-5.2.tar.gz;
-    md5 = "e39331f32ad14009b9ff49cc10c5e751";
+    sha256 = "0icz4hqqq8mlkwrpczyaha94kns0am9z0mh3a2913kg2msb8vs0j";
   };
   propagatedBuildInputs = [ncurses];
+  configureFlags = "--enable-shared --disable-static";
+  patches = stdenv.lib.optional stdenv.isDarwin ./shobj-darwin.patch;
 }
diff --git a/pkgs/development/libraries/readline/shobj-darwin.patch b/pkgs/development/libraries/readline/shobj-darwin.patch
new file mode 100644
index 00000000000..a9199ca3e89
--- /dev/null
+++ b/pkgs/development/libraries/readline/shobj-darwin.patch
@@ -0,0 +1,11 @@
+--- a/support/shobj-conf.orig	2006-04-11 06:15:43.000000000 -0700
++++ b/support/shobj-conf	2007-11-08 01:15:43.000000000 -0800
+@@ -171,7 +171,7 @@
+ 	SHLIB_LIBSUFF='dylib'
+ 
+ 	case "${host_os}" in
+-	darwin[78]*)	SHOBJ_LDFLAGS=''
++	darwin[789]*)	SHOBJ_LDFLAGS=''
+ 			SHLIB_XLDFLAGS='-dynamiclib -arch_only `/usr/bin/arch` -install_name $(libdir)/$@ -current_version $(SHLIB_MAJOR)$(SHLIB_MINOR) -compatibility_version $(SHLIB_MAJOR) -v'
+ 			;;
+ 	*)		SHOBJ_LDFLAGS='-dynamic'
diff --git a/pkgs/development/libraries/redland/default.nix b/pkgs/development/libraries/redland/default.nix
index 1e657991eab..d344fbc0ac3 100644
--- a/pkgs/development/libraries/redland/default.nix
+++ b/pkgs/development/libraries/redland/default.nix
@@ -1,13 +1,15 @@
 args:
 with args;
-stdenv.mkDerivation {
-  name = "redland-1.0.6";
+stdenv.mkDerivation rec {
+  name = "redland-1.0.7";
 
   src = fetchurl {
-    url = http://prdownloads.sourceforge.net/librdf/redland-1.0.6.tar.gz;
-    sha256 = "16hm8s6wy43avy4xcsq74n2dyzwzsdq2h2l2jav0by7s6mkh5gxw";
+    url = "mirror://sf/librdf/${name}.tar.gz";
+    sha256 = "1z160hhrnlyy5c8vh2hjza6kdfmzml8mg9dk8yffifkhnxjq5r2z";
   };
-  buildInputs = [ bdb openssl libxml2 pkgconfig perl];
-  configureFlags="--without-static --with-threads --with-bdb=${bdb}";
+  buildInputs = [pkgconfig];
+  propagatedBuildInputs = [ bdb openssl libxslt perl mysql postgresql sqlite
+    curl pcre];
+  configureFlags = "--disable-static --with-threads --with-bdb=${bdb}";
   patchPhase="sed -e 1s@/usr@${perl}@ -i utils/touch-mtime.pl";
 }
diff --git a/pkgs/development/libraries/speex/default.nix b/pkgs/development/libraries/speex/default.nix
index 556b6c19dcc..6904339a57c 100644
--- a/pkgs/development/libraries/speex/default.nix
+++ b/pkgs/development/libraries/speex/default.nix
@@ -1,10 +1,10 @@
 args: with args;
 
 stdenv.mkDerivation {
-  name = "speex-1.2beta2";
+  name = "speex-1.2beta3";
   src = fetchurl {
-    url = http://downloads.us.xiph.org/releases/speex/speex-1.2beta2.tar.gz;
-	sha256 = "1np34q5i7yswkgknb8pa6ngqb4l4jv84c9yqnn0215vncbl76xg5";
+    url = http://downloads.us.xiph.org/releases/speex/speex-1.2beta3.tar.gz;
+	sha256 = "1az7kiwa8mzi1x7j01gcakx854qcbm4g67n0c4s56bvny6dn18vp";
   };
   buildInputs = [libogg];
 }
diff --git a/pkgs/development/libraries/strigi/default.nix b/pkgs/development/libraries/strigi/default.nix
deleted file mode 100644
index 85f21652b53..00000000000
--- a/pkgs/development/libraries/strigi/default.nix
+++ /dev/null
@@ -1,20 +0,0 @@
-{ stdenv, fetchurl, zlib, bzip2, expat, pkgconfig, cluceneCore, cluceneContrib,
-qt, cmake, dbus, libxml2, perl }:
-
-stdenv.mkDerivation {
-  name = "strigi-0.5.3dev";
-
-  src = fetchurl {
-    url = http://repo.calcforge.org/f8/strigi-0.5.3.tar.bz2;
-    sha256 = "0rv7l2s4r022hrsw3jw0pvxh0yzlaw53jhmjxi3cbi6mdvc1y2sv";
-  };
-
-  patchPhase="sed -e 's/ iconv / /' -i ../cmake/FindIconv.cmake;
-  export CLUCENE_HOME=${cluceneCore}";
-  buildInputs = [zlib cluceneCore cluceneContrib expat bzip2 pkgconfig qt cmake
-  stdenv.gcc.libc dbus libxml2 perl];
-
-  meta = {
-    description = "Strigi is a fast and light desktop search engine";
-  };
-}
diff --git a/pkgs/development/libraries/t1lib/default.nix b/pkgs/development/libraries/t1lib/default.nix
index c5b26424cdf..a3ebe5e27ca 100644
--- a/pkgs/development/libraries/t1lib/default.nix
+++ b/pkgs/development/libraries/t1lib/default.nix
@@ -1,11 +1,12 @@
-{stdenv, fetchurl, x11, libXaw}:
+{stdenv, fetchurl, x11, libXaw, libXpm}:
 
 stdenv.mkDerivation {
   name = "t1lib-5.1.0";
   src = fetchurl {
-    url = ftp://ftp.nluug.nl/pub/metalab/libs/graphics/t1lib-5.1.0.tar.gz;
-    md5 = "a05bed4aa63637052e60690ccde70421";
+    url = ftp://ftp.nluug.nl/pub/metalab/libs/graphics/t1lib-5.1.1.tar.gz;
+    sha256 = "0r1wb94kjd8jwym9na2k2snikizrnyc4cf4mf92v89r4yy0apph8";
   };
-  buildInputs = [x11 libXaw];
+  buildInputs = [x11 libXaw libXpm];
   buildFlags = "without_doc";
 }
+
diff --git a/pkgs/development/libraries/tapioca-qt/default.nix b/pkgs/development/libraries/tapioca-qt/default.nix
new file mode 100644
index 00000000000..962a82a8a1a
--- /dev/null
+++ b/pkgs/development/libraries/tapioca-qt/default.nix
@@ -0,0 +1,16 @@
+args: with args;
+let rev = "2066"; in
+stdenv.mkDerivation {
+	name = "tapioca-qt-r${rev}";
+	src = fetchsvn {
+		url = "https://tapioca-voip.svn.sourceforge.net/svnroot/tapioca-voip/trunk/tapioca-qt";
+		inherit rev;
+		sha256 = "0r2qzlm56yizdi64xga6v2sdhdcgl3cvlsd7g9ynh95813nky88z";
+	};
+
+	buildInputs = [cmake];
+	propagatedBuildInputs = [telepathy_qt stdenv.gcc.libc];
+	meta = {
+		description = "Qt Tapioca binding library";
+	};
+}
diff --git a/pkgs/development/libraries/telepathy-gabble/default.nix b/pkgs/development/libraries/telepathy-gabble/default.nix
new file mode 100644
index 00000000000..44affecefd8
--- /dev/null
+++ b/pkgs/development/libraries/telepathy-gabble/default.nix
@@ -0,0 +1,17 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "telepathy-gabble-0.7.2";
+
+	src = fetchurl {
+		url = "${meta.homepage}/releases/telepathy-gabble/${name}.tar.gz";
+		sha256 = "0r1j475a5s2a4f10hybmavf4kf6nrnjnv091dpic5nl2asdilb7i";
+	};
+
+	propagatedBuildInputs = [telepathy_glib loudmouth];
+	buildInputs = [pkgconfig libxslt];
+	configureFlags = "--enable-shared --disable-static";
+
+	meta = {
+		homepage = http://telepathy.freedesktop.org;
+	};
+}
diff --git a/pkgs/development/libraries/telepathy-glib/default.nix b/pkgs/development/libraries/telepathy-glib/default.nix
new file mode 100644
index 00000000000..fd4f59bdc8a
--- /dev/null
+++ b/pkgs/development/libraries/telepathy-glib/default.nix
@@ -0,0 +1,17 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "telepathy-glib-0.7.0";
+
+	src = fetchurl {
+		url = "${meta.homepage}/releases/telepathy-glib/${name}.tar.gz";
+		sha256 = "0hf1jrgisr7skrji7djh66q0ic351vlsm65xqy982p5d0axzxkz5";
+	};
+
+	propagatedBuildInputs = [dbus_glib glib python];
+	buildInputs = [pkgconfig libxslt];
+	configureFlags = "--enable-shared --disable-static";
+
+	meta = {
+		homepage = http://telepathy.freedesktop.org;
+	};
+}
diff --git a/pkgs/development/libraries/telepathy-qt/default.nix b/pkgs/development/libraries/telepathy-qt/default.nix
new file mode 100644
index 00000000000..6e8e84399d1
--- /dev/null
+++ b/pkgs/development/libraries/telepathy-qt/default.nix
@@ -0,0 +1,16 @@
+args: with args;
+let rev = "2031"; in
+stdenv.mkDerivation {
+	name = "telepathy-qt-r${rev}";
+	src = fetchsvn {
+		url = "https://tapioca-voip.svn.sourceforge.net/svnroot/tapioca-voip/trunk/telepathy-qt";
+		inherit rev;
+		sha256 = "0d7psgc8nr5bryrjgfg92622hbilp0qwx0pya3836bz2l6x3msnb";
+	};
+
+	buildInputs = [cmake];
+	propagatedBuildInputs = [qt stdenv.gcc.libc];
+	meta = {
+		description = "Qt bindings for telepathy";
+	};
+}
diff --git a/pkgs/development/libraries/tk/8.4.16.nix b/pkgs/development/libraries/tk/8.4.16.nix
new file mode 100644
index 00000000000..1f26db83f1b
--- /dev/null
+++ b/pkgs/development/libraries/tk/8.4.16.nix
@@ -0,0 +1,18 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "tk-${version}";
+  src = fetchurl {
+    url = "mirror://sourceforge/tcl/tk${version}-src.tar.gz";
+    sha256 = "0cciavzd05bpm5yfppid0s0vsf8kabwia9620vgvi26sv1gjgwhb";
+  };
+  postInstall = ''
+    echo -e '#! /bin/sh \n $( readlink -f $( type -tP wish${__substring 0 3 version}) ) "$@"' >$out/bin/wish
+    chmod a+x $out/bin/wish
+  ''; 
+  configureFlags="--with-tcl=${tcl}/lib";
+  preConfigure = "cd unix";
+
+  buildInputs = [tcl x11];
+  inherit tcl;
+}
diff --git a/pkgs/development/libraries/tk/default.nix b/pkgs/development/libraries/tk/default.nix
deleted file mode 100644
index f36438e56d2..00000000000
--- a/pkgs/development/libraries/tk/default.nix
+++ /dev/null
@@ -1,12 +0,0 @@
-{stdenv, fetchurl, tcl, x11}:
-
-stdenv.mkDerivation {
-  name = "tk-8.4.13";
-  builder = ./builder.sh;
-  src = fetchurl {
-    url = mirror://sourceforge/tcl/tk8.4.13-src.tar.gz;
-    md5 = "0a16d4d9398e43cbb85784c85fb807a4";
-  };
-  buildInputs = [tcl x11];
-  inherit tcl;
-}
diff --git a/pkgs/development/libraries/xine-lib/default.nix b/pkgs/development/libraries/xine-lib/default.nix
index 191fa13c0ce..ba6880d525a 100644
--- a/pkgs/development/libraries/xine-lib/default.nix
+++ b/pkgs/development/libraries/xine-lib/default.nix
@@ -1,30 +1,14 @@
-{ xvideoSupport ? true
-, xineramaSupport ? true
-, encryptedDVDSupport ? true
-, alsaSupport ? true
-, stdenv, fetchurl, zlib, x11
-, libXv ? null, libXinerama ? null, libdvdcss ? null, alsaLib ? null
-}:
+args: with args;
 
-assert xvideoSupport -> libXv != null;
-assert xineramaSupport -> libXinerama != null;
-assert encryptedDVDSupport -> libdvdcss != null;
-assert alsaSupport -> alsaLib != null;
-
-(stdenv.mkDerivation {
-  name = "xine-lib-1.1.7";
-  builder = ./builder.sh;
+(stdenv.mkDerivation rec {
+  name = "xine-lib-1.1.9.1";
   src = fetchurl {
-    url = mirror://sourceforge/xine/xine-lib-1.1.7.tar.bz2;
-    sha256 = "1aycmhvq95gbb5mqw5skgcxyn4nh5qkzq21yclnqk5yzflpwwvvg";
+    url = "mirror://sourceforge/xine/${name}.tar.bz2";
+    sha256 = "1rz4k2a9pny2ksqb5diw1ci8ijihpcm0mi8qxp5p7nasgzgqcj82";
   };
-  buildInputs = [
-    x11
-    (if xvideoSupport then libXv else null)
-    (if xineramaSupport then libXinerama else null)
-    (if alsaSupport then alsaLib else null)
-  ];
-  libXv = if xvideoSupport then libXv else null;
-  libdvdcss = if encryptedDVDSupport then libdvdcss else null;
+  buildInputs = [ x11 pkgconfig libXv libXinerama alsaLib mesa aalib SDL
+  libvorbis libtheora speex ];
+  configureFlags = "--with-xv-path=${libXv}/lib";
+  NIX_LDFLAGS = "-rpath ${libdvdcss}/lib -L${libdvdcss}/lib -ldvdcss";
   propagatedBuildInputs = [zlib];
-}) // {inherit xineramaSupport libXinerama;}
+}) // { xineramaSupport = true; inherit libXinerama; }
diff --git a/pkgs/development/libraries/xine-lib/xine-lib-linux-headers-2.6.23.patch b/pkgs/development/libraries/xine-lib/xine-lib-linux-headers-2.6.23.patch
new file mode 100644
index 00000000000..cd3d766ea8f
--- /dev/null
+++ b/pkgs/development/libraries/xine-lib/xine-lib-linux-headers-2.6.23.patch
@@ -0,0 +1,22 @@
+# HG changeset patch
+# User Ken Moffat <zarniwhoop@users.sourceforge.net>
+# Date 1193435051 -3600
+# Node ID 8a369a0d5ff104cc115bbe76c6b4f3e281d1ef25
+# Parent 05fde4048642d1a7edb19ea623acd760064718bc
+Linux-2.6.23 header change breaks build
+>
+> /* Special codes used when specifying changer slots. */
+> #define CDSL_NONE               (INT_MAX-1)
+> #define CDSL_CURRENT            INT_MAX
+
+--- a/src/input/vcd/libcdio/_cdio_linux.c	Tue Oct 23 23:45:58 2007 +0100
++++ b/src/input/vcd/libcdio/_cdio_linux.c	Fri Oct 26 22:44:11 2007 +0100
+@@ -59,6 +59,7 @@ static const char _rcsid[] = "$Id: _cdio
+ #include <unistd.h>
+ #include <fcntl.h>
+ #include <mntent.h>
++#include <limits.h>
+ 
+ #include <linux/cdrom.h>
+ #include <scsi/scsi.h>
+
diff --git a/pkgs/development/perl-modules/DB_File/default.nix b/pkgs/development/perl-modules/DB_File/default.nix
new file mode 100644
index 00000000000..6931d5d424c
--- /dev/null
+++ b/pkgs/development/perl-modules/DB_File/default.nix
@@ -0,0 +1,11 @@
+{fetchurl, perl, db4}:
+
+import ../generic perl {
+  name = "DB_File-1.816";
+  src = fetchurl {
+    url = http://search.cpan.org/CPAN/authors/id/P/PM/PMQS/DB_File-1.816.tar.gz;
+    sha256 = "1a668hk5v0l180kbqss2hq9khl756cmrykn8fz1rl4qzsp6lq284";
+  };
+  perlPreHook = "source ${./hook.sh}";
+  inherit db4;
+}
diff --git a/pkgs/development/perl-modules/DB_File/hook.sh b/pkgs/development/perl-modules/DB_File/hook.sh
new file mode 100644
index 00000000000..033de2fd5db
--- /dev/null
+++ b/pkgs/development/perl-modules/DB_File/hook.sh
@@ -0,0 +1,11 @@
+oldPreConfigure=$preConfigure
+preConfigure=myPreConfigure
+myPreConfigure() {
+    cat > config.in <<EOF
+PREFIX = size_t
+HASH = u_int32_t
+LIB = $db4/lib
+INCLUDE = $db4/include
+EOF
+    $oldPreConfigure
+}
diff --git a/pkgs/development/python-modules/ZopeInterface/default.nix b/pkgs/development/python-modules/ZopeInterface/default.nix
index 0fe40954115..6bcedcd0f17 100644
--- a/pkgs/development/python-modules/ZopeInterface/default.nix
+++ b/pkgs/development/python-modules/ZopeInterface/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, python}:
 
 stdenv.mkDerivation {
-  name = "ZopeInterface-3.1.0c1";
+  name = "ZopeInterface-3.3.0";
   src = fetchurl {
-    url = http://www.zope.org/Products/ZopeInterface/3.1.0c1/ZopeInterface-3.1.0c1.tgz;
-    md5 = "f34cb95f2fbdbe3f1850c95cefddbd2c";
+    url = http://www.zope.org/Products/ZopeInterface/3.3.0/zope.interface-3.3.0.tar.gz;
+    sha256 = "0xahg9cmagn4j3dbifvgzbjliw2jdrbf27fhqwkdp8j80xpyyjf0";
   };
   buildInputs = [python];
   buildPhase = "true";
diff --git a/pkgs/development/python-modules/pil/default.nix b/pkgs/development/python-modules/pil/default.nix
index 863366f1a42..d5ed9aae12a 100644
--- a/pkgs/development/python-modules/pil/default.nix
+++ b/pkgs/development/python-modules/pil/default.nix
@@ -1,20 +1,20 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "python-imaging-1.1.6";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://effbot.org/downloads/Imaging-1.1.6.tar.gz;
     sha256 = "141zidl3s9v4vfi3nsbg42iq1lc2a932gprqr1kij5hrnn53bmvx";
   };
 
-  buildInputs =(with args; [python zlib libtiff libjpeg freetype]);
+  buildInputs = [python zlib libtiff libjpeg freetype];
  
-  configurePhase = (with args;"
+  configurePhase = "
 		sed -e 's@FREETYPE_ROOT = None@FREETYPE_ROOT = libinclude(\"${freetype}\")@' -i setup.py
 		sed -e 's@JPEG_ROOT = None@JPEG_ROOT = libinclude(\"${libjpeg}\")@' -i setup.py
 		sed -e 's@TIFF_ROOT = None@TIFF_ROOT = libinclude(\"${libtiff}\")@' -i setup.py
 		sed -e 's@ZLIB_ROOT = None@ZLIB_ROOT = libinclude(\"${zlib}\")@' -i setup.py
-	");
+	";
 
   buildPhase = "true";
 	
diff --git a/pkgs/development/python-modules/pygame/default.nix b/pkgs/development/python-modules/pygame/default.nix
index 0ed717479d8..cad9b17ebad 100644
--- a/pkgs/development/python-modules/pygame/default.nix
+++ b/pkgs/development/python-modules/pygame/default.nix
@@ -1,22 +1,22 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "pygame-1.7";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://www.pygame.org/ftp/pygame-1.7.1release.tar.gz ;
     sha256 = "0hl0rmgjcqj217fibwyilz7w9jpg0kh7hsa7vyzd4cgqyliskpqi";
   };
 
-  buildInputs =(with args; [python pkgconfig SDL SDL_image SDL_ttf]);
+  buildInputs = [python pkgconfig SDL SDL_image SDL_ttf];
  
-  configurePhase = (with args;
+  configurePhase =
 	 "
 	export LOCALBASE=///
 	sed -e \"/origincdirs =/a'${SDL_image}/include/SDL','${SDL_image}/include',\" -i config_unix.py
 	sed -e \"/origlibdirs =/aoriglibdirs += '${SDL_image}/lib',\" -i config_unix.py
 	sed -e \"/origincdirs =/a'${SDL_ttf}/include/SDL','${SDL_ttf}/include',\" -i config_unix.py
 	sed -e \"/origlibdirs =/aoriglibdirs += '${SDL_ttf}/lib',\" -i config_unix.py
-	yes Y | python config.py ");
+	yes Y | python config.py ";
 
   buildPhase = "yes Y | python setup.py build";	
 
diff --git a/pkgs/development/python-modules/twisted/default.nix b/pkgs/development/python-modules/twisted/default.nix
index 37a42faf856..7fdf610d74c 100644
--- a/pkgs/development/python-modules/twisted/default.nix
+++ b/pkgs/development/python-modules/twisted/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, python, ZopeInterface}:
 
 stdenv.mkDerivation {
-  name = "twisted-2.4.0";
+  name = "twisted-2.5.0";
   src = fetchurl {
-    url = http://tmrc.mit.edu/mirror/twisted/Twisted/2.4/Twisted-2.4.0.tar.bz2;
-    md5 = "42eb0c8fd0f8707a39fff1dd6adab27d";
+    url = http://tmrc.mit.edu/mirror/twisted/Twisted/2.5/Twisted-2.5.0.tar.bz2;
+    sha256 = "1kfj4354lm4kphm317giyldykyd17lba2xd7y512lxc38hzxzcpk";
   };
   buildInputs = [python];
   propagatedBuildInputs = [ZopeInterface];
diff --git a/pkgs/development/tools/build-managers/cmake/setup-hook.sh b/pkgs/development/tools/build-managers/cmake/setup-hook.sh
index 4712ef2b648..2ec77d8223e 100755
--- a/pkgs/development/tools/build-managers/cmake/setup-hook.sh
+++ b/pkgs/development/tools/build-managers/cmake/setup-hook.sh
@@ -1,49 +1,49 @@
 addCMakeParamsInclude()
 {
-	addToSearchPath CMAKE_INCLUDE_PATH /include "" $1
+    addToSearchPath CMAKE_INCLUDE_PATH /include "" $1
 }
 
 addCMakeParamsLibs()
 {
-	addToSearchPath CMAKE_LIBRARY_PATH /lib "" $1
+    addToSearchPath CMAKE_LIBRARY_PATH /lib "" $1
 }
 
 addCMakeModulePath()
 {
-	addToSearchPath CMAKE_MODULE_PATH /share/cmake-2.4/Modules "" $1
+    addToSearchPath CMAKE_MODULE_PATH /share/cmake-2.4/Modules "" $1
 }
 
 fixCmakeFiles()
 {
-	local replaceArgs;
-	echo "Fixing cmake files"
-	replaceArgs="-e -f -L -T /usr /FOO"
-   	replaceArgs="${replaceArgs}	-a NO_DEFAULT_PATH \"\" -a NO_SYSTEM_PATH \"\""
-	find $1 -type f -name "*.cmake" | xargs replace-literal ${replaceArgs}
+    local replaceArgs;
+    echo "Fixing cmake files"
+    replaceArgs="-e -f -L -T /usr /FOO"
+    replaceArgs="${replaceArgs}     -a NO_DEFAULT_PATH \"\" -a NO_SYSTEM_PATH \"\""
+    find $1 -type f -name "*.cmake" | xargs replace-literal ${replaceArgs}
 }
 
 cmakePostUnpack()
 {
-	sourceRoot=$sourceRoot/build
-	mkdir -v $sourceRoot
-	echo source root reset to $sourceRoot
-
-	if [ -z "$dontFixCmake" ]; then
-		fixCmakeFiles .
-	fi
-
-	if [ -z "$configureScript" ]; then
-		configureScript="cmake .."
-	fi
-	if [ -z "$dontAddPrefix" ]; then
-		dontAddPrefix=1
-		configureFlags="-DCMAKE_INSTALL_PREFIX=$out $configureFlags"
-	fi
+    sourceRoot=$sourceRoot/build
+    mkdir -v $sourceRoot
+    echo source root reset to $sourceRoot
+
+    if [ -z "$dontFixCmake" ]; then
+        fixCmakeFiles .
+    fi
+
+    if [ -z "$configureScript" ]; then
+        configureScript="cmake .."
+    fi
+    if [ -z "$dontAddPrefix" ]; then
+        dontAddPrefix=1
+        configureFlags="-DCMAKE_INSTALL_PREFIX=$out $configureFlags"
+    fi
 }
 
 
 if [ -z "$noCmakeTewaks" ]; then
-	postUnpack="cmakePostUnpack${postUnpack:+; }${postUnpack}"
+    postUnpack="cmakePostUnpack${postUnpack:+; }${postUnpack}"
 fi;
 
 envHooks=(${envHooks[@]} addCMakeParamsInclude addCMakeParamsLibs addCMakeModulePath)
diff --git a/pkgs/development/tools/build-managers/gnumake/log.patch b/pkgs/development/tools/build-managers/gnumake/log.patch
index 99111ca3495..3104e1f2bde 100644
--- a/pkgs/development/tools/build-managers/gnumake/log.patch
+++ b/pkgs/development/tools/build-managers/gnumake/log.patch
@@ -1,6 +1,6 @@
-diff -rc make-orig/job.c make-3.81/job.c
-*** make-orig/job.c	2006-03-20 04:03:04.000000000 +0100
---- make-3.81/job.c	2006-06-21 17:31:52.000000000 +0200
+diff -rc make-3.81-orig/job.c make-3.81/job.c
+*** make-3.81-orig/job.c	2006-03-20 04:03:04.000000000 +0100
+--- make-3.81/job.c	2008-02-20 17:41:25.000000000 +0100
 ***************
 *** 1083,1089 ****
        appear.  */
@@ -18,9 +18,9 @@ diff -rc make-orig/job.c make-3.81/job.c
   
     /* Tell update_goal_chain that a command has been started on behalf of
        this target.  It is important that this happens here and not in
-diff -rc make-orig/main.c make-3.81/main.c
-*** make-orig/main.c	2006-03-20 03:36:37.000000000 +0100
---- make-3.81/main.c	2006-06-21 17:48:43.000000000 +0200
+diff -rc make-3.81-orig/main.c make-3.81/main.c
+*** make-3.81-orig/main.c	2006-03-20 03:36:37.000000000 +0100
+--- make-3.81/main.c	2008-02-20 17:41:25.000000000 +0100
 ***************
 *** 886,891 ****
 --- 886,900 ----
@@ -83,9 +83,9 @@ diff -rc make-orig/main.c make-3.81/main.c
 + 
 + int logNestingStdout = 0;
 + int logNestingStderr = 0;
-diff -rc make-orig/make.h make-3.81/make.h
-*** make-orig/make.h	2006-02-16 00:54:43.000000000 +0100
---- make-3.81/make.h	2006-06-21 17:39:35.000000000 +0200
+diff -rc make-3.81-orig/make.h make-3.81/make.h
+*** make-3.81-orig/make.h	2006-02-16 00:54:43.000000000 +0100
+--- make-3.81/make.h	2008-02-20 17:41:25.000000000 +0100
 ***************
 *** 609,611 ****
 --- 609,613 ----
@@ -94,15 +94,16 @@ diff -rc make-orig/make.h make-3.81/make.h
   
 + extern int logNestingStdout;
 + extern int logNestingStderr;
-diff -rc make-orig/remake.c make-3.81/remake.c
-*** make-orig/remake.c	2006-03-20 03:36:37.000000000 +0100
---- make-3.81/remake.c	2006-06-21 17:31:52.000000000 +0200
+diff -rc make-3.81-orig/remake.c make-3.81/remake.c
+*** make-3.81-orig/remake.c	2006-03-20 03:36:37.000000000 +0100
+--- make-3.81/remake.c	2008-02-20 17:44:01.000000000 +0100
 ***************
 *** 1120,1126 ****
---- 1120,1130 ----
+--- 1120,1131 ----
         /* The normal case: start some commands.  */
         if (!touch_flag || file->cmds->any_recurse)
   	{
++           log_working_directory (1);
 +           fprintf(stderr, "\e[pbuilding %s\n", file->name);
 +           logNestingStderr++;
   	  execute_file_commands (file);
diff --git a/pkgs/development/tools/documentation/haddock/default.nix b/pkgs/development/tools/documentation/haddock/default.nix
new file mode 100644
index 00000000000..86d07b240a5
--- /dev/null
+++ b/pkgs/development/tools/documentation/haddock/default.nix
@@ -0,0 +1,11 @@
+{cabal}:
+
+cabal.mkDerivation (self : {
+  pname = "haddock";
+  version = "2.0.0.0";
+  name = self.fname;
+  sha256 = "a2ea5bdc127bc8b189a8d869f582ec774fea0933e7f5ca89549a6c142b9993df";
+  meta = {
+    description = "a tool for automatically generating documentation from annotated Haskell source code";
+  };
+})
diff --git a/pkgs/development/tools/guile/guile-lint/default.nix b/pkgs/development/tools/guile/guile-lint/default.nix
new file mode 100644
index 00000000000..f9032dd4884
--- /dev/null
+++ b/pkgs/development/tools/guile/guile-lint/default.nix
@@ -0,0 +1,26 @@
+{stdenv, fetchurl, guile}:
+
+stdenv.mkDerivation rec {
+  name = "guile-lint-14";
+  src = fetchurl {
+    url = "http://www.geocities.com/user42_kevin/guile-lint/"
+            + name + ".tar.bz2.bin";
+    sha256 = "5bfcf7a623338b2ef81ac097e3e136eaf32856dd0730b7eeaff3161067b5d0be";
+  };
+
+  buildInputs = [ guile ];
+
+  unpackPhase = ''tar xjvf "$src" && sourceRoot="$PWD/${name}"'';
+  patchPhase = ''
+    cat guile-lint.in |						\
+    sed 's|^exec guile|exec $\{GUILE:-${guile}/bin/guile}|g' > ,,tmp &&	\
+    mv ,,tmp guile-lint.in
+  '';
+
+  meta = {
+    description = ''Guile-Lint checks syntax and semantics in a
+                    Guile program or module.'';
+    homepage = http://www.geocities.com/user42_kevin/guile-lint/index.html;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/development/tools/haskell/uuagc/default.nix b/pkgs/development/tools/haskell/uuagc/default.nix
index 519244ae7b8..b45db5f2ea6 100644
--- a/pkgs/development/tools/haskell/uuagc/default.nix
+++ b/pkgs/development/tools/haskell/uuagc/default.nix
@@ -1,14 +1,12 @@
-{stdenv, fetchurl, ghc, uulib}:
-
-stdenv.mkDerivation
-{
-  name = "uuagc-0.9.2";
-
-  src = fetchurl { url = http://www.cs.uu.nl/~ariem/uuagc-0.9.2-src.tar.gz;
-                   md5 = "cbac92287c9c0a858ccbfa37615d9f5f";
-                 };
-
-  buildInputs = [ghc uulib];
-
-  meta = { description = "The UUAG Compiler"; };
-}
+{cabal, uulib}:
+
+cabal.mkDerivation (self : {
+  pname = "uuagc";
+  version = "0.9.5";
+  name = self.fname;
+  sha256 = "c5be435efa609f72c09e175dd5cf7835a060bd7eaf6634ec4cde72ea84b99f25";
+  extraBuildInputs = [uulib];
+  meta = {
+    description = "Attribute Grammar System of Universiteit Utrecht";
+  };
+})
diff --git a/pkgs/development/tools/misc/automake/setup-hook.sh b/pkgs/development/tools/misc/automake/setup-hook.sh
index 4489d343510..2b12ae3aee0 100644
--- a/pkgs/development/tools/misc/automake/setup-hook.sh
+++ b/pkgs/development/tools/misc/automake/setup-hook.sh
@@ -1,5 +1,5 @@
 addAclocals () {
-	addToSearchPathWithCustomDelimiter : ACLOCAL_PATH /share/aclocal "" $1
+    addToSearchPathWithCustomDelimiter : ACLOCAL_PATH /share/aclocal "" $1
 }
 
 envHooks=(${envHooks[@]} addAclocals)
diff --git a/pkgs/development/tools/misc/avrdude/default.nix b/pkgs/development/tools/misc/avrdude/default.nix
index e573d0751f2..f87d305dfb2 100644
--- a/pkgs/development/tools/misc/avrdude/default.nix
+++ b/pkgs/development/tools/misc/avrdude/default.nix
@@ -12,7 +12,7 @@ let
     #defaultFlags = ["doc"];
   };
 
-in args.stdenv.mkDerivation {
+in stdenv.mkDerivation {
 
   # passing the flags in case a library using this want's to check them (*) .. 
   inherit (co) /* flags */ buildInputs configureFlags;
diff --git a/pkgs/development/tools/misc/ccache/default.nix b/pkgs/development/tools/misc/ccache/default.nix
new file mode 100644
index 00000000000..8342dfcc728
--- /dev/null
+++ b/pkgs/development/tools/misc/ccache/default.nix
@@ -0,0 +1,15 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "ccache-2.4";
+  src = fetchurl {
+    url = http://samba.org/ftp/ccache/ccache-2.4.tar.gz;
+    sha256 = "435f862ca5168c346f5aa9e242174bbf19a5abcaeecfceeac2f194558827aaa0";
+  };
+
+  meta = {
+    description = "ccache, a tool that caches compilation results.";
+    homepage = http://ccache.samba.org/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/development/tools/misc/elfutils/default.nix b/pkgs/development/tools/misc/elfutils/0.127.nix
index a57792d7039..efa91fa637c 100644
--- a/pkgs/development/tools/misc/elfutils/default.nix
+++ b/pkgs/development/tools/misc/elfutils/0.127.nix
@@ -1,9 +1,10 @@
-{stdenv, fetchurl}:
+args: with args;
 
 stdenv.mkDerivation {
-  name = "elfutils-0.127";
+  name = "elfutils-"+version;
   src = fetchurl {
     url = http://nix.cs.uu.nl/dist/tarballs/elfutils-0.127.tar.gz;
     sha256 = "12n3h5r3c24a6l2wxz0w2dqq072bvgms0dzckivrwp5vdn22lpdv";
   };
+  preBuild = "sed -e 's/-Werror//' -i */Makefile ";
 }
diff --git a/pkgs/development/tools/misc/elfutils/0.131.nix b/pkgs/development/tools/misc/elfutils/0.131.nix
new file mode 100644
index 00000000000..5efe046493d
--- /dev/null
+++ b/pkgs/development/tools/misc/elfutils/0.131.nix
@@ -0,0 +1,9 @@
+args: with args;
+
+stdenv.mkDerivation {
+  name = "elfutils-"+version;
+  src = fetchurl {
+    url = http://ftp.de.debian.org/debian/pool/main/e/elfutils/elfutils_0.131.orig.tar.gz;
+    sha256 = "0vqfjpcv81m3q0gsk78qykakhz9rbfwd65i4zsi03xr2lrk9ayll";
+  };
+}
diff --git a/pkgs/development/tools/misc/gdb/default.nix b/pkgs/development/tools/misc/gdb/default.nix
index e914391ea2f..c9a47a953ef 100644
--- a/pkgs/development/tools/misc/gdb/default.nix
+++ b/pkgs/development/tools/misc/gdb/default.nix
@@ -1,10 +1,10 @@
-{stdenv, fetchurl, ncurses}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "gdb-6.6";
+stdenv.mkDerivation rec {
+  name = "gdb-6.7.1";
   src = fetchurl {
-    url = http://ftp.gnu.org/gnu/gdb/gdb-6.6.tar.bz2;
-    md5 = "a4df41d28dd514d64e8ccbfe125fd9a6";
+    url = "mirror://gnu/gdb/${name}.tar.bz2";
+	sha256 = "0qig8j8hcqpqfhnnp685rzgj8v88bw2fc5igvbiiqkqg88wfr37r";
   };
   buildInputs = [ncurses];
 }
diff --git a/pkgs/development/tools/misc/hasktags/default.nix b/pkgs/development/tools/misc/hasktags/default.nix
new file mode 100644
index 00000000000..613d028948f
--- /dev/null
+++ b/pkgs/development/tools/misc/hasktags/default.nix
@@ -0,0 +1,24 @@
+args:
+args.stdenv.mkDerivation {
+  name = "hasktags-modified";
+
+  src = args.fetchurl {
+    url = http://mawercer.de/hasktags.hs;
+    sha256 = "112k97g6mgvwa0a9zrq840mqxxw55cn422h1c134xb0fl29llig7";
+  };
+
+  buildInputs =(with args; [ghc]);
+
+  phases = "buildPhase";
+
+  # calling it hasktags-modified to not clash with the one distributed with ghc
+  buildPhase = "
+    ensureDir \$out/bin
+    ghc --make \$src -o \$out/bin/hasktags-modified
+  ";
+
+  meta = { 
+      # this can be removed again when somone comitts my changes into the distribution
+      description = "Marc's modified hasktags";
+  };
+}
diff --git a/pkgs/development/tools/misc/indent/2.2.9.nix b/pkgs/development/tools/misc/indent/2.2.9.nix
new file mode 100644
index 00000000000..5e92802beed
--- /dev/null
+++ b/pkgs/development/tools/misc/indent/2.2.9.nix
@@ -0,0 +1,29 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = ftp://ftp.gnu.org/gnu/indent/indent-2.2.9.tar.gz;
+			sha256 = "0rp4divzv5xyflm8ixpp2isa092n0nmhgmhvz56db7k3lnyqg4qb";
+		};
+
+		buildInputs = [];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+	preBuild = FullDepEntry ("
+		sed -e '/extern FILE [*]output/i#ifndef OUTPUT_DEFINED_ELSEWHERE' -i src/indent.h
+		sed -e '/extern FILE [*]output/a#endif' -i src/indent.h
+		sed -e '1i#define OUTPUT_DEFINED_ELSEWHERE 1' -i src/output.c
+	") [minInit doUnpack];
+in
+stdenv.mkDerivation rec {
+	name = "indent";
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doConfigure preBuild doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	GNU Indent - a source text formatter.
+";
+	};
+}
diff --git a/pkgs/development/tools/misc/intltool/0.36.2.nix b/pkgs/development/tools/misc/intltool/0.36.2.nix
index f42a6901dfa..884c76a800c 100644
--- a/pkgs/development/tools/misc/intltool/0.36.2.nix
+++ b/pkgs/development/tools/misc/intltool/0.36.2.nix
@@ -1,18 +1,20 @@
 args : with args;
-	with builderDefs {
+	let localDefs = builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = http://ftp.gnome.org/pub/gnome/sources/intltool/0.36/intltool-0.36.2.tar.bz2;
 		sha256 = "0cfblqz3k5s4rsw6rx9f5v3izsrmrs96293rb7bd02vijbah9gxj";
 	};
 
-		buildInputs = [perl perlXMLParser];
+		propagatedBuildInputs = [perl perlXMLParser];
 		configureFlags = [];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 stdenv.mkDerivation rec {
 	name = "intltool-0.36.2";
 	builder = writeScript (name + "-builder")
-		(textClosure [doConfigure doMakeInstall doForceShare]);
+		(textClosure localDefs [doConfigure doMakeInstall doPropagate doForceShare]);
+	inherit propagatedBuildInputs;
 	meta = {
 		description = "
 	Internalization tool for XML.
diff --git a/pkgs/development/tools/misc/intltool/default.nix b/pkgs/development/tools/misc/intltool/default.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/development/tools/misc/intltool/default.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args
diff --git a/pkgs/development/tools/misc/libtool/default.nix b/pkgs/development/tools/misc/libtool/default.nix
index 226552b3943..b955ccbc3c8 100644
--- a/pkgs/development/tools/misc/libtool/default.nix
+++ b/pkgs/development/tools/misc/libtool/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, m4, perl}:
 
-stdenv.mkDerivation {
-  name = "libtool-1.5.22";
+stdenv.mkDerivation rec {
+  name = "libtool-1.5.26";
   src = fetchurl {
-    url = http://ftp.gnu.org/gnu/libtool/libtool-1.5.22.tar.gz;
-    md5 = "8e0ac9797b62ba4dcc8a2fb7936412b0";
+    url = "mirror://gnu/libtool/" + name + ".tar.gz";
+    sha256 = "029ggq5kri1gjn6nfqmgw4w920gyfzscjjxbsxxidal5zqsawd8w";
   };
   buildInputs = [m4 perl];
 }
diff --git a/pkgs/development/tools/misc/ltrace/default.nix b/pkgs/development/tools/misc/ltrace/0.5-3deb.nix
index 23b44bf3b5b..bff3e6a8fbc 100644
--- a/pkgs/development/tools/misc/ltrace/default.nix
+++ b/pkgs/development/tools/misc/ltrace/0.5-3deb.nix
@@ -1,5 +1,10 @@
-args : with args;
-	with builderDefs {
+args : with args;	let 
+        patch = fetchurl {
+          url = ftp://ftp.debian.org/debian/pool/main/l/ltrace/ltrace_0.5-3.diff.gz;
+          sha256 = "0rin25si7117wld5bc7vf3d73c5k9ph3zach7cbg9h9vvz376c26";
+        };
+	localDefs = with (builderDefs {src="";} null);
+	 builderDefs {
 		src = /* put a fetchurl here */
 	fetchurl {
 		url = ftp://ftp.debian.org/debian/pool/main/l/ltrace/ltrace_0.5.orig.tar.gz;
@@ -11,7 +16,12 @@ args : with args;
 		goSrcDir = "
 			cd ltrace-*;
 		";
+		preBuild = FullDepEntry (''
+		  gunzip < ${patch} | patch -Np1
+		  sed -e s@-Werror@@ -i Makefile.in
+		'')["minInit" "doUnpack"];
 	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
 let
 	preConfigure = FullDepEntry ("
 		sed -e 's@-o root -g root@@' -i Makefile.in;
@@ -20,7 +30,7 @@ in
 stdenv.mkDerivation rec {
 	name = "ltrace-0.5";
 	builder = writeScript (name + "-builder")
-		(textClosure [preConfigure doConfigure doMakeInstall doForceShare]);
+		(textClosure localDefs [preBuild preConfigure doConfigure doMakeInstall doForceShare]);
 	meta = {
 		description = "
 	Library call tracer.
diff --git a/pkgs/development/tools/misc/pkgconfig/default.nix b/pkgs/development/tools/misc/pkgconfig/default.nix
index 481d2174ebc..41a61f600e0 100644
--- a/pkgs/development/tools/misc/pkgconfig/default.nix
+++ b/pkgs/development/tools/misc/pkgconfig/default.nix
@@ -5,14 +5,9 @@ stdenv.mkDerivation {
   setupHook = ./setup-hook.sh;
   src = fetchurl {
     url = http://pkgconfig.freedesktop.org/releases/pkg-config-0.22.tar.gz;
-	sha256 = "1rpb5wygmp0f8nal7y3ga4556i7hkjdslv3wdq04fj30gns621vy";
+    sha256 = "1rpb5wygmp0f8nal7y3ga4556i7hkjdslv3wdq04fj30gns621vy";
   };
 
-  postInstall = "
-  ensureDir \$out/nix-support
-  cp \$setupHook \$out/nix-support/setup-hook
-  ";
-
   patches = [
     # Process Requires.private properly, see
     # http://bugs.freedesktop.org/show_bug.cgi?id=4738.
@@ -23,3 +18,4 @@ stdenv.mkDerivation {
     })
   ];
 }
+
diff --git a/pkgs/development/tools/misc/pkgconfig/setup-hook.sh b/pkgs/development/tools/misc/pkgconfig/setup-hook.sh
index f13a44eb999..c137fb0e96c 100644
--- a/pkgs/development/tools/misc/pkgconfig/setup-hook.sh
+++ b/pkgs/development/tools/misc/pkgconfig/setup-hook.sh
@@ -1,5 +1,5 @@
 addPkgConfigPath () {
-	addToSearchPath PKG_CONFIG_PATH /lib/pkgconfig "" $1
+    addToSearchPath PKG_CONFIG_PATH /lib/pkgconfig "" $1
 }
 
 envHooks=(${envHooks[@]} addPkgConfigPath)
diff --git a/pkgs/development/tools/misc/strace/default.nix b/pkgs/development/tools/misc/strace/default.nix
index b94a313d23d..5091a715167 100644
--- a/pkgs/development/tools/misc/strace/default.nix
+++ b/pkgs/development/tools/misc/strace/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "strace-4.5.15";
+  name = "strace-4.5.16";
 
   src = fetchurl {
-    url = mirror://sourceforge/strace/strace-4.5.15.tar.gz;
-    sha256 = "07n62yv53p2hsb59srfaxb0kk8b6p6iq77drmf65pq8jpa50s9ip";
+    url = mirror://sourceforge/strace/strace-4.5.16.tar.bz2;
+    sha256 = "15ks9i1gv7mbyiwnzbjls2xy0pyv5x4j9a5ca2x0258fq8lxwdhp";
   };
 }
diff --git a/pkgs/development/tools/misc/swig/default.nix b/pkgs/development/tools/misc/swig/default.nix
index e8e77924b8c..72dd19b7af8 100644
--- a/pkgs/development/tools/misc/swig/default.nix
+++ b/pkgs/development/tools/misc/swig/default.nix
@@ -6,12 +6,12 @@ assert pythonSupport -> python != null;
 assert javaSupport -> jdk != null;
 
 stdenv.mkDerivation {
-  name = "swig-1.3.31";
+  name = "swig-1.3.33";
 
   builder = ./builder.sh;
   src = fetchurl {
-    url = mirror://sourceforge/swig/swig-1.3.31.tar.gz;
-    sha256 = "01fqf6xvhaqh76kh13bknn5j7axpm1pdnjpzwxsa9d1lbq4n7bf2";
+    url = mirror://sourceforge/swig/swig-1.3.33.tar.gz;
+    sha256 = "02rz31i642sbsngny7k98d9hxlkcb9snvbzlnz3sh0qiyr3ciggv";
   };
 
   inherit perlSupport pythonSupport javaSupport;
diff --git a/pkgs/development/tools/misc/uisp/default.nix b/pkgs/development/tools/misc/uisp/default.nix
index c6810939dd4..694dc940d92 100644
--- a/pkgs/development/tools/misc/uisp/default.nix
+++ b/pkgs/development/tools/misc/uisp/default.nix
@@ -1,16 +1,14 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "uisp-20050207";
 
   configureFlags="--disable-dependency-tracking";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://mirror.switch.ch/mirror/gentoo/distfiles/uisp-20050207.tar.gz;
     sha256 = "1bncxp5yxh9r1yrp04vvhfiva8livi1pwic7v8xj99q09zrwahvw";
   };
 
-  #buildInputs =(with args; []);
-
   meta = {
     description = "tool for AVR microcontrollers which can interface to many hardware in-system programmers";
     license = "GPL-2";
diff --git a/pkgs/development/tools/misc/valgrind/default.nix b/pkgs/development/tools/misc/valgrind/default.nix
index 5fb0e85dda1..7f46228304b 100644
--- a/pkgs/development/tools/misc/valgrind/default.nix
+++ b/pkgs/development/tools/misc/valgrind/default.nix
@@ -1,16 +1,17 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "valgrind-3.2.3";
+  name = "valgrind-3.3.0";
   src = fetchurl {
-    url = http://valgrind.org/downloads/valgrind-3.2.3.tar.bz2;
-    sha256 = "0hf48y13mm1c1zg59bvkbr0lzcwng5mb33lgiv3d0gzl4w2r5jhv";
+    url = http://valgrind.org/downloads/valgrind-3.3.0.tar.bz2;
+    sha256 = "0yllx5a2f5bx18gqz74aikr27zxwpblswn65lqvm9rbzswlq5w2s";
   };
 
   configureFlags =
     if stdenv.system == "x86_64-linux" then ["--enable-only64bit"] else [];
 
   meta = {
+    homepage = http://www.valgrind.org/;
     description = "Award-winning suite of tools for debugging and profiling Linux programs";
   };
 }
diff --git a/pkgs/development/tools/parsing/alex/default.nix b/pkgs/development/tools/parsing/alex/default.nix
new file mode 100644
index 00000000000..273a25753e8
--- /dev/null
+++ b/pkgs/development/tools/parsing/alex/default.nix
@@ -0,0 +1,12 @@
+{cabal, perl}:
+
+cabal.mkDerivation (self : {
+  pname = "alex";
+  version = "2.2";
+  name = self.fname;
+  sha256 = "e958d4fc6cfdb1d351dc39a45ea882f23b1b1773a736d43814a52d4939a41ffe";
+  extraBuildInputs = [perl];
+  meta = {
+    description = "A lexical analyser generator for Haskell";
+  };
+})
diff --git a/pkgs/development/tools/parsing/bison/bison-1.875.nix b/pkgs/development/tools/parsing/bison/bison-1.875.nix
index 92aeafb335a..6a2ae1c794d 100644
--- a/pkgs/development/tools/parsing/bison/bison-1.875.nix
+++ b/pkgs/development/tools/parsing/bison/bison-1.875.nix
@@ -5,7 +5,9 @@ assert m4 != null;
 stdenv.mkDerivation {
   name = "bison-1.875";
   src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/bison-1.875.tar.bz2;
+    urls = [ http://nix.cs.uu.nl/dist/tarballs/bison-1.875.tar.bz2 
+	ftp://ftp.gnu.org/pub/gnu/bison/bison-1.875.tar.bz2 
+      ];
     md5 = "b7f8027b249ebd4dd0cc948943a71af0";
   };
   buildInputs = [m4];
diff --git a/pkgs/development/tools/parsing/flex-iputils/builder.sh b/pkgs/development/tools/parsing/flex-iputils/builder.sh
deleted file mode 100644
index 946301946ba..00000000000
--- a/pkgs/development/tools/parsing/flex-iputils/builder.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-source $stdenv/setup
-
-installPhase() {
-   make install
-   cd $out/bin; ln -s flex lex
-   cd $out/lib; ln -s libfl.a libl.a
-}
-
-installPhase=installPhase
-genericBuild
diff --git a/pkgs/development/tools/parsing/flex-iputils/default.nix b/pkgs/development/tools/parsing/flex-iputils/default.nix
deleted file mode 100644
index c680f0f5c49..00000000000
--- a/pkgs/development/tools/parsing/flex-iputils/default.nix
+++ /dev/null
@@ -1,13 +0,0 @@
-{stdenv, fetchurl, yacc}:
-
-assert yacc != null;
-
-stdenv.mkDerivation {
-  name = "flex-2.5.4a";
-  builder = ./builder.sh;
-  src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/flex-2.5.4a.tar.gz;
-    md5 = "bd8753d0b22e1f4ec87a553a73021adf";
-  };
-  buildInputs = [yacc];
-}
diff --git a/pkgs/development/tools/parsing/flex-iputils/flex-new.nix b/pkgs/development/tools/parsing/flex-iputils/flex-new.nix
deleted file mode 100644
index 802f77a9ad6..00000000000
--- a/pkgs/development/tools/parsing/flex-iputils/flex-new.nix
+++ /dev/null
@@ -1,16 +0,0 @@
-# !!! this should be moved to default.nix eventually (but I delay
-# doing that since it would cause a rebuild of lots of stuff).
-
-{stdenv, fetchurl, yacc, m4}:
-
-assert yacc != null && m4 != null;
-
-stdenv.mkDerivation {
-  name = "flex-2.5.31";
-  src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/flex-2.5.31.tar.bz2;
-    md5 = "363dcc4afc917dc51306eb9d3de0152f";
-  };
-  buildInputs = [yacc];
-  propagatedBuildInputs = [m4];
-}
diff --git a/pkgs/development/tools/parsing/flex/flex-2.5.34.nix b/pkgs/development/tools/parsing/flex/flex-2.5.34.nix
new file mode 100644
index 00000000000..d56cf0c88a2
--- /dev/null
+++ b/pkgs/development/tools/parsing/flex/flex-2.5.34.nix
@@ -0,0 +1,19 @@
+# This should be moved to default.nix eventually (?)
+
+{stdenv, fetchurl, yacc, m4}:
+
+assert yacc != null && m4 != null;
+
+stdenv.mkDerivation {
+  name = "flex-2.5.34";
+  src = fetchurl {
+    url = mirror://sourceforge/flex/flex-2.5.34.tar.bz2;
+    sha256 = "1c8e64f32508841b0441ddfb139c4cfd25fee3728cadb63f5f351c6eb9b224a6";
+  };
+  buildInputs = [yacc];
+  propagatedBuildInputs = [m4];
+
+  meta = {
+    description = "A fast lexical analyser generator";
+  };
+}
diff --git a/pkgs/development/tools/parsing/flex/flex-2.5.4a.nix b/pkgs/development/tools/parsing/flex/flex-2.5.4a.nix
index 2d146eeca25..13bb6834979 100644
--- a/pkgs/development/tools/parsing/flex/flex-2.5.4a.nix
+++ b/pkgs/development/tools/parsing/flex/flex-2.5.4a.nix
@@ -5,7 +5,7 @@ assert yacc != null;
 stdenv.mkDerivation {
   name = "flex-2.5.4a";
   src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/flex-2.5.4a.tar.gz;
+    url = mirror://sourceforge/flex/flex-2.5.4a.tar.gz;
     md5 = "bd8753d0b22e1f4ec87a553a73021adf";
   };
   buildInputs = [yacc];
diff --git a/pkgs/development/tools/parsing/happy/happy-1.17.nix b/pkgs/development/tools/parsing/happy/happy-1.17.nix
new file mode 100644
index 00000000000..b7fa22ccb80
--- /dev/null
+++ b/pkgs/development/tools/parsing/happy/happy-1.17.nix
@@ -0,0 +1,12 @@
+{cabal, perl}:
+
+cabal.mkDerivation (self : {
+
+  # requires cabal-1.2 (and therefore, in Nix, currently ghc-6.8)
+
+  pname = "happy";
+  version = "1.17";
+  name = self.fname;
+  sha256 = "dca4e47d17e5d538335496236b3d2c3cbff644cf7380c987a4714e7784c70a2b";
+  extraBuildInputs = [perl];
+})
diff --git a/pkgs/development/tools/parsing/sdf/sdf2-bundle-2.4.nix b/pkgs/development/tools/parsing/sdf/sdf2-bundle-2.4.nix
new file mode 100644
index 00000000000..7d62d743070
--- /dev/null
+++ b/pkgs/development/tools/parsing/sdf/sdf2-bundle-2.4.nix
@@ -0,0 +1,12 @@
+{stdenv, fetchurl, aterm, getopt, pkgconfig}:
+
+stdenv.mkDerivation {
+  name = "sdf2-bundle-2.4";
+  src = fetchurl {
+    url = http://buildfarm.st.ewi.tudelft.nl/releases/meta-environment/sdf2-bundle-2.4pre212034-2nspl1xc/sdf2-bundle-2.4.tar.gz;
+    md5 = "00107bef17d3fb8486575f8974fb384b";
+  };
+
+  buildInputs = [aterm pkgconfig];
+  propagatedBuildInputs = [getopt];
+}
diff --git a/pkgs/development/tools/selenium/remote-control/default.nix b/pkgs/development/tools/selenium/remote-control/default.nix
new file mode 100644
index 00000000000..4c55805e5c8
--- /dev/null
+++ b/pkgs/development/tools/selenium/remote-control/default.nix
@@ -0,0 +1,23 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "selenium-rc-0.8.3-binary";
+
+  src = fetchurl {
+    url = http://release.openqa.org/cgi-bin/selenium-remote-control-redirect.zip;
+    sha256 = "694b46a8440011bcedc4fdc6d01fd91c8b4b4b62b7c6629ace4e745ef47f583e";
+  };
+
+  phases = "installPhase";
+  installPhase = "
+  ensureDir \$out/lib
+  cp selenium-server-*/*.jar \$out/lib
+  ";
+
+  buildInputs = [unzip];
+
+  meta = { 
+      description = "test tool for web applications";
+      homepage = http://www.openqa.org/selenium-c;
+      license = "";
+  };
+}
diff --git a/pkgs/games/construo/0.2.2.nix b/pkgs/games/construo/0.2.2.nix
new file mode 100644
index 00000000000..555d2f4b30b
--- /dev/null
+++ b/pkgs/games/construo/0.2.2.nix
@@ -0,0 +1,30 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://savannah.nongnu.org/download/construo/construo-0.2.2.tar.gz;
+			sha256 = "0c661rjasax4ykw77dgqj39jhb4qi48m0bhhdy42vd5a4rfdrcck";
+		};
+
+		buildInputs = [libX11 zlib xproto]
+		++ (if args ? mesa then [mesa freeglut] else [])
+		;
+		configureFlags = [""];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+preConfigure = FullDepEntry ("
+  sed -e 's/math[.]h/cmath/' -i vector.cxx
+  sed -e 's/games/bin/' -i Makefile.in
+") [doUnpack minInit];
+in
+stdenv.mkDerivation rec {
+	name = "construo-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [preConfigure doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	Construo masses and springs simulation.
+";
+	};
+}
diff --git a/pkgs/games/fsg/alt-builder.nix b/pkgs/games/fsg/alt-builder.nix
index 8efd788789b..4401bf8451a 100644
--- a/pkgs/games/fsg/alt-builder.nix
+++ b/pkgs/games/fsg/alt-builder.nix
@@ -1,13 +1,13 @@
 args: with args; 
-	with (builderDefs 
-	{ 
+	let localDefs = builderDefs {
   		buildInputs =[(wxGTK null)];
 		  src = 
 			fetchurl {
 				url = http://www.piettes.com/fallingsandgame/fsg-src-4.4.tar.gz;
 				sha256 = "1756y01rkvd3f1pkj88jqh83fqcfl2fy0c48mcq53pjzln9ycv8c";
 			};
-	} null);
+	} null;
+	in with localDefs;
 let 
 	preBuild = FullDepEntry "
 		sed -e '
@@ -25,7 +25,7 @@ in
 stdenv.mkDerivation {
   name = "fsg-4.4";
 	builder = writeScript "fsg-4.4-builder"
-		(textClosure [doUnpack addInputs preBuild doMake installPhase doForceShare]);
+		(textClosure localDefs [doUnpack addInputs preBuild doMake installPhase doForceShare]);
 
   meta = {
     description = "
diff --git a/pkgs/games/orbit/1.01.nix b/pkgs/games/orbit/1.01.nix
new file mode 100644
index 00000000000..ba824e83f1c
--- /dev/null
+++ b/pkgs/games/orbit/1.01.nix
@@ -0,0 +1,43 @@
+args : with args; with builderDefs {src="";} null;
+	let localDefs = builderDefs rec {
+		src = /* put a fetchurl here */
+		fetchurl {
+			sha256 = "1kx69f9jqnfzwjh47cl1df8p8hn3bnp6bznxnb6c4wx32ijn5gri";
+			url = http://ftp.de.debian.org/debian/pool/main/s/space-orbit/space-orbit_1.01.orig.tar.gz;
+		};
+
+		buildInputs = [mesa libXi libXt libXext libX11 libXmu freeglut esound];
+		configureFlags = [];
+		debianPatch = 
+		fetchurl {
+			url = http://ftp.de.debian.org/debian/pool/main/s/space-orbit/space-orbit_1.01-9.diff.gz;
+			sha256 = "1v3s97day6fhv08l2rn81waiprhi1lfyjjsj55axfh6n6zqfn1w2";
+		};
+		customBuild = FullDepEntry (''
+			gunzip < ${debianPatch} | patch -Np1
+                        cd src
+			sed -e 's@/usr/share/games/orbit/@'$out'/dump/@g' -i *.c
+                        sed -e '/DIR=/d' -i Makefile 
+                        make 
+                        ensureDir $out/bin
+                        cp -r .. $out/dump
+                        cat >$out/bin/space-orbit <<EOF
+#! /bin/sh
+$out/dump/orbit "\$@"
+EOF
+                        chmod a+x $out/bin/space-orbit
+		'') ["minInit" "doUnpack" "defEnsureDir" "addInputs"];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "space-orbit-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs 
+			[ customBuild doForceShare doPropagate]);
+	meta = {
+		description = "
+		Orbit space flight simulator.
+";
+	};
+}
+
diff --git a/pkgs/games/scummvm/default.nix b/pkgs/games/scummvm/default.nix
index 610556a2635..2f81aaa474d 100644
--- a/pkgs/games/scummvm/default.nix
+++ b/pkgs/games/scummvm/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl, SDL, zlib, mpeg2dec}:
 
 stdenv.mkDerivation {
-  name = "scummvm-0.10.0";
+  name = "scummvm-0.11.0";
   
   src = fetchurl {
-    url = mirror://sourceforge/scummvm/scummvm-0.10.0.tar.bz2;
-    sha256 = "09ii4vbs4nygc0x4n1l9dkfiywj5qwxv9j81pbrf9r6d6y4wdlf9";
+    url = mirror://sourceforge/scummvm/scummvm-0.11.0.tar.bz2;
+    sha256 = "106vcknkr07m17rxypavlz3cjyd862bwq1qw1arakcvhhi90mbfl";
   };
   
   buildInputs = [SDL zlib mpeg2dec];
diff --git a/pkgs/games/thePenguinMachine/default.nix b/pkgs/games/thePenguinMachine/default.nix
index 89f675e083d..4ce42934b5a 100644
--- a/pkgs/games/thePenguinMachine/default.nix
+++ b/pkgs/games/thePenguinMachine/default.nix
@@ -1,20 +1,19 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "thePenguinMachine";
 
-  src = args.
-	fetchurl {
+  src = fetchurl {
 		url = http://www.migniot.com/matrix/projects/thepenguinmachine/ThePenguinMachine.tar.gz;
 		sha256 = "09ljks8vj75g00h3azc83yllbfsrxwmv1c9g32gylcmsshik0dqv";
 	};
 
-  buildInputs =(with args; [python24 pil pygame SDL]);
+  buildInputs = [python24 pil pygame SDL];
 
-  configurePhase = (with args; "
+  configurePhase = "
 		sed -e \"/includes = /aincludes.append('${SDL}/include/SDL')\" -i setup.py;
 		sed -e \"/includes = /aincludes.append('${pygame}/include/python2.4')\" -i setup.py;
 		cat setup.py;
-	");
+	";
   buildPhase = "
 		python setup.py build;
 		python setup.py build_clib;
@@ -22,13 +21,13 @@ args.stdenv.mkDerivation {
 		python setup.py build_py;
 		python setup.py build_scripts;
 		";
-  installPhase = (with args ; "
+  installPhase = "
 		python setup.py install --prefix=\${out}
 		cp -r . /tmp/tpm-build
 		echo 'export PYTHONPATH=$PYTHONPATH:${pygame}/lib/python2.4/site-packages:${pil}/lib/python2.4/site-packages/PIL
 		python ThePenguinMachine.py' >/tmp/tpm-build/tpm.sh; 
 		chmod a+rx /tmp/tpm-build/tpm.sh
-		");
+		";
 
   meta = {
     description = "
diff --git a/pkgs/games/wesnoth/default.nix b/pkgs/games/wesnoth/default.nix
new file mode 100644
index 00000000000..2e132dd8889
--- /dev/null
+++ b/pkgs/games/wesnoth/default.nix
@@ -0,0 +1,22 @@
+args: with args;
+stdenv.mkDerivation (rec {
+  pname = "wesnoth";
+  version = "1.3.18";
+
+  name = "${pname}-${version}";
+
+  src = fetchurl {
+    url = "http://surfnet.dl.sourceforge.net/sourceforge/${pname}/${name}.tar.bz2";
+    sha256 = "ab2ed2cbe1daa134c453927bf0ec5d3a36f3319063b6f18c35819871f386da75";
+  };
+
+  buildInputs = [SDL SDL_image SDL_mixer SDL_net gettext zlib boost freetype];
+
+  configureFlags = "--with-preferences-dir=.${name} --program-suffix=-${version} --with-datadir-name=${name} --with-boost=${boost}/include --disable-python";
+
+  meta = {
+    description = "
+      The Battle for Wesnoth  is a free, turn-based strategy game with a fantasy theme.
+";
+  };
+})
diff --git a/pkgs/lib/annotatedDerivations.nix b/pkgs/lib/annotatedDerivations.nix
new file mode 100644
index 00000000000..eca97747cd8
--- /dev/null
+++ b/pkgs/lib/annotatedDerivations.nix
@@ -0,0 +1,56 @@
+{ lib } : with lib; with builtins; rec {
+  /*
+  # traversal proposal (very unstable now )
+  # goal: create tags easily (and install source files along without recompiling)
+
+  rec {
+    # encouraged: using it you can filter based on names later on? Do we ned it?
+    name = 
+
+    # required: the annotated derivation (this attr is used to identify a
+    # annotated derivation)
+    aDeriv =
+
+    # required: extra list of annotated dependencies, so we can traverse the tree
+    aDeps = <annotated deps>
+
+    # your annotation derivations 
+  };
+  */
+
+  isAnnotated = a : (a ? aDeriv); # this function serves documentation purposes 
+
+  delAnnotation = a :
+    if ((__isAttrs a) && (isAnnotated a)) then  a.aDeriv
+    else a; # most probalby a derivation without annotations.
+
+  # returns buildInputs and propagatedBuildInputs from given set after removing annotations
+  delAnnotationsFromInputs = attrs :
+    subsetmap (map delAnnotation) attrs [ "buildInputs" "propagatedBuildInputs" ];
+
+  /* so an annotated drivation function might look like this
+  args: with args;
+    let aDeps = filterDeps args;
+        deps = delAnnotation aDeps;
+    in rec {
+      name = "my-package-0.2";
+      inherit aDeps;
+
+      aDeriv = stdenv.mkDerivation {
+        inherit name;
+        buildInputs = deps;
+      };
+    };
+
+  */
+
+  filterAnnotated = lib.filter isAnnotated;
+
+  # stops when depthCounter = 0 
+  traverseByDepthCounter = depthCounter : aAttrs :
+    if (depthCounter == 0) then []
+    else [ aAttrs ] ++ map (traverseByDepthCounter (__sub depthCounter 1) ) (filterAnnotated aAttrs.aDeps);
+
+  # get all deps recursively
+  uniqAnnotatedDeps = aAttrs : uniqList { inputList = traverseByDepthCounter 10 aAttrs; };
+}
diff --git a/pkgs/lib/default-unstable.nix b/pkgs/lib/default-unstable.nix
deleted file mode 100644
index 33fb68f5857..00000000000
--- a/pkgs/lib/default-unstable.nix
+++ /dev/null
@@ -1,429 +0,0 @@
-# Utility functions.
-
-let
-
-  inherit (builtins)
-    head tail isList stringLength substring lessThan sub
-    listToAttrs attrNames hasAttr;
-
-in
-
-rec {
-
-  # "Fold" a binary function `op' between successive elements of
-  # `list' with `nul' as the starting value, i.e., `fold op nul [x_1
-  # x_2 ... x_n] == op x_1 (op x_2 ... (op x_n nul))'.  (This is
-  # Haskell's foldr).
-  fold = op: nul: list:
-    if list == []
-    then nul
-    else op (head list) (fold op nul (tail list));
-    
-  # Concatenate a list of lists.
-  concatLists =
-    fold (x: y: x ++ y) [];
-
-
-  # Concatenate a list of strings.
-  concatStrings =
-    fold (x: y: x + y) "";
-
-
-  # Place an element between each element of a list, e.g.,
-  # `intersperse "," ["a" "b" "c"]' returns ["a" "," "b" "," "c"].
-  intersperse = separator: list:
-    if list == [] || tail list == []
-    then list
-    else [(head list) separator]
-         ++ (intersperse separator (tail list));
-
-
-  concatStringsSep = separator: list:
-    concatStrings (intersperse separator list);
-
-
-  # Flatten the argument into a single list; that is, nested lists are
-  # spliced into the top-level lists.  E.g., `flatten [1 [2 [3] 4] 5]
-  # == [1 2 3 4 5]' and `flatten 1 == [1]'.
-  flatten = x:
-    if isList x
-    then fold (x: y: (flatten x) ++ y) [] x
-    else [x];
-
-
-  # Return an attribute from nested attribute sets.  For instance ["x"
-  # "y"] applied to some set e returns e.x.y, if it exists.  The
-  # default value is returned otherwise.
-  # comment: I'd rename this to getAttrRec or something like that .. (has the same name as builtin.getAttr) - Marc Weber
-  getAttr = attrPath: default: e:
-    let {
-      attr = head attrPath;
-      body =
-        if attrPath == [] then e
-        else if builtins ? hasAttr && builtins.hasAttr attr e
-        then getAttr (tail attrPath) default (builtins.getAttr attr e)
-        else default;
-    };
-
-
-  # Filter a list using a predicate; that is, return a list containing
-  # every element from `list' for which `pred' returns true.
-  filter = pred: list:
-    fold (x: y: if pred x then [x] ++ y else y) [] list;
-
-
-  # Return true if `list' has an element `x':
-  elem = x: list: fold (a: bs: x == a || bs) false list;
-
-
-  # Find the sole element in the list matching the specified
-  # predicate, or returns the default value.
-  findSingle = pred: default: list:
-    let found = filter pred list;
-    in if found == [] then default
-       else if tail found != [] then
-         abort "Multiple elements match predicate in findSingle."
-       else head found;
-
-
-  # Return true if each element of a list is equal, false otherwise.
-  eqLists = xs: ys:
-    if xs == [] && ys == [] then true
-    else if xs == [] || ys == [] then false
-    else head xs == head ys && eqLists (tail xs) (tail ys);
-
-
-  # Determine whether a filename ends in the given suffix.
-  hasSuffix = ext: fileName:
-    let lenFileName = stringLength fileName;
-        lenExt = stringLength ext;
-    in !(lessThan lenFileName lenExt) &&
-       substring (sub lenFileName lenExt) lenFileName fileName == ext;
-
-       
-  # Bring in a path as a source, filtering out all Subversion and CVS
-  # directories, as well as backup files (*~).
-  cleanSource =
-    let filter = name: type: let baseName = baseNameOf (toString name); in ! (
-      # Filter out Subversion and CVS directories.
-      (type == "directory" && (name == ".svn" || name == "CVS")) ||
-      # Filter out backup files.
-      (hasSuffix "~" name)
-    );
-    in src: builtins.filterSource filter src;
-
-
-  # Return a singleton list or an empty list, depending on a boolean
-  # value.  Useful when building lists with optional elements
-  # (e.g. `++ optional (system == "i686-linux") flashplayer').
-  optional = cond: elem: if cond then [elem] else [];
-
-    
-  # Return a list of integers from `first' up to and including `last'.
-  range = first: last:
-    if builtins.lessThan last first
-    then []
-    else [first] ++ range (builtins.add first 1) last;
-
-  # Return true only if there is an attribute and it is true.
-  checkFlag = attrSet: name:
-	if (name == "true") then true else
-	if (name == "false") then false else
-	if (isInList (getAttr ["flags"] [] attrSet) name) then true else
-	getAttr [name] false attrSet ;
-
-  logicalOR = x: y: x || y;
-  logicalAND = x: y: x && y;
-
-  # Input : attrSet, [ [name default] ... ], name
-  # Output : its value or default.
-  getValue = attrSet: argList: name:
-  ( getAttr [name] (if checkFlag attrSet name then true else
-	if argList == [] then null else
-	let x = builtins.head argList; in
-		if (head x) == name then 
-			(head (tail x))
-		else (getValue attrSet 
-			(tail argList) name)) attrSet );
-
-  # Input : attrSet, [[name default] ...], [ [flagname reqs..] ... ]
-  # Output : are reqs satisfied? It's asserted.
-  checkReqs = attrSet : argList : condList :
-  (
-    fold logicalAND true 
-      (map (x: let name = (head x) ; in
-	
-	((checkFlag attrSet name) -> 
-	(fold logicalAND true
-	(map (y: let val=(getValue attrSet argList y); in
-		(val!=null) && (val!=false)) 
-	(tail x))))) condList)) ;
-	
-   
-  isInList = list: x:
-	if (list == []) then false else
-	if (x == (head list)) then true else
-	isInList (tail list) x;
-  
-  uniqList = {inputList, outputList ? []}:
-	if (inputList == []) then outputList else
-	let x=head inputList; 
-	newOutputList = outputList ++
-	 (if (isInList outputList x) then [] else [x]);
-	in uniqList {outputList=newOutputList; 
-		inputList = (tail inputList);};
-
-  condConcat = name: list: checker:
-	if list == [] then name else
-	if checker (head list) then 
-		condConcat 
-			(name + (head (tail list))) 
-			(tail (tail list)) 
-			checker
-	else condConcat
-		name (tail (tail list)) checker;
-
-  # calls a function (f attr value ) for each record item. returns a list
-  mapRecordFlatten = f : r : map (attr: f attr (builtins.getAttr attr r) ) (attrNames r);
-
-  # to be used with listToAttrs (_a_ttribute _v_alue)
-  av = name : value : { inherit name value; };
-  # attribute set containing one attribute
-  avs = attr : value : listToAttrs [ (av attr value) ];
-  # adds / replaces an attribute of an attribute set
-  setAttr = set : attr : v : set // (avs attr v);
-
-  id = x : x;
-  # true if all/ at least one element(s) satisfy f
-  all = f : l : fold logicalAND true (map f l);
-  any = f : l : fold logicalOR false (map f l);
-
-  # iterates over a list of attributes collecting the attribute attr if it exists
-  catAttrs = attr : l : fold ( s : l : if (hasAttr attr s) then [(builtins.getAttr attr s)] ++ l else l) [] l;
-
-  mergeAttrs = fold ( x : y : x // y) {};
-
-  # returns atribute values as a list 
-  flattenAttrs = set : map ( attr : builtins.getAttr attr set) (attrNames set);
-  mapIf = cond : f :  fold ( x : l : if (cond x) then [(f x)] ++ l else l) [];
-
-# Marc 2nd proposal: (not everything has been tested in detail yet..)
-           
-  # calls chooseOptionsByFlags2 with some preprocessing
-  # chooseOptionsByFlags2 returns an attribute set meant to be used to create new derivaitons.
-  # see mkDerivationByConfiguration in all-packages.nix and the examples given below.
-  # You can just copy paste them into all-packages.nix to test them..
-
-  chooseOptionsByFlags = { flagConfig, args, optionals ? [], defaults ? [],
-                           collectExtraPhaseActions ? [] } :
-    let passedOptionals = filter ( x : hasAttr x args ) optionals; # these are in optionals and in args
-        # we simply merge in <optional_name> = { buildInputs = <arg.<optional_name>; pass = <arg.optional_name>; }
-        flagConfigWithOptionals = flagConfig // ( listToAttrs
-          (map ( o : av o ( { buildInputs = o; pass = avs o (builtins.getAttr o args); }
-                            // getAttr [o] {} flagConfig )
-               )
-               passedOptionals ) );
-
-    in chooseOptionsByFlags2 flagConfigWithOptionals collectExtraPhaseActions args 
-       ( (getAttr ["flags"] defaults args) ++ passedOptionals);
-
-  chooseOptionsByFlags2 = flagConfig : collectExtraPhaseActions : args : flags :
-    let   
-        # helper function
-        collectFlags = # state : flags :
-              fold ( flag : s : (
-                     if (hasAttr flag s.result) then s # this state has already been visited
-                     else if (! hasAttr flag flagConfig) then throw "unkown flag `${flag}' specified"
-                           else let fDesc = (builtins.getAttr flag flagConfig);
-                                    implied = flatten ( getAttr ["implies"] [] fDesc );
-                                    blocked = flatten ( getAttr ["blocks"] [] fDesc ); 
-                                    # add this flag
-                                    s2 =  s // { result = ( setAttr s.result flag (builtins.getAttr flag flagConfig) );
-                                                 blockedFlagsBy = s.blockedFlagsBy 
-                                                   // listToAttrs (map (b: av b flag ) blocked); };
-                                    # add implied flags
-                                in collectFlags s2 implied
-                   ));
-
-        # chosen contains flagConfig but only having those attributes elected by flags 
-        # (or by implies attributes of elected attributes)
-        options = let stateOpts = collectFlags { blockedFlagsBy = {}; result = {}; } 
-                                               (flags ++ ( if (hasAttr "mandatory" flagConfig) then ["mandatory"] else [] ));
-                      # these options have not been chosen (neither by flags nor by implies)
-                      unsetOptions = filter ( x : (! hasAttr x stateOpts.result) && (hasAttr ("no_"+x) flagConfig)) 
-                                            ( attrNames flagConfig );
-                      # no add the corresponding no_ attributes as well ..
-                      state = collectFlags stateOpts (map ( x : "no_" + x ) unsetOptions);
-                  in # check for blockings:
-                     assert ( all id ( map ( b: if (hasAttr b state.result) 
-                                             then throw "flag ${b} is blocked by flag ${__getAttr b state.blockedFlagsBy}"
-                                             else true ) 
-                                           (attrNames state.blockedFlagsBy) ) ); 
-                    state.result;
-        flatOptions = flattenAttrs options;
-
-        # helper functions :
-        collectAttrs = attr : catAttrs attr flatOptions;
-        optsConcatStrs = delimiter : attrs : concatStrings 
-                ( intersperse delimiter (flatten ( collectAttrs attrs ) ) );
-          
-    in assert ( all id ( mapRecordFlatten ( attr : r : if ( all id ( flatten (getAttr ["assertion"] [] r ) ) ) 
-                                              then true else throw "assertion failed flag ${attr}" )
-                                         options) );
-      ( rec {
-
-          #foldOptions = attr: f : start: fold f start (catAttrs attr flatOptions);
-
-          # compared to flags flagsSet does also contain the implied flags.. This makes it easy to write assertions. ( assert args.
-          inherit options flatOptions collectAttrs optsConcatStrs;
-
-          buildInputs = map ( attr: if (! hasAttr attr args) then throw "argument ${attr} is missing!" else (builtins.getAttr attr args) )
-                        (flatten  (catAttrs "buildInputs" flatOptions));
-
-          configureFlags = optsConcatStrs " " "cfgOption";
-
-          #flags = listToAttrs (map ( flag: av flag (hasAttr flag options) ) (attrNames flagConfig) );
-          flags_prefixed = listToAttrs (map ( flag: av ("flag_set_"+flag) (hasAttr flag options) ) (attrNames flagConfig) );
-
-          pass = mergeAttrs (flatten (collectAttrs "pass") );
-      } #  now add additional phase actions (see examples)
-      // listToAttrs ( map ( x : av x (optsConcatStrs "\n" x) ) collectExtraPhaseActions ) );
-}
-
-/* 
-
-  # ###########################################################################
-  #  configuration tutorial .. examples and tests.. 
-  #  Copy this into all-packages.nix and  try
-
-  # The following derviations will all fail.. 
-  # But they will print the passed options so that you can get to know
-  # how these configurations ought to work.
-  # TODO: There is no nice way to pass an otpion yet.
-  #       I could imagine something like
-  #       flags = [ "flagA" "flagB" { flagC = 4; } ];
-
-  # They are named:
-  # simpleYes, simpleNo, 
-  # defaultsimpleYes, defaultsimpleNo
-  # optionalssimpleYes, optionalssimpleNo
-  # bitingsimpleYes can only be ran with -iA  blockingBiteMonster
-  # assertionsimpleNo
-  # of course you can use -iA and the attribute name as well to select these examples
-
-  # dummy build input
-  whoGetsTheFlagFirst = gnused;
-  whoGetsTheFlagLast = gnumake;
-
-  # simple example demonstrating containing one flag.
-  # features:
-  # * configure options are passed automatically
-  # * buildInputs are collected (they are special, see the setup script)
-  # * they can be passed by additional name as well using pass =
-  # * an attribute named the same way as the flag is added indicating 
-  #   true/ false (flag has been set/ not set)
-  # * extra phase dependend commands can be added
-  #   Its easy to add your own stuff using co.collectAttrs or co.optsConcatStrs 
-  #   ( perhaps this name will change?)
-  simpleFlagYesNoF = namePrefix : extraFlagAttrs : mkDerivationByConfiguration ( {
-    flagConfig = {
-      flag    = { name = namePrefix + "simpleYes"; 
-                  cfgOption = [ "--Yes" "--you-dont-need-a-list" ]; 
-                  buildInputs = [ "whoGetsTheFlagFirst" ]; 
-                  pass = { inherit gnumake; };
-                  extraConfigureCmd = "echo Hello, it worked! ";
-                  blocks = "bitingMonster";
-                };
-      no_flag = { name = namePrefix + "simpleNo"; 
-                  cfgOption = "--no"; 
-                  implies = ["bitingMonster"];
-                };
-      bitingMonster = {
-                  extraConfigureCmd = "echo Ill bite you";
-                };
-      gnutar = { cfgOption="--with-gnutar";
-                  # buildInputs and pass will be added automatically if gnutar is added to optionals
-               };
-      # can be used to check configure options of dependencies
-      # eg testFlag = { assertion = [ arg.desktop.flag_set_wmii (! arg.desktop.flag_set_gnome) (! arg.desktops.flag_set_kde ]; }
-      assertionFlag = { assertion = false; }; # assert is nix language keyword
-                                        
-    }; 
-
-    collectExtraPhaseActions = [ "extraConfigureCmd" ];
-
-    extraAttrs = co : {
-      name = ( __head (co.collectAttrs "name") );
-
-      unpackPhase = "
-       echo my name is 
-       echo \$name
-       echo
-       echo flag given \\(should be 1 or empty string\\) ? 
-       echo \$flag_set_flag
-       echo
-       echo my build inputs are 
-       echo \$buildInputs
-       echo
-       echo my configuration flags are 
-       echo \$configureFlags
-       echo
-       echo what about gnumake? Did it pass?
-       echo \$gnumake
-       echo 
-       echo configurePhase command is
-       echo $\configurePhase
-       echo 
-       echo gnutar passed? \\(optional test\\)
-       echo \$gnutar
-       echo
-       echo dying now
-       echo die_Hopefully_Soon
-      ";
-    configurePhase = co.extraConfigureCmd;
-    };
-  } // extraFlagAttrs ); 
-
-
-  simpleYes = simpleFlagYesNoF "" {} {
-    inherit whoGetsTheFlagFirst lib stdenv;
-    flags = ["flag"];
-  };
-  # note the "I'll bite you" because of the implies attribute
-  simpleNo = simpleFlagYesNoF "" {} {
-    inherit whoGetsTheFlagFirst lib stdenv;
-    flags = [];
-  };
-
-  # specifying defaults by adding a default attribute
-  
-  yesAgainDefault = simpleFlagYesNoF "default" { defaults = [ "flag" ];} {
-    inherit whoGetsTheFlagFirst lib stdenv;
-  };
-  noAgainOverridingDefault = simpleFlagYesNoF "default" { defaults = [ "flag" ];} {
-    inherit whoGetsTheFlagFirst lib stdenv;
-    flags = [];
-  };
-
-  # requested by Michael Raskin: activate flag automatically if dependency is passed:
-  withGnutarOptional = simpleFlagYesNoF "optionals" { optionals = [ "gnutar" ];} {
-    flags = [ "flag" ]; # I only need to pass this to trigger name optionalssimpleYes
-    inherit whoGetsTheFlagFirst lib stdenv;
-    inherit gnutar;
-  };
-  withoutGnutarOptional = simpleFlagYesNoF "optionals" { optionals = [ "gnutar" ];} {
-    inherit whoGetsTheFlagFirst lib stdenv;
-  };
-
-  # blocking example, this shouldn't even start building:
-  blockingBiteMonster = simpleFlagYesNoF "biting" {} {
-    inherit whoGetsTheFlagFirst lib stdenv;
-    flags = [ "flag" "bitingMonster" ];
-  };
-
-  # assertion example this shouldn't even start building:
-  assertion = simpleFlagYesNoF "assertion" {} {
-    inherit whoGetsTheFlagFirst lib stdenv;
-    flags = [ "assertionFlag" ];
-  };
-*/
diff --git a/pkgs/lib/default.nix b/pkgs/lib/default.nix
index 33b7b3d6c9e..3ac24d5cfb3 100644
--- a/pkgs/lib/default.nix
+++ b/pkgs/lib/default.nix
@@ -3,22 +3,36 @@
 let
 
   inherit (builtins)
-    head tail isList stringLength substring lessThan sub;
+    head tail isList stringLength substring lessThan sub
+    listToAttrs attrNames hasAttr;
 
 in
 
 rec {
+  listOfListsToAttrs = ll : builtins.listToAttrs (map (l : { name = (head l); value = (head (tail l)); }) ll);
 
+
+  # Identity function.
+  id = x: x;
+
+
+  # accumulates / merges all attr sets until null is fed.
+  # example: sumArgs id { a = 'a'; x = 'x'; } { y = 'y'; x = 'X'; } null
+  # result : { a = 'a'; x = 'X'; y = 'Y'; }
   innerSumArgs = f : x : y : (if y == null then (f x)
 	else (innerSumArgs f (x // y)));
   sumArgs = f : innerSumArgs f {};
 
+  # example a = pairMap (x : y : x + y) ["a" "b" "c" "d"];
+  # result: ["ab" "cd"]
   innerPairMap = acc: f: l: 
   	if l == [] then acc else
 	innerPairMap (acc ++ [(f (head l)(head (tail l)))])
 		f (tail (tail l));
   pairMap = innerPairMap [];
 
+  
+  
   # "Fold" a binary function `op' between successive elements of
   # `list' with `nul' as the starting value, i.e., `fold op nul [x_1
   # x_2 ... x_n] == op x_1 (op x_2 ... (op x_n nul))'.  (This is
@@ -39,6 +53,12 @@ rec {
     fold (x: y: x + y) "";
 
 
+  # Map and concatenate the result.
+  concatMap = f: list: concatLists (map f list);
+
+  concatMapStrings = f: list: concatStrings (map f list);
+  
+
   # Place an element between each element of a list, e.g.,
   # `intersperse "," ["a" "b" "c"]' returns ["a" "," "b" "," "c"].
   intersperse = separator: list:
@@ -47,6 +67,7 @@ rec {
     else [(head list) separator]
          ++ (intersperse separator (tail list));
 
+  toList = x : if (__isList x) then x else [x];
 
   concatStringsSep = separator: list:
     concatStrings (intersperse separator list);
@@ -64,15 +85,18 @@ rec {
   # Return an attribute from nested attribute sets.  For instance ["x"
   # "y"] applied to some set e returns e.x.y, if it exists.  The
   # default value is returned otherwise.
+  # comment: there is also builtins.getAttr ? (is there a better name for this function?)
   getAttr = attrPath: default: e:
-    let {
-      attr = head attrPath;
-      body =
-        if attrPath == [] then e
-        else if builtins ? hasAttr && builtins.hasAttr attr e
-        then getAttr (tail attrPath) default (builtins.getAttr attr e)
-        else default;
-    };
+    let attr = head attrPath;
+    in
+      if attrPath == [] then e
+      else if builtins ? hasAttr && builtins.hasAttr attr e
+      then getAttr (tail attrPath) default (builtins.getAttr attr e)
+      else default;
+
+  # shortcut for getAttr ["name"] default attrs
+  maybeAttr = name: default: attrs:
+    if (__hasAttr name attrs) then (__getAttr name attrs) else default;
 
 
   # Filter a list using a predicate; that is, return a list containing
@@ -95,15 +119,39 @@ rec {
        else head found;
 
 
+  # Return true iff function `pred' returns true for at least element
+  # of `list'.
+  any = pred: list:
+    if list == [] then false
+    else if pred (head list) then true
+    else any pred (tail list);
+
+
+  # Return true iff function `pred' returns true for all elements of
+  # `list'.
+  all = pred: list:
+    if list == [] then true
+    else if pred (head list) then all pred (tail list)
+    else false;
+
+  # much shorter implementations using map and fold (are lazy as well)
+  # which ones are better?
+  # true if all/ at least one element(s) satisfy f
+  # all = f : l : fold logicalAND true (map f l);
+  # any = f : l : fold logicalOR false (map f l);
+
+
   # Return true if each element of a list is equal, false otherwise.
   eqLists = xs: ys:
     if xs == [] && ys == [] then true
     else if xs == [] || ys == [] then false
     else head xs == head ys && eqLists (tail xs) (tail ys);
 
+    
   # Workaround, but works in stable Nix now.
   eqStrings = a: b: (a+(substring 0 0 b)) == ((substring 0 0 a)+b);
 
+  
   # Determine whether a filename ends in the given suffix.
   hasSuffix = ext: fileName:
     let lenFileName = stringLength fileName;
@@ -112,25 +160,39 @@ rec {
        substring (sub lenFileName lenExt) lenFileName fileName == ext;
 
   hasSuffixHack = a: b: hasSuffix (a+(substring 0 0 b)) ((substring 0 0 a)+b);
-       
+
+         
   # Bring in a path as a source, filtering out all Subversion and CVS
   # directories, as well as backup files (*~).
   cleanSource =
     let filter = name: type: let baseName = baseNameOf (toString name); in ! (
       # Filter out Subversion and CVS directories.
-      (type == "directory" && (name == ".svn" || name == "CVS")) ||
+      (type == "directory" && (baseName == ".svn" || baseName == "CVS")) ||
       # Filter out backup files.
-      (hasSuffix "~" name)
+      (hasSuffix "~" baseName)
     );
     in src: builtins.filterSource filter src;
 
 
+  # Get all files ending with the specified suffices from the given
+  # directory.  E.g. `sourceFilesBySuffices ./dir [".xml" ".c"]'.
+  sourceFilesBySuffices = path: exts:
+    let filter = name: type: 
+      let base = baseNameOf (toString name);
+      in type != "directory" && any (ext: hasSuffix ext base) exts;
+    in builtins.filterSource filter path;
+
+
   # Return a singleton list or an empty list, depending on a boolean
   # value.  Useful when building lists with optional elements
   # (e.g. `++ optional (system == "i686-linux") flashplayer').
   optional = cond: elem: if cond then [elem] else [];
 
 
+  # Return a list or an empty list, dependening on a boolean value.
+  optionals = cond: elems: if cond then elems else [];
+
+
   # Return a list of integers from `first' up to and including `last'.
   range = first: last:
     if builtins.lessThan last first
@@ -190,6 +252,19 @@ rec {
 	in uniqList {outputList=newOutputList; 
 		inputList = (tail inputList);};
 
+  uniqListExt = {inputList, outputList ? [],
+    getter ? (x : x), compare ? (x: y: x==y)}:
+	if (inputList == []) then outputList else
+	let x=head inputList; 
+	isX = y: (compare (getter y) (getter x));
+	newOutputList = outputList ++
+	 (if any isX outputList then [] else [x]);
+	in uniqListExt {outputList=newOutputList; 
+		inputList = (tail inputList);
+		inherit getter compare;
+		};
+
+
                 
   condConcat = name: list: checker:
 	if list == [] then name else
@@ -200,8 +275,6 @@ rec {
 			checker
 	else condConcat
 		name (tail (tail list)) checker;
-
-
   /* Options. */
   
   mkOption = attrs: attrs // {_type = "option";};
@@ -244,4 +317,317 @@ rec {
         (l + (if l=="" then "" else ".") + s) (builtins.getAttr s attrs)))
         (builtins.attrNames attrs)))));
 
+  innerModifySumArgs = f: x: a: b: if b == null then (f a b) // x else 
+	innerModifySumArgs f x (a // b);
+  modifySumArgs = f: x: innerModifySumArgs f x {};
+
+  debugVal = if builtins ? trace then x: (builtins.trace x x) else x: x;
+  debugXMLVal = if builtins ? trace then x: (builtins.trace (builtins.toXML x) x) else x: x;
+
+  # this can help debug your code as well - designed to not produce thousands of lines
+  traceWhatis = x : __trace (whatis x) x;
+  whatis = x : 
+      if (__isAttrs x) then
+          if (x ? outPath) then "x is a derivation with name ${x.name}"
+          else "x is an attr set with attributes ${builtins.toString (__attrNames x)}"
+      else if (__isFunction x) then "x is a function"
+      else if (__isList x) then "x is a list, first item is : ${whatis (__head x)}"
+      else if (x == true || x == false) then builtins.toString x
+      else "x is propably a string starting, starting characters: ${__substring 0 50 x}..";
+
+
+  innerClosePropagation = ready: list: if list == [] then ready else
+    if (head list) ? propagatedBuildInputs then 
+      innerClosePropagation (ready ++ [(head list)]) 
+        ((head list).propagatedBuildInputs ++ (tail list)) else
+      innerClosePropagation (ready ++ [(head list)]) (tail list);
+
+  closePropagation = list: (uniqList {inputList = (innerClosePropagation [] list);});
+
+  stringToCharacters = s : let l = __stringLength s; in
+    if (__lessThan l 1) then [""] else  [(__substring 0 1 s)] ++ stringToCharacters (__substring 1 (__sub l 1) s);
+
+  # should this be implemented as primop ? Yes it should..
+  escapeShellArg = s :
+    let escapeChar = x : if ( x == "'" ) then "'\"'\"'" else x;
+    in "'" + concatStrings (map escapeChar (stringToCharacters s) ) +"'";
+
+  defineShList = name : list : "\n${name}=(${concatStringsSep " " (map escapeShellArg list)})\n";
+
+  # calls a function (f attr value ) for each record item. returns a list
+  mapRecordFlatten = f : r : map (attr: f attr (builtins.getAttr attr r) ) (attrNames r);
+
+  # to be used with listToAttrs (_a_ttribute _v_alue)
+  nv = name : value : { inherit name value; };
+  # attribute set containing one attribute
+  nvs = name : value : listToAttrs [ (nv name value) ];
+  # adds / replaces an attribute of an attribute set
+  setAttr = set : name : v : set // (nvs name v);
+
+  # iterates over a list of attributes collecting the attribute attr if it exists
+  catAttrs = attr : l : fold ( s : l : if (hasAttr attr s) then [(builtins.getAttr attr s)] ++ l else l) [] l;
+
+  mergeAttrs = fold ( x : y : x // y) {};
+
+  # Using f = a : b = b the result is similar to //
+  # merge attributes with custom function handling the case that the attribute
+  # exists in both sets
+  mergeAttrsWithFunc = f : set1 : set2 :
+    fold (n: set : if (__hasAttr n set) 
+                        then setAttr set n (f (__getAttr n set) (__getAttr n set2))
+                        else set )
+           set1 (__attrNames set2);
+
+  # merging two attribute set concatenating the values of same attribute names
+  # eg { a = 7; } {  a = [ 2 3 ]; } becomes { a = [ 7 2 3 ]; }
+  mergeAttrsConcatenateValues = mergeAttrsWithFunc ( a : b : (toList a) ++ (toList b) );
+
+  # returns atribute values as a list 
+  flattenAttrs = set : map ( attr : builtins.getAttr attr set) (attrNames set);
+  mapIf = cond : f :  fold ( x : l : if (cond x) then [(f x)] ++ l else l) [];
+
+  # pick attrs subset_attr_names and apply f 
+  subsetmap = f : attrs : subset_attr_names : 
+    listToAttrs (fold ( attr : r : if __hasAttr attr attrs
+          then r ++ [ (  nv attr ( f (__getAttr attr attrs) ) ) ] else r ) []
+      subset_attr_names );
+
+# Marc 2nd proposal: (not everything has been tested in detail yet..)
+
+  # usage / example
+  # flagConfig = {
+  # } // (enableDisableFeature "flagName" "configure_feature" extraAttrs;)
+  #
+  # is equal to
+  # flagConfig = {
+  #   flagName = { cfgOption = "--enable-configure_feature"; } // extraAttrs;
+  #   no_flagName = { cfgOption = "--disable-configure_feature"; };
+  enableDisableFeature = flagName : configure_feature : extraAttrs :
+    listToAttrs [ ( nv flagName ({ cfgOption = "--enable-${configure_feature}"; } // extraAttrs ) )
+                  ( nv "no_${flagName}" ({ cfgOption = "--disable-${configure_feature}"; } ) )];
+
+  # calls chooseOptionsByFlags2 with some preprocessing
+  # chooseOptionsByFlags2 returns an attribute set meant to be used to create new derivaitons.
+  # see mkDerivationByConfiguration in all-packages.nix and the examples given below.
+  # You can just copy paste them into all-packages.nix to test them..
+
+  chooseOptionsByFlags = { flagConfig, args, optionals ? [], defaults ? [],
+                           collectExtraPhaseActions ? [] } :
+    let passedOptionals = filter ( x : hasAttr x args ) optionals; # these are in optionals and in args
+        # we simply merge in <optional_name> = { buildInputs = <arg.<optional_name>; pass = <arg.optional_name>; }
+        flagConfigWithOptionals = flagConfig // ( listToAttrs
+          (map ( o : nv o ( { buildInputs = o; pass = nvs o (builtins.getAttr o args); }
+                            // getAttr [o] {} flagConfig )
+               )
+               passedOptionals ) );
+
+    in chooseOptionsByFlags2 flagConfigWithOptionals collectExtraPhaseActions args 
+       ( (getAttr ["flags"] defaults args) ++ passedOptionals);
+
+  chooseOptionsByFlags2 = flagConfig : collectExtraPhaseActions : args : flags :
+    let   
+        # helper function
+        collectFlags = # state : flags :
+              fold ( flag : s : (
+                     if (hasAttr flag s.result) then s # this state has already been visited
+                     else if (! hasAttr flag flagConfig) then throw "unkown flag `${flag}' specified"
+                           else let fDesc = (builtins.getAttr flag flagConfig);
+                                    implied = flatten ( getAttr ["implies"] [] fDesc );
+                                    blocked = flatten ( getAttr ["blocks"] [] fDesc ); 
+                                    # add this flag
+                                    s2 =  s // { result = ( setAttr s.result flag (builtins.getAttr flag flagConfig) );
+                                                 blockedFlagsBy = s.blockedFlagsBy 
+                                                   // listToAttrs (map (b: nv b flag ) blocked); };
+                                    # add implied flags
+                                in collectFlags s2 implied
+                   ));
+
+        # chosen contains flagConfig but only having those attributes elected by flags 
+        # (or by implies attributes of elected attributes)
+        options = let stateOpts = collectFlags { blockedFlagsBy = {}; result = {}; } 
+                                               (flags ++ ( if (hasAttr "mandatory" flagConfig) then ["mandatory"] else [] ));
+                      # these options have not been chosen (neither by flags nor by implies)
+                      unsetOptions = filter ( x : (! hasAttr x stateOpts.result) && (hasAttr ("no_"+x) flagConfig)) 
+                                            ( attrNames flagConfig );
+                      # no add the corresponding no_ attributes as well ..
+                      state = collectFlags stateOpts (map ( x : "no_" + x ) unsetOptions);
+                  in # check for blockings:
+                     assert ( all id ( map ( b: if (hasAttr b state.result) 
+                                             then throw "flag ${b} is blocked by flag ${__getAttr b state.blockedFlagsBy}"
+                                             else true ) 
+                                           (attrNames state.blockedFlagsBy) ) ); 
+                    state.result;
+        flatOptions = flattenAttrs options;
+
+        # helper functions :
+        collectAttrs = attr : catAttrs attr flatOptions;
+        optsConcatStrs = delimiter : attrs : concatStrings 
+                ( intersperse delimiter (flatten ( collectAttrs attrs ) ) );
+
+        ifStringGetArg = x : if (__isAttrs x) then x # ( TODO implement __isString ?)
+                             else nvs x (__getAttr x args);
+          
+    in assert ( all id ( mapRecordFlatten ( attr : r : if ( all id ( flatten (getAttr ["assertion"] [] r ) ) ) 
+                                              then true else throw "assertion failed flag ${attr}" )
+                                         options) );
+      ( rec {
+
+          #foldOptions = attr: f : start: fold f start (catAttrs attr flatOptions);
+
+          # compared to flags flagsSet does also contain the implied flags.. This makes it easy to write assertions. ( assert args.
+          inherit options flatOptions collectAttrs optsConcatStrs;
+
+          buildInputs = map ( attr: if (! hasAttr attr args) then throw "argument ${attr} is missing!" else (builtins.getAttr attr args) )
+                        (flatten  (catAttrs "buildInputs" flatOptions));
+          propagatedBuildInputs = map ( attr: if (! hasAttr attr args) then throw "argument ${attr} is missing!" else (builtins.getAttr attr args) )
+                        (flatten  (catAttrs "propagatedBuildInputs" flatOptions));
+
+          configureFlags = optsConcatStrs " " "cfgOption";
+
+          #flags = listToAttrs (map ( flag: nv flag (hasAttr flag options) ) (attrNames flagConfig) );
+          flags_prefixed = listToAttrs (map ( flag: nv ("flag_set_"+flag) (hasAttr flag options) ) (attrNames flagConfig) );
+
+          pass = mergeAttrs ( map ifStringGetArg ( flatten (collectAttrs "pass") ) );
+      } #  now add additional phase actions (see examples)
+      // listToAttrs ( map ( x : nv x (optsConcatStrs "\n" x) ) collectExtraPhaseActions ) );
 }
+
+/* 
+  TODO: Perhaps it's better to move this documentation / these tests into some extra packages ..
+
+  # ###########################################################################
+  #  configuration tutorial .. examples and tests.. 
+  #  Copy this into all-packages.nix and  try
+
+  # The following derviations will all fail.. 
+  # But they will print the passed options so that you can get to know
+  # how these configurations ought to work.
+  # TODO: There is no nice way to pass an otpion yet.
+  #       I could imagine something like
+  #       flags = [ "flagA" "flagB" { flagC = 4; } ];
+
+  # They are named:
+  # simpleYes, simpleNo, 
+  # defaultsimpleYes, defaultsimpleNo
+  # optionalssimpleYes, optionalssimpleNo
+  # bitingsimpleYes can only be ran with -iA  blockingBiteMonster
+  # assertionsimpleNo
+  # of course you can use -iA and the attribute name as well to select these examples
+
+  # dummy build input
+  whoGetsTheFlagFirst = gnused;
+  whoGetsTheFlagLast = gnumake;
+
+  # simple example demonstrating containing one flag.
+  # features:
+  # * configure options are passed automatically
+  # * buildInputs are collected (they are special, see the setup script)
+  # * they can be passed by additional name as well using pass = { inherit (args) python } 
+  #                                       ( or short (value not attrs) : pass = "python" )
+  # * an attribute named the same way as the flag is added indicating 
+  #   true/ false (flag has been set/ not set)
+  # * extra phase dependend commands can be added
+  #   Its easy to add your own stuff using co.collectAttrs or co.optsConcatStrs 
+  #   ( perhaps this name will change?)
+  simpleFlagYesNoF = namePrefix : extraFlagAttrs : mkDerivationByConfiguration ( {
+    flagConfig = {
+      flag    = { name = namePrefix + "simpleYes"; 
+                  cfgOption = [ "--Yes" "--you-dont-need-a-list" ]; 
+                  buildInputs = [ "whoGetsTheFlagFirst" ]; 
+                  pass = { inherit gnumake; };
+                  extraConfigureCmd = "echo Hello, it worked! ";
+                  blocks = "bitingMonster";
+                };
+      no_flag = { name = namePrefix + "simpleNo"; 
+                  cfgOption = "--no"; 
+                  implies = ["bitingMonster"];
+                };
+      bitingMonster = {
+                  extraConfigureCmd = "echo Ill bite you";
+                };
+      gnutar = { cfgOption="--with-gnutar";
+                  # buildInputs and pass will be added automatically if gnutar is added to optionals
+               };
+      # can be used to check configure options of dependencies
+      # eg testFlag = { assertion = [ arg.desktop.flag_set_wmii (! arg.desktop.flag_set_gnome) (! arg.desktops.flag_set_kde ]; }
+      assertionFlag = { assertion = false; }; # assert is nix language keyword
+                                        
+    }; 
+
+    collectExtraPhaseActions = [ "extraConfigureCmd" ];
+
+    extraAttrs = co : {
+      name = ( __head (co.collectAttrs "name") );
+
+      unpackPhase = "
+       echo my name is 
+       echo \$name
+       echo
+       echo flag given \\(should be 1 or empty string\\) ? 
+       echo \$flag_set_flag
+       echo
+       echo my build inputs are 
+       echo \$buildInputs
+       echo
+       echo my configuration flags are 
+       echo \$configureFlags
+       echo
+       echo what about gnumake? Did it pass?
+       echo \$gnumake
+       echo 
+       echo configurePhase command is
+       echo $\configurePhase
+       echo 
+       echo gnutar passed? \\(optional test\\)
+       echo \$gnutar
+       echo
+       echo dying now
+       echo die_Hopefully_Soon
+      ";
+    configurePhase = co.extraConfigureCmd;
+    };
+  } // extraFlagAttrs ); 
+
+
+  simpleYes = simpleFlagYesNoF "" {} {
+    inherit whoGetsTheFlagFirst lib stdenv;
+    flags = ["flag"];
+  };
+  # note the "I'll bite you" because of the implies attribute
+  simpleNo = simpleFlagYesNoF "" {} {
+    inherit whoGetsTheFlagFirst lib stdenv;
+    flags = [];
+  };
+
+  # specifying defaults by adding a default attribute
+  
+  yesAgainDefault = simpleFlagYesNoF "default" { defaults = [ "flag" ];} {
+    inherit whoGetsTheFlagFirst lib stdenv;
+  };
+  noAgainOverridingDefault = simpleFlagYesNoF "default" { defaults = [ "flag" ];} {
+    inherit whoGetsTheFlagFirst lib stdenv;
+    flags = [];
+  };
+
+  # requested by Michael Raskin: activate flag automatically if dependency is passed:
+  withGnutarOptional = simpleFlagYesNoF "optionals" { optionals = [ "gnutar" ];} {
+    flags = [ "flag" ]; # I only need to pass this to trigger name optionalssimpleYes
+    inherit whoGetsTheFlagFirst lib stdenv;
+    inherit gnutar;
+  };
+  withoutGnutarOptional = simpleFlagYesNoF "optionals" { optionals = [ "gnutar" ];} {
+    inherit whoGetsTheFlagFirst lib stdenv;
+  };
+
+  # blocking example, this shouldn't even start building:
+  blockingBiteMonster = simpleFlagYesNoF "biting" {} {
+    inherit whoGetsTheFlagFirst lib stdenv;
+    flags = [ "flag" "bitingMonster" ];
+  };
+
+  # assertion example this shouldn't even start building:
+  assertion = simpleFlagYesNoF "assertion" {} {
+    inherit whoGetsTheFlagFirst lib stdenv;
+    flags = [ "assertionFlag" ];
+  };
+*/
diff --git a/pkgs/lib/strings-with-deps.nix b/pkgs/lib/strings-with-deps.nix
index 78cded99ef7..4fb4fe150a7 100644
--- a/pkgs/lib/strings-with-deps.nix
+++ b/pkgs/lib/strings-with-deps.nix
@@ -1,9 +1,24 @@
+/*
+Usage:
+
+  You define you custom builder script by adding all build steps to a list.
+  for example:
+	builder = writeScript "fsg-4.4-builder"
+		(textClosure [doUnpack addInputs preBuild doMake installPhase doForceShare]);
+
+  a step is defined by noDepEntry, FullDepEntry or PackEntry.
+  To ensure that prerequisite are met those are added before the task itself by
+  textClosureDupList. Duplicated items are removed again.
+
+  See trace/nixpkgs/trunk/pkgs/top-level/builder-defs.nix for some predefined build steps
+
+*/
 args: 
 	with args;
 	with lib;
 	let 
 		inherit (builtins)	
-			head tail isList;
+			head tail isList isAttrs;
 in
 rec {
 
@@ -37,12 +52,23 @@ rec {
 			(concatLists (map textClosureDupList arg.deps)) ++ [arg]
 	);
 
-	textClosureList = arg:
+	textClosureDupListOverridable = predefined: arg:
+	(
+		if isList arg then 
+			textClosureDupListOverridable predefined {text = ""; deps = arg;} 
+		else if isAttrs arg then
+			(concatLists (map (textClosureDupListOverridable predefined) arg.deps)) ++ [arg]
+		else
+			textClosureDupListOverridable predefined (getAttr [arg] [] predefined)
+	);
+
+	textClosureListOverridable = predefined: arg:
 		(map	(x : x.text) 
-			(uniqList {inputList = textClosureDupList arg;}));
-	textClosure = arg: concatStringsSep "\n" (textClosureList arg);
+			(uniqList {inputList = textClosureDupListOverridable predefined arg;}));
+	textClosureOverridable = predefined: arg: concatStringsSep "\n" (textClosureListOverridable predefined arg);
 	
-	textClosureMap = f: arg: concatStringsSep "\n" (map f (textClosureList arg));
+	textClosureMapOveridable = f: predefined: arg: 
+		concatStringsSep "\n" (map f (textClosureListOverridable predefined arg));
 
 	noDepEntry = text : {inherit text;deps = [];};
 	FullDepEntry = text : deps: {inherit text deps;};
diff --git a/pkgs/misc/emulators/wine/default.nix b/pkgs/misc/emulators/wine/default.nix
index 8106390674e..3127036d68b 100644
--- a/pkgs/misc/emulators/wine/default.nix
+++ b/pkgs/misc/emulators/wine/default.nix
@@ -1,5 +1,6 @@
 { stdenv, fetchurl, xlibs, flex, bison, mesa, alsaLib
 , ncurses, libpng, libjpeg, lcms, freetype, fontconfig, fontforge
+, libxml2, libxslt, openssl
 }:
 
 assert stdenv.isLinux;
@@ -7,26 +8,29 @@ assert stdenv.isLinux;
 let lib = import ../../../lib/default.nix; in
 
 stdenv.mkDerivation {
-  name = "wine-0.9.46";
+  name = "wine-0.9.55";
 
   src = fetchurl {
-		url = mirror://sourceforge/wine/wine-0.9.46.tar.bz2;
-		sha256 = "0c5fapw38bivipi8yzci3swxyhl9g67dpicqzslwmffwbi9y9z3i";
-	};
+    url = mirror://sourceforge/wine/wine-0.9.55.tar.bz2;
+    sha256 = "1qsyd4k7fbv8nsv3y7zi72fakpp6z1idi7afhi87qv9xgqzy3a4d";
+  };
 
   buildInputs = [
     xlibs.xlibs flex bison xlibs.libXi mesa
     xlibs.libXcursor xlibs.libXinerama xlibs.libXrandr
-    xlibs.libXrender xlibs.libXxf86vm alsaLib ncurses
-    libpng libjpeg lcms fontforge
+    xlibs.libXrender xlibs.libXxf86vm xlibs.libXcomposite
+    alsaLib ncurses libpng libjpeg lcms fontforge
+    libxml2 libxslt openssl
   ];
 
   # Wine locates a lot of libraries dynamically through dlopen().  Add
   # them to the RPATH so that the user doesn't have to set them in
   # LD_LIBRARY_PATH.
-  NIX_LDFLAGS = map (path: "-rpath " + path + "/lib") [
+  NIX_LDFLAGS = map (path: "-rpath ${path}/lib") [
     freetype fontconfig stdenv.gcc.gcc mesa mesa.libdrm
-    xlibs.libXinerama xlibs.libXrender xlibs.libXrandr xlibs.libXcursor
+    xlibs.libXinerama xlibs.libXrender xlibs.libXrandr
+    xlibs.libXcursor xlibs.libXcomposite
+    openssl
   ];
 
   # Don't shrink the ELF RPATHs in order to keep the extra RPATH
diff --git a/pkgs/misc/emulators/wine/opengl-child-window.patch b/pkgs/misc/emulators/wine/opengl-child-window.patch
deleted file mode 100644
index 3340ecf7011..00000000000
--- a/pkgs/misc/emulators/wine/opengl-child-window.patch
+++ /dev/null
@@ -1,1286 +0,0 @@
-diff -rc wine-0.9.43-orig/dlls/winex11.drv/dce.c wine-0.9.43/dlls/winex11.drv/dce.c
-*** wine-0.9.43-orig/dlls/winex11.drv/dce.c	2007-08-10 18:18:12.000000000 +0200
---- wine-0.9.43/dlls/winex11.drv/dce.c	2007-08-21 10:20:19.000000000 +0200
-***************
-*** 639,644 ****
---- 639,656 ----
-  
-  
-  /**********************************************************************
-+  *      hwnd_from_dce
-+  *
-+  * Retrieve the HWND from a given dce
-+  */
-+ HWND hwnd_from_dce( struct dce *dce )
-+ {
-+     HWND hwnd = 0;
-+     if (dce) hwnd = dce->hwnd;
-+     return hwnd;
-+ }
-+ 
-+ /**********************************************************************
-   *		WindowFromDC   (X11DRV.@)
-   */
-  HWND X11DRV_WindowFromDC( HDC hdc )
-***************
-*** 650,656 ****
-      EnterCriticalSection( &dce_section );
-      if (!ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPCSTR)&escape,
-                      sizeof(dce), (LPSTR)&dce )) dce = NULL;
-!     if (dce) hwnd = dce->hwnd;
-      LeaveCriticalSection( &dce_section );
-      return hwnd;
-  }
---- 662,668 ----
-      EnterCriticalSection( &dce_section );
-      if (!ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPCSTR)&escape,
-                      sizeof(dce), (LPSTR)&dce )) dce = NULL;
-!     hwnd = hwnd_from_dce( dce );
-      LeaveCriticalSection( &dce_section );
-      return hwnd;
-  }
-diff -rc wine-0.9.43-orig/dlls/winex11.drv/event.c wine-0.9.43/dlls/winex11.drv/event.c
-*** wine-0.9.43-orig/dlls/winex11.drv/event.c	2007-08-10 18:18:12.000000000 +0200
---- wine-0.9.43/dlls/winex11.drv/event.c	2007-08-21 10:20:19.000000000 +0200
-***************
-*** 957,962 ****
---- 957,973 ----
-          return X11DRV_AcquireClipboard( hwnd );
-      case WM_X11DRV_DELETE_WINDOW:
-          return SendMessageW( hwnd, WM_SYSCOMMAND, SC_CLOSE, 0 );
-+     case WM_X11DRV_GET_PARENT_INFO:
-+         {
-+             struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
-+             if (data)
-+             {
-+                 ((void**)lp)[0] = &data->client_rect;
-+                 ((void**)lp)[1] = thread_display();
-+                 return 1;
-+             }
-+         }
-+         return 0;
-      default:
-          FIXME( "got window msg %x hwnd %p wp %lx lp %lx\n", msg, hwnd, wp, lp );
-          return 0;
-Only in wine-0.9.43/dlls/winex11.drv: event.c.orig
-diff -rc wine-0.9.43-orig/dlls/winex11.drv/init.c wine-0.9.43/dlls/winex11.drv/init.c
-*** wine-0.9.43-orig/dlls/winex11.drv/init.c	2007-08-10 18:18:12.000000000 +0200
---- wine-0.9.43/dlls/winex11.drv/init.c	2007-08-21 10:20:19.000000000 +0200
-***************
-*** 129,134 ****
---- 129,135 ----
-      if (!physDev) return FALSE;
-  
-      *pdev = physDev;
-+     physDev->display = gdi_display;
-      physDev->hdc = hdc;
-  
-      if (GetObjectType( hdc ) == OBJ_MEMDC)
-Only in wine-0.9.43/dlls/winex11.drv: init.c.orig
-diff -rc wine-0.9.43-orig/dlls/winex11.drv/opengl.c wine-0.9.43/dlls/winex11.drv/opengl.c
-*** wine-0.9.43-orig/dlls/winex11.drv/opengl.c	2007-08-10 18:18:12.000000000 +0200
---- wine-0.9.43/dlls/winex11.drv/opengl.c	2007-08-21 10:31:52.000000000 +0200
-***************
-*** 575,583 ****
-      int tmp;
-      int ctx_vis_id;
-      TRACE(" Context %p have (vis:%p):\n", ctx, ctx->vis);
-!     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_FBCONFIG_ID, &tmp);
-      TRACE(" - FBCONFIG_ID 0x%x\n", tmp);
-!     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_VISUAL_ID, &tmp);
-      TRACE(" - VISUAL_ID 0x%x\n", tmp);
-      ctx_vis_id = tmp;
-      return ctx_vis_id;
---- 575,583 ----
-      int tmp;
-      int ctx_vis_id;
-      TRACE(" Context %p have (vis:%p):\n", ctx, ctx->vis);
-!     pglXGetFBConfigAttrib(ctx->physDev->display, ctx->fmt->fbconfig, GLX_FBCONFIG_ID, &tmp);
-      TRACE(" - FBCONFIG_ID 0x%x\n", tmp);
-!     pglXGetFBConfigAttrib(ctx->physDev->display, ctx->fmt->fbconfig, GLX_VISUAL_ID, &tmp);
-      TRACE(" - VISUAL_ID 0x%x\n", tmp);
-      ctx_vis_id = tmp;
-      return ctx_vis_id;
-***************
-*** 595,614 ****
-      }
-  
-      TRACE(" Drawable %p have :\n", (void*) drawable);
-!     pglXQueryDrawable(gdi_display, drawable, GLX_WIDTH, (unsigned int*) &tmp);
-      TRACE(" - WIDTH as %d\n", tmp);
-!     pglXQueryDrawable(gdi_display, drawable, GLX_HEIGHT, (unsigned int*) &tmp);
-      TRACE(" - HEIGHT as %d\n", tmp);
-!     pglXQueryDrawable(gdi_display, drawable, GLX_FBCONFIG_ID, (unsigned int*) &tmp);
-      TRACE(" - FBCONFIG_ID as 0x%x\n", tmp);
-  
-      attribList[1] = tmp;
-!     fbCfgs = pglXChooseFBConfig(gdi_display, DefaultScreen(gdi_display), attribList, &nElements);
-      if (fbCfgs == NULL) {
-          return -1;
-      }
-  
-!     pglXGetFBConfigAttrib(gdi_display, fbCfgs[0], GLX_VISUAL_ID, &tmp);
-      TRACE(" - VISUAL_ID as 0x%x\n", tmp);
-  
-      XFree(fbCfgs);
---- 595,614 ----
-      }
-  
-      TRACE(" Drawable %p have :\n", (void*) drawable);
-!     pglXQueryDrawable(ctx->physDev->display, drawable, GLX_WIDTH, (unsigned int*) &tmp);
-      TRACE(" - WIDTH as %d\n", tmp);
-!     pglXQueryDrawable(ctx->physDev->display, drawable, GLX_HEIGHT, (unsigned int*) &tmp);
-      TRACE(" - HEIGHT as %d\n", tmp);
-!     pglXQueryDrawable(ctx->physDev->display, drawable, GLX_FBCONFIG_ID, (unsigned int*) &tmp);
-      TRACE(" - FBCONFIG_ID as 0x%x\n", tmp);
-  
-      attribList[1] = tmp;
-!     fbCfgs = pglXChooseFBConfig(ctx->physDev->display, DefaultScreen(gdi_display), attribList, &nElements);
-      if (fbCfgs == NULL) {
-          return -1;
-      }
-  
-!     pglXGetFBConfigAttrib(ctx->physDev->display, fbCfgs[0], GLX_VISUAL_ID, &tmp);
-      TRACE(" - VISUAL_ID as 0x%x\n", tmp);
-  
-      XFree(fbCfgs);
-***************
-*** 1236,1265 ****
-  
-    wine_tsx11_lock();
-  
-!   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_CONFIG_CAVEAT, &value);
-    if(value == GLX_SLOW_CONFIG)
-        ppfd->dwFlags |= PFD_GENERIC_ACCELERATED;
-  
-!   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value); if (value) ppfd->dwFlags |= PFD_DOUBLEBUFFER;
-!   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value); if (value) ppfd->dwFlags |= PFD_STEREO;
-  
-    /* Pixel type */
-!   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
-    if (value & GLX_RGBA_BIT)
-      ppfd->iPixelType = PFD_TYPE_RGBA;
-    else
-      ppfd->iPixelType = PFD_TYPE_COLORINDEX;
-  
-    /* Color bits */
-!   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &value);
-    ppfd->cColorBits = value;
-  
-    /* Red, green, blue and alpha bits / shifts */
-    if (ppfd->iPixelType == PFD_TYPE_RGBA) {
-!     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RED_SIZE, &rb);
-!     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_GREEN_SIZE, &gb);
-!     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BLUE_SIZE, &bb);
-!     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &ab);
-  
-      ppfd->cRedBits = rb;
-      ppfd->cRedShift = gb + bb + ab;
---- 1236,1265 ----
-  
-    wine_tsx11_lock();
-  
-!   pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_CONFIG_CAVEAT, &value);
-    if(value == GLX_SLOW_CONFIG)
-        ppfd->dwFlags |= PFD_GENERIC_ACCELERATED;
-  
-!   pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value); if (value) ppfd->dwFlags |= PFD_DOUBLEBUFFER;
-!   pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_STEREO, &value); if (value) ppfd->dwFlags |= PFD_STEREO;
-  
-    /* Pixel type */
-!   pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
-    if (value & GLX_RGBA_BIT)
-      ppfd->iPixelType = PFD_TYPE_RGBA;
-    else
-      ppfd->iPixelType = PFD_TYPE_COLORINDEX;
-  
-    /* Color bits */
-!   pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_BUFFER_SIZE, &value);
-    ppfd->cColorBits = value;
-  
-    /* Red, green, blue and alpha bits / shifts */
-    if (ppfd->iPixelType == PFD_TYPE_RGBA) {
-!     pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_RED_SIZE, &rb);
-!     pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_GREEN_SIZE, &gb);
-!     pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_BLUE_SIZE, &bb);
-!     pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_ALPHA_SIZE, &ab);
-  
-      ppfd->cRedBits = rb;
-      ppfd->cRedShift = gb + bb + ab;
-***************
-*** 1293,1303 ****
-    ppfd->cAccumAlphaBits = ab;
-  
-    /* Depth bits */
-!   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &value);
-    ppfd->cDepthBits = value;
-  
-    /* stencil bits */
-!   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &value);
-    ppfd->cStencilBits = value;
-  
-    wine_tsx11_unlock();
---- 1293,1303 ----
-    ppfd->cAccumAlphaBits = ab;
-  
-    /* Depth bits */
-!   pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_DEPTH_SIZE, &value);
-    ppfd->cDepthBits = value;
-  
-    /* stencil bits */
-!   pglXGetFBConfigAttrib(physDev->display, fmt->fbconfig, GLX_STENCIL_SIZE, &value);
-    ppfd->cStencilBits = value;
-  
-    wine_tsx11_unlock();
-***************
-*** 1350,1357 ****
---- 1350,1365 ----
-  BOOL X11DRV_SetPixelFormat(X11DRV_PDEVICE *physDev,
-  			   int iPixelFormat,
-  			   const PIXELFORMATDESCRIPTOR *ppfd) {
-+   XSetWindowAttributes attr;
-+   XVisualInfo *vis;
-+   XVisualInfo template;
-+   Display *display;
-+   Window gl_child;
-+   HWND main_hwnd;
-+   RECT rect;
-    WineGLPixelFormat *fmt;
-    int value;
-+   int num;
-  
-    TRACE("(%p,%d,%p)\n", physDev, iPixelFormat, ppfd);
-  
-***************
-*** 1374,1380 ****
---- 1382,1494 ----
-      return 0;
-    }
-  
-+   /* Check for an existing pixel format */
-+   if (physDev->current_pf) {
-+     if (physDev->current_pf != iPixelFormat) {
-+       ERR("Pixel format already set for physDev (cur: %d, req: %d)\n", physDev->current_pf, iPixelFormat);
-+       return 0;
-+     }
-+     /* TODO: test if the current gl_drawable is still valid */
-+   }
-+ 
-+   /* Check the window we'll be parenting from */
-+   if (!physDev->drawable) {
-+     ERR("No drawable associated with physDev %p\n", physDev);
-+     return 0;
-+   }
-+ 
-+ 
-+   /* Get the window and display for the opengl child */
-+   main_hwnd = hwnd_from_dce(physDev->dce);
-+   display = X11DRV_get_gl_display(main_hwnd);
-+ 
-+   TRACE("main_hwnd: %p\n", main_hwnd);
-+   /* Make sure this window doesn't already have a gl drawable */
-+   if (physDev->gl_drawable) {
-+         /* Check if the gl_drawable is still valid */
-+         if(X11DRV_get_gl_window(main_hwnd) == 0)
-+             physDev->gl_drawable = 0;
-+         else
-+             WARN("Window already has an opengl child (%p), possible window leak!\n", (void*)physDev->gl_drawable);
-+ 
-+     physDev->gl_drawable = 0;
-+     X11DRV_set_gl_window(main_hwnd, 0);
-+   }
-+ 
-+   /* Force semi-sane values */
-+   rect = physDev->dc_rect;
-+   if (rect.right <= rect.left) {
-+     rect.right = 0;
-+     rect.left = -16;
-+   }
-+   if (rect.bottom <= rect.top) {
-+     rect.bottom = 0;
-+     rect.top = -16;
-+   }
-+ 
-+   wine_tsx11_lock();
-+ 
-+   /* Get the visual for the X11 child window and set up a colormap for it */
-+   template.visualid = XVisualIDFromVisual(visual);
-+   vis = XGetVisualInfo(gdi_display, VisualIDMask, &template, &num);
-+   if (!vis) {
-+     wine_tsx11_unlock();
-+     ERR("No visual for pixel format %i\n", iPixelFormat);
-+     return 0;
-+   }
-+ 
-+   if ((vis->class == PseudoColor) || (vis->class == GrayScale) ||
-+       (vis->class == DirectColor)) {
-+     attr.colormap = XCreateColormap(display, physDev->drawable, vis->visual, AllocAll);
-+   }
-+   else {
-+     attr.colormap = XCreateColormap(display, physDev->drawable, vis->visual, AllocNone);
-+   }
-+   XInstallColormap(display, attr.colormap);
-+ 
-+   TRACE("Creating X11 window x=%d,y=%d,w=%d,h=%d, parent=%p\n", rect.left, rect.top,
-+         rect.right-rect.left, rect.bottom-rect.top, (void*)physDev->drawable);
-+ 
-+   /* Create the window */
-+   gl_child = XCreateWindow(display, physDev->drawable, rect.left, rect.top,
-+ //  gl_child = XCreateWindow(display, RootWindow(display, DefaultScreen(display)), rect.left, rect.top,
-+                            rect.right-rect.left, rect.bottom-rect.top, 0,
-+                            CopyFromParent, InputOutput, vis->visual,
-+                            CWColormap, &attr);
-+ 
-+   XFree(vis);
-+   wine_tsx11_unlock();
-+ 
-+   if (!gl_child) {
-+     ERR("Could not create OpenGL child window!\n");
-+     return 0;
-+   }
-+ 
-+   if(!X11DRV_set_gl_window(main_hwnd, gl_child)) {
-+     wine_tsx11_lock();
-+     XDestroyWindow(display, gl_child);
-+     wine_tsx11_unlock();
-+     ERR("Could not set OpenGL child window for hwnd %p!\n", main_hwnd);
-+     return 0;
-+   }
-+ 
-+   TRACE("Created window %p\n", (void*)gl_child);
-+ 
-    physDev->current_pf = iPixelFormat;
-+ //if(physDev->dc_rect.left != 4)
-+ //physDev->gl_drawable = 0;
-+ //else
-+   physDev->gl_drawable = gl_child;
-+   physDev->display = display;
-+ 
-+   /* Finally, map the child if the window is visible */
-+   if (X11DRV_is_window_rect_mapped(&physDev->dc_rect) &&
-+       X11DRV_get_visible(main_hwnd)) {
-+     wine_tsx11_lock();
-+ //    if(physDev->dc_rect.left == 4)
-+     XMapWindow(physDev->display, physDev->gl_drawable);
-+     wine_tsx11_unlock();
-+   }
-  
-    if (TRACE_ON(opengl)) {
-      int gl_test = 0;
-***************
-*** 1407,1412 ****
---- 1521,1527 ----
-        TRACE(" - DRAWABLE_TYPE 0x%x\n", value);
-      }
-    }
-+ 
-    return TRUE;
-  }
-  
-***************
-*** 1468,1474 ****
-      ret->fmt = fmt;
-  
-      /*ret->vis = vis;*/
-!     ret->vis = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
-  
-      TRACE(" creating context %p (GL context creation delayed)\n", ret);
-      return (HGLRC) ret;
---- 1583,1589 ----
-      ret->fmt = fmt;
-  
-      /*ret->vis = vis;*/
-!     ret->vis = pglXGetVisualFromFBConfig(physDev->display, fmt->fbconfig);
-  
-      TRACE(" creating context %p (GL context creation delayed)\n", ret);
-      return (HGLRC) ret;
-***************
-*** 1496,1502 ****
-      * so make sure it is valid first */
-      if (is_valid_context( ctx ))
-      {
-!         if (ctx->ctx) pglXDestroyContext(gdi_display, ctx->ctx);
-          free_context(ctx);
-      }
-      else
---- 1611,1617 ----
-      * so make sure it is valid first */
-      if (is_valid_context( ctx ))
-      {
-!         if (ctx->ctx) pglXDestroyContext(ctx->physDev->display, ctx->ctx);
-          free_context(ctx);
-      }
-      else
-***************
-*** 1579,1584 ****
---- 1694,1700 ----
-   */
-  static void sync_current_drawable(BOOL updatedc)
-  {
-+ #if 0
-      int dy;
-      int width;
-      int height;
-***************
-*** 1616,1621 ****
---- 1732,1738 ----
-  
-          wine_tsx11_unlock();
-      }
-+ #endif
-  }
-  
-  /**
-***************
-*** 1628,1634 ****
-      HDC hdc = physDev->hdc;
-      DWORD type = GetObjectType(hdc);
-  
-!     TRACE("(%p,%p)\n", hdc, hglrc);
-  
-      if (!has_opengl()) {
-          ERR("No libGL on this box - disabling OpenGL support !\n");
---- 1745,1751 ----
-      HDC hdc = physDev->hdc;
-      DWORD type = GetObjectType(hdc);
-  
-!     TRACE("(%p %p,%p)\n", physDev, hdc, hglrc);
-  
-      if (!has_opengl()) {
-          ERR("No libGL on this box - disabling OpenGL support !\n");
-***************
-*** 1637,1643 ****
-  
-      wine_tsx11_lock();
-      if (hglrc == NULL) {
-!         ret = pglXMakeCurrent(gdi_display, None, NULL);
-          NtCurrentTeb()->glContext = NULL;
-      } else {
-          Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
---- 1754,1760 ----
-  
-      wine_tsx11_lock();
-      if (hglrc == NULL) {
-!         ret = pglXMakeCurrent(physDev->display, None, NULL);
-          NtCurrentTeb()->glContext = NULL;
-      } else {
-          Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
-***************
-*** 1654,1668 ****
-               */
-              TRACE(" Creating GLX Context\n");
-              if(ctx->vis)
-!                 ctx->ctx = pglXCreateContext(gdi_display, ctx->vis, NULL, type == OBJ_MEMDC ? False : True);
-              else /* Create a GLX Context for a pbuffer */
-!                 ctx->ctx = pglXCreateNewContext(gdi_display, ctx->fmt->fbconfig, ctx->fmt->render_type, NULL, True);
-  
-              TRACE(" created a delayed OpenGL context (%p)\n", ctx->ctx);
-          }
-!         TRACE(" make current for dis %p, drawable %p, ctx %p\n", gdi_display, (void*) drawable, ctx->ctx);
-!         ret = pglXMakeCurrent(gdi_display, drawable, ctx->ctx);
-          NtCurrentTeb()->glContext = ctx;
-          if(ret)
-          {
-              ctx->physDev = physDev;
---- 1771,1786 ----
-               */
-              TRACE(" Creating GLX Context\n");
-              if(ctx->vis)
-!                 ctx->ctx = pglXCreateContext(physDev->display, ctx->vis, NULL, type == OBJ_MEMDC ? False : True);
-              else /* Create a GLX Context for a pbuffer */
-!                 ctx->ctx = pglXCreateNewContext(physDev->display, ctx->fmt->fbconfig, ctx->fmt->render_type, NULL, True);
-  
-              TRACE(" created a delayed OpenGL context (%p)\n", ctx->ctx);
-          }
-!         TRACE(" make current for dis %p, drawable %p, ctx %p\n", physDev->display, (void*) drawable, ctx->ctx);
-!         ret = pglXMakeCurrent(physDev->display, drawable, ctx->ctx);
-          NtCurrentTeb()->glContext = ctx;
-+         
-          if(ret)
-          {
-              ctx->physDev = physDev;
-***************
-*** 1711,1720 ****
-              Drawable d_read = get_glxdrawable(hReadDev);
-  
-              if (ctx->ctx == NULL) {
-!                 ctx->ctx = pglXCreateContext(gdi_display, ctx->vis, NULL, GetObjectType(hDrawDev->hdc) == OBJ_MEMDC ? False : True);
-                  TRACE(" created a delayed OpenGL context (%p)\n", ctx->ctx);
-              }
-!             ret = pglXMakeContextCurrent(gdi_display, d_draw, d_read, ctx->ctx);
-              NtCurrentTeb()->glContext = ctx;
-          }
-      }
---- 1829,1838 ----
-              Drawable d_read = get_glxdrawable(hReadDev);
-  
-              if (ctx->ctx == NULL) {
-!                 ctx->ctx = pglXCreateContext(ctx->physDev->display, ctx->vis, NULL, GetObjectType(hDrawDev->hdc) == OBJ_MEMDC ? False : True);
-                  TRACE(" created a delayed OpenGL context (%p)\n", ctx->ctx);
-              }
-!             ret = pglXMakeContextCurrent(ctx->physDev->display, d_draw, d_read, ctx->ctx);
-              NtCurrentTeb()->glContext = ctx;
-          }
-      }
-***************
-*** 1749,1757 ****
-              describeContext(org);
-  
-              if(org->vis)
-!                 org->ctx = pglXCreateContext(gdi_display, org->vis, NULL, GetObjectType(org->physDev->hdc) == OBJ_MEMDC ? False : True);
-              else /* Create a GLX Context for a pbuffer */
-!                 org->ctx = pglXCreateNewContext(gdi_display, org->fmt->fbconfig, org->fmt->render_type, NULL, True);
-              wine_tsx11_unlock();
-              TRACE(" created a delayed OpenGL context (%p) for Wine context %p\n", org->ctx, org);
-          }
---- 1867,1875 ----
-              describeContext(org);
-  
-              if(org->vis)
-!                 org->ctx = pglXCreateContext(org->physDev->display, org->vis, NULL, GetObjectType(org->physDev->hdc) == OBJ_MEMDC ? False : True);
-              else /* Create a GLX Context for a pbuffer */
-!                 org->ctx = pglXCreateNewContext(org->physDev->display, org->fmt->fbconfig, org->fmt->render_type, NULL, True);
-              wine_tsx11_unlock();
-              TRACE(" created a delayed OpenGL context (%p) for Wine context %p\n", org->ctx, org);
-          }
-***************
-*** 1760,1768 ****
-              describeContext(dest);
-              /* Create the destination context with display lists shared */
-              if(dest->vis)
-!                 dest->ctx = pglXCreateContext(gdi_display, dest->vis, org->ctx, GetObjectType(org->physDev->hdc) == OBJ_MEMDC ? False : True);
-              else /* Create a GLX Context for a pbuffer */
-!                 dest->ctx = pglXCreateNewContext(gdi_display, dest->fmt->fbconfig, dest->fmt->render_type, org->ctx, True);
-              wine_tsx11_unlock();
-              TRACE(" created a delayed OpenGL context (%p) for Wine context %p sharing lists with OpenGL ctx %p\n", dest->ctx, dest, org->ctx);
-              return TRUE;
---- 1878,1886 ----
-              describeContext(dest);
-              /* Create the destination context with display lists shared */
-              if(dest->vis)
-!                 dest->ctx = pglXCreateContext(dest->physDev->display, dest->vis, org->ctx, GetObjectType(org->physDev->hdc) == OBJ_MEMDC ? False : True);
-              else /* Create a GLX Context for a pbuffer */
-!                 dest->ctx = pglXCreateNewContext(dest->physDev->display, dest->fmt->fbconfig, dest->fmt->render_type, org->ctx, True);
-              wine_tsx11_unlock();
-              TRACE(" created a delayed OpenGL context (%p) for Wine context %p sharing lists with OpenGL ctx %p\n", dest->ctx, dest, org->ctx);
-              return TRUE;
-***************
-*** 1937,1942 ****
---- 2055,2061 ----
-  
-  static void WINAPI X11DRV_wglDisable(GLenum cap)
-  {
-+ #if 0
-      if (cap == GL_SCISSOR_TEST)
-      {
-         Wine_GLContext *ctx = (Wine_GLContext *) NtCurrentTeb()->glContext;
-***************
-*** 1945,1950 ****
---- 2064,2070 ----
-            ctx->scissor_enabled = FALSE;
-      }
-      else
-+ #endif
-      {
-          wine_tsx11_lock();
-          pglDisable(cap);
-***************
-*** 1954,1959 ****
---- 2074,2080 ----
-  
-  static void WINAPI X11DRV_wglEnable(GLenum cap)
-  {
-+ #if 0
-      if (cap == GL_SCISSOR_TEST)
-      {
-         Wine_GLContext *ctx = (Wine_GLContext *) NtCurrentTeb()->glContext;
-***************
-*** 1962,1967 ****
---- 2083,2089 ----
-             ctx->scissor_enabled = TRUE;
-      }
-      else
-+ #endif
-      {
-          wine_tsx11_lock();
-          pglEnable(cap);
-***************
-*** 2012,2017 ****
---- 2134,2140 ----
-  {
-      GLboolean enabled = False;
-  
-+ #if 0
-      if (cap == GL_SCISSOR_TEST)
-      {
-         Wine_GLContext *ctx = (Wine_GLContext *) NtCurrentTeb()->glContext;
-***************
-*** 2020,2025 ****
---- 2143,2149 ----
-             enabled = ctx->scissor_enabled;
-      }
-      else
-+ #endif
-      {
-          wine_tsx11_lock();
-          enabled = pglIsEnabled(cap);
-***************
-*** 2030,2035 ****
---- 2154,2160 ----
-  
-  static void WINAPI X11DRV_wglScissor(GLint x, GLint y, GLsizei width, GLsizei height)
-  {
-+ #if 0
-      Wine_GLContext *ctx = (Wine_GLContext *) NtCurrentTeb()->glContext;
-  
-      if (ctx)
-***************
-*** 2041,2050 ****
---- 2166,2181 ----
-  
-          sync_current_drawable(TRUE);
-      }
-+ #else
-+     wine_tsx11_lock();
-+     pglScissor(x, y, width, height);
-+     wine_tsx11_unlock();
-+ #endif
-  }
-  
-  static void WINAPI X11DRV_wglViewport(GLint x, GLint y, GLsizei width, GLsizei height)
-  {
-+ #if 0
-      Wine_GLContext *ctx = (Wine_GLContext *) NtCurrentTeb()->glContext;
-  
-      if (ctx)
-***************
-*** 2056,2061 ****
---- 2187,2197 ----
-  
-          sync_current_drawable(TRUE);
-      }
-+ #else
-+     wine_tsx11_lock();
-+     pglViewport(x, y, width, height);
-+     wine_tsx11_unlock();
-+ #endif
-  }
-  
-  /**
-***************
-*** 2327,2332 ****
---- 2463,2469 ----
-  
-      /* The function wglGetPbufferDCARB returns a DC to which the pbuffer can be connected.
-       * All formats in our pixelformat list are compatible with each other and the main drawable. */
-+     physDev->display = object->display;
-      physDev->current_pf = object->fmt->iPixelFormat;
-      physDev->drawable = object->drawable;
-      SetRect( &physDev->drawable_rect, 0, 0, object->width, object->height );
-***************
-*** 3234,3241 ****
---- 3371,3381 ----
-              ret = physDev->bitmap->glxpixmap;
-          }
-      }
-+     else if(physDev->gl_drawable)
-+         ret = physDev->gl_drawable;
-      else
-          ret = physDev->drawable;
-+ 
-      return ret;
-  }
-  
-***************
-*** 3264,3270 ****
-  
-    drawable = get_glxdrawable(physDev);
-    wine_tsx11_lock();
-!   pglXSwapBuffers(gdi_display, drawable);
-    wine_tsx11_unlock();
-  
-    /* FPS support */
---- 3404,3410 ----
-  
-    drawable = get_glxdrawable(physDev);
-    wine_tsx11_lock();
-!   pglXSwapBuffers(physDev->display, drawable);
-    wine_tsx11_unlock();
-  
-    /* FPS support */
-***************
-*** 3285,3290 ****
---- 3425,3431 ----
-    return TRUE;
-  }
-  
-+ 
-  /***********************************************************************
-   *		X11DRV_setup_opengl_visual
-   *
-Only in wine-0.9.43/dlls/winex11.drv: opengl.c.orig
-Only in wine-0.9.43/dlls/winex11.drv: opengl.c.rej
-Only in wine-0.9.43/dlls/winex11.drv: opengl.c~
-diff -rc wine-0.9.43-orig/dlls/winex11.drv/window.c wine-0.9.43/dlls/winex11.drv/window.c
-*** wine-0.9.43-orig/dlls/winex11.drv/window.c	2007-08-10 18:18:12.000000000 +0200
---- wine-0.9.43/dlls/winex11.drv/window.c	2007-08-21 10:20:19.000000000 +0200
-***************
-*** 55,61 ****
---- 55,64 ----
-  
-  static const char whole_window_prop[] = "__wine_x11_whole_window";
-  static const char icon_window_prop[]  = "__wine_x11_icon_window";
-+ static const char gl_display_prop[]   = "__wine_x11_gl_display";
-+ static const char gl_winptr_prop[]    = "__wine_x11_gl_winptr";
-  static const char managed_prop[]      = "__wine_x11_managed";
-+ static const char visible_prop[]      = "__wine_x11_visible";
-  static const char visual_id_prop[]    = "__wine_x11_visual_id";
-  
-  /* for XDG systray icons */
-***************
-*** 604,632 ****
-      BOOL iconic = (style & WS_MINIMIZE) != 0;
-  
-      if (!(data = X11DRV_get_win_data( hwnd ))) return;
-!     if (!data->whole_window || data->whole_window == DefaultRootWindow(display)) return;
-  
-      GetWindowRect( hwnd, &rect );
-  
-      wine_tsx11_lock();
-  
-!     if (!(wm_hints = XGetWMHints( display, data->whole_window ))) wm_hints = XAllocWMHints();
-!     wm_hints->flags |= StateHint | IconPositionHint;
-!     wm_hints->initial_state = iconic ? IconicState : NormalState;
-!     wm_hints->icon_x = rect.left - virtual_screen_rect.left;
-!     wm_hints->icon_y = rect.top - virtual_screen_rect.top;
-!     XSetWMHints( display, data->whole_window, wm_hints );
-! 
-!     if (style & WS_VISIBLE)
-      {
-!         if (iconic)
-!             XIconifyWindow( display, data->whole_window, DefaultScreen(display) );
-!         else
-!             if (X11DRV_is_window_rect_mapped( &rect ))
-!                 XMapWindow( display, data->whole_window );
-      }
-  
-!     XFree(wm_hints);
-      wine_tsx11_unlock();
-  }
-  
---- 607,650 ----
-      BOOL iconic = (style & WS_MINIMIZE) != 0;
-  
-      if (!(data = X11DRV_get_win_data( hwnd ))) return;
-!     if ((!data->whole_window && !data->gl_window) || data->whole_window == DefaultRootWindow(display)) return;
-  
-      GetWindowRect( hwnd, &rect );
-  
-      wine_tsx11_lock();
-  
-!     if (data->gl_window)
-      {
-!         if (style & WS_VISIBLE)
-!         {
-!             if (iconic)
-!                 XUnmapWindow( data->gl_display, data->gl_window );
-!             else
-!                 if (X11DRV_is_window_rect_mapped( &rect ))
-!                     XMapWindow( data->gl_display, data->gl_window );
-!         }
-      }
-  
-!     if (data->whole_window)
-!     {
-!         if (!(wm_hints = XGetWMHints( display, data->whole_window ))) wm_hints = XAllocWMHints();
-!         wm_hints->flags |= StateHint | IconPositionHint;
-!         wm_hints->initial_state = iconic ? IconicState : NormalState;
-!         wm_hints->icon_x = rect.left - virtual_screen_rect.left;
-!         wm_hints->icon_y = rect.top - virtual_screen_rect.top;
-!         XSetWMHints( display, data->whole_window, wm_hints );
-! 
-!         if (style & WS_VISIBLE)
-!         {
-!             if (iconic)
-!                 XIconifyWindow( display, data->whole_window, DefaultScreen(display) );
-!             else
-!                 if (X11DRV_is_window_rect_mapped( &rect ))
-!                     XMapWindow( display, data->whole_window );
-!         }
-! 
-!         XFree(wm_hints);
-!     }
-      wine_tsx11_unlock();
-  }
-  
-***************
-*** 694,699 ****
---- 712,748 ----
-      data->client_rect = *new_client_rect;
-      OffsetRect( &data->client_rect, -data->whole_rect.left, -data->whole_rect.top );
-  
-+     if (data->gl_window)
-+     {
-+         changes.width = data->client_rect.right - data->client_rect.left;
-+         changes.height = data->client_rect.bottom - data->client_rect.top;
-+ 
-+         if ( changes.width > 0 && changes.height > 0 )
-+         {
-+             POINT pt;
-+             pt.x = data->gl_offset->left;
-+             pt.y = data->gl_offset->top;
-+             if (data->hwnd != data->gl_parent)
-+                 MapWindowPoints( data->hwnd, data->gl_parent, &pt, 1 );
-+ 
-+             changes.x = pt.x;
-+             changes.y = pt.y;
-+ 
-+             TRACE( "setting gl_win %lx pos %d,%d,%dx%d\n",
-+                    data->gl_window, changes.x, changes.y,
-+                    changes.width, changes.height );
-+ 
-+             wine_tsx11_lock();
-+             XReconfigureWMWindow( data->gl_display, data->gl_window,
-+                                   DefaultScreen(data->gl_display),
-+                                   CWX|CWY|CWWidth|CWHeight, &changes );
-+             wine_tsx11_unlock();
-+         }
-+ 
-+         if (!data->whole_window)
-+             return;
-+     }
-+ 
-      if (!data->whole_window || data->lock_changes) return;
-  
-      mask = get_window_changes( &changes, &old_whole_rect, &data->whole_rect );
-***************
-*** 905,910 ****
---- 954,963 ----
-      if (!(data = X11DRV_get_win_data( hwnd ))) return;
-  
-      free_window_dce( data );
-+     wine_tsx11_lock();
-+ 
-+     if (data->gl_window) XDestroyWindow( data->gl_display, data->gl_window );
-+     wine_tsx11_unlock();
-      destroy_whole_window( display, data );
-      destroy_icon_window( display, data );
-  
-***************
-*** 927,932 ****
---- 980,989 ----
-          data->hwnd          = hwnd;
-          data->whole_window  = 0;
-          data->icon_window   = 0;
-+         data->gl_window     = 0;
-+         data->gl_parent     = 0;
-+         data->gl_offset     = NULL;
-+         data->gl_display    = NULL;
-          data->xic           = 0;
-          data->managed       = FALSE;
-          data->dce           = NULL;
-***************
-*** 1056,1061 ****
---- 1113,1147 ----
-      /* get class or window DC if needed */
-      alloc_window_dce( data );
-  
-+     if (!data->whole_window)
-+     {
-+         HWND parent = hwnd;
-+         while ((parent = GetAncestor( parent, GA_PARENT )))
-+         {
-+             if (X11DRV_get_whole_window( parent ))
-+             {
-+                 void *params[2];
-+                 SendMessageW( parent, WM_X11DRV_GET_PARENT_INFO, 0, (LPARAM)params );
-+                 data->gl_parent = parent;
-+                 data->gl_offset = params[0];
-+                 data->gl_display = params[1];
-+                 break;
-+             }
-+         }
-+         if (!parent)
-+             ERR( "Could not find drawable parent for HWND %p!\n", hwnd );
-+     }
-+     else
-+     {
-+         data->gl_parent = data->hwnd;
-+         data->gl_offset = &data->client_rect;
-+         data->gl_display = thread_display();
-+     }
-+ 
-+     SetPropA( hwnd, gl_display_prop, (HANDLE)data->gl_display );
-+     SetPropA( hwnd, gl_winptr_prop, (HANDLE)&data->gl_window );
-+     SetPropA( hwnd, visible_prop, (HANDLE)!!(cs->style&WS_VISIBLE) );
-+ 
-      /* Call the WH_CBT hook */
-  
-      /* the window style passed to the hook must be the real window style,
-***************
-*** 1216,1221 ****
---- 1302,1394 ----
-  
-  
-  /***********************************************************************
-+  *		X11DRV_get_gl_display
-+  *
-+  * Return the X display associated with the full area of a window
-+  */
-+ Display *X11DRV_get_gl_display( HWND hwnd )
-+ {
-+     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
-+ 
-+     if (!data) return (Display *)GetPropA( hwnd, gl_display_prop );
-+     return data->gl_display;
-+ }
-+ 
-+ 
-+ /***********************************************************************
-+  *		X11DRV_get_visible
-+  *
-+  * Returns if the window has the WS_VISIBLE style or not
-+  */
-+ BOOL X11DRV_get_visible( HWND hwnd )
-+ {
-+     return (BOOL)GetPropA( hwnd, visible_prop );
-+ }
-+ 
-+ 
-+ /***********************************************************************
-+  *		X11DRV_set_visible
-+  *
-+  * Stores the WS_VISIBLE style for the window in a prop
-+  */
-+ BOOL X11DRV_set_visible( HWND hwnd, BOOL is_visible )
-+ {
-+     return (BOOL)SetPropA( hwnd, visible_prop, (HANDLE)is_visible );
-+ }
-+ 
-+ 
-+ /***********************************************************************
-+  *		X11DRV_set_gl_window
-+  *
-+  * Retrieve the OpenGL child window from the HWND
-+  */
-+ Window X11DRV_get_gl_window( HWND hwnd )
-+ {
-+     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
-+ 
-+     if (!data)
-+     {
-+         Window *WinPtr = (Window *)GetPropA( hwnd, gl_winptr_prop );
-+         return *WinPtr;
-+     }
-+     else
-+     {
-+         return data->gl_window;
-+     }
-+ 
-+     return 0;
-+ }
-+ 
-+ 
-+ /***********************************************************************
-+  *		X11DRV_set_gl_window
-+  *
-+  * Sets the OpenGL child window for the HWND
-+  */
-+ BOOL X11DRV_set_gl_window( HWND hwnd, Window window )
-+ {
-+     struct x11drv_win_data *data = X11DRV_get_win_data( hwnd );
-+ 
-+     if (!data)
-+     {
-+         Window *WinPtr = (Window *)GetPropA( hwnd, gl_winptr_prop );
-+         if (WinPtr)
-+         {
-+             *WinPtr = window;
-+             return TRUE;
-+         }
-+     }
-+     else
-+     {
-+         data->gl_window = window;
-+         return TRUE;
-+     }
-+ 
-+     return FALSE;
-+ }
-+ 
-+ 
-+ /***********************************************************************
-   *		X11DRV_get_ic
-   *
-   * Return the X input context associated with a window
-Only in wine-0.9.43/dlls/winex11.drv: window.c.orig
-diff -rc wine-0.9.43-orig/dlls/winex11.drv/winpos.c wine-0.9.43/dlls/winex11.drv/winpos.c
-*** wine-0.9.43-orig/dlls/winex11.drv/winpos.c	2007-08-10 18:18:12.000000000 +0200
---- wine-0.9.43/dlls/winex11.drv/winpos.c	2007-08-21 10:20:19.000000000 +0200
-***************
-*** 142,158 ****
-  
-      if (changed & WS_VISIBLE)
-      {
-!         if (data->whole_window && X11DRV_is_window_rect_mapped( &data->window_rect ))
-          {
-              if (new_style & WS_VISIBLE)
-              {
-                  TRACE( "mapping win %p\n", hwnd );
-!                 X11DRV_sync_window_style( display, data );
-!                 X11DRV_set_wm_hints( display, data );
-!                 wine_tsx11_lock();
-!                 XMapWindow( display, data->whole_window );
-!                 wine_tsx11_unlock();
-              }
-              /* we don't unmap windows, that causes trouble with the window manager */
-          }
-          invalidate_dce( hwnd, &data->window_rect );
---- 142,171 ----
-  
-      if (changed & WS_VISIBLE)
-      {
-!         if ((data->whole_window || data->gl_window) &&
-!             X11DRV_is_window_rect_mapped( &data->window_rect ))
-          {
-              if (new_style & WS_VISIBLE)
-              {
-                  TRACE( "mapping win %p\n", hwnd );
-!                 if (data->gl_window)
-!                 {
-!                     wine_tsx11_lock();
-!                     XMapWindow( data->gl_display, data->gl_window );
-!                     wine_tsx11_unlock();
-!                 }
-!                 if (data->whole_window)
-!                 {
-!                     X11DRV_sync_window_style( display, data );
-!                     X11DRV_set_wm_hints( display, data );
-!                     wine_tsx11_lock();
-!                     XMapWindow( display, data->whole_window );
-!                     wine_tsx11_unlock();
-!                 }
-!                 X11DRV_set_visible( hwnd, 1 );
-              }
-+             else
-+                 X11DRV_set_visible( hwnd, 0 );
-              /* we don't unmap windows, that causes trouble with the window manager */
-          }
-          invalidate_dce( hwnd, &data->window_rect );
-***************
-*** 287,292 ****
---- 300,307 ----
-      }
-      SERVER_END_REQ;
-  
-+ //needs to be cleaned up
-+ X11DRV_set_visible ( hwnd, (new_style&WS_VISIBLE)?1 : 0 );
-      if (win == WND_DESKTOP || data->whole_window == DefaultRootWindow(gdi_display))
-      {
-          data->whole_rect = data->client_rect = data->window_rect = *rectWindow;
-***************
-*** 347,360 ****
-          }
-  
-  
-!         if (data->whole_window && !data->lock_changes)
-          {
-              if ((old_style & WS_VISIBLE) && !(new_style & WS_VISIBLE))
-              {
-                  /* window got hidden, unmap it */
-                  TRACE( "unmapping win %p\n", hwnd );
-                  wine_tsx11_lock();
-!                 XUnmapWindow( display, data->whole_window );
-                  wine_tsx11_unlock();
-              }
-              else if ((new_style & WS_VISIBLE) && !X11DRV_is_window_rect_mapped( rectWindow ))
---- 362,378 ----
-          }
-  
-  
-!         if ((data->whole_window || data->gl_window) && !data->lock_changes)
-          {
-              if ((old_style & WS_VISIBLE) && !(new_style & WS_VISIBLE))
-              {
-                  /* window got hidden, unmap it */
-                  TRACE( "unmapping win %p\n", hwnd );
-                  wine_tsx11_lock();
-!                 if (data->gl_window)
-!                     XUnmapWindow( data->gl_display, data->gl_window );
-!                 if (data->whole_window)
-!                     XUnmapWindow( display, data->whole_window );
-                  wine_tsx11_unlock();
-              }
-              else if ((new_style & WS_VISIBLE) && !X11DRV_is_window_rect_mapped( rectWindow ))
-***************
-*** 362,375 ****
-                  /* resizing to zero size or off screen -> unmap */
-                  TRACE( "unmapping zero size or off-screen win %p\n", hwnd );
-                  wine_tsx11_lock();
-!                 XUnmapWindow( display, data->whole_window );
-                  wine_tsx11_unlock();
-              }
-          }
-  
-          X11DRV_sync_window_position( display, data, swp_flags, rectClient, &new_whole_rect );
-  
-!         if (data->whole_window && !data->lock_changes)
-          {
-              BOOL new_fs_state, mapped = FALSE;
-  
---- 380,396 ----
-                  /* resizing to zero size or off screen -> unmap */
-                  TRACE( "unmapping zero size or off-screen win %p\n", hwnd );
-                  wine_tsx11_lock();
-!                 if (data->gl_window)
-!                     XUnmapWindow( data->gl_display, data->gl_window );
-!                 if (data->whole_window)
-!                     XUnmapWindow( display, data->whole_window );
-                  wine_tsx11_unlock();
-              }
-          }
-  
-          X11DRV_sync_window_position( display, data, swp_flags, rectClient, &new_whole_rect );
-  
-!         if ((data->whole_window || data->gl_window) && !data->lock_changes)
-          {
-              BOOL new_fs_state, mapped = FALSE;
-  
-***************
-*** 380,402 ****
-                  {
-                      /* window got shown, map it */
-                      TRACE( "mapping win %p\n", hwnd );
-!                     X11DRV_sync_window_style( display, data );
-!                     X11DRV_set_wm_hints( display, data );
-!                     wine_tsx11_lock();
-!                     XMapWindow( display, data->whole_window );
-!                     XFlush( display );
-!                     wine_tsx11_unlock();
-!                     mapped = TRUE;
-                  }
-                  else if ((swp_flags & (SWP_NOSIZE | SWP_NOMOVE)) != (SWP_NOSIZE | SWP_NOMOVE))
-                  {
-                      /* resizing from zero size to non-zero -> map */
-                      TRACE( "mapping non zero size or off-screen win %p\n", hwnd );
-                      wine_tsx11_lock();
-!                     XMapWindow( display, data->whole_window );
-!                     XFlush( display );
-                      wine_tsx11_unlock();
--                     mapped = TRUE;
-                  }
-                  SetRect( &old_screen_rect, 0, 0, screen_width, screen_height );
-                  if (fullscreen_state_changed( data, &old_client_rect, &old_screen_rect, &new_fs_state ) || mapped)
---- 401,441 ----
-                  {
-                      /* window got shown, map it */
-                      TRACE( "mapping win %p\n", hwnd );
-!                     if (data->gl_window)
-!                     {
-!                         wine_tsx11_lock();
-!                         XMapWindow( data->gl_display, data->gl_window );
-!                         XFlush( display );
-!                         wine_tsx11_unlock();
-!                     }
-!                     if (data->whole_window)
-!                     {
-!                         X11DRV_sync_window_style( display, data );
-!                         X11DRV_set_wm_hints( display, data );
-!                         wine_tsx11_lock();
-!                         XMapWindow( display, data->whole_window );
-!                         XFlush( display );
-!                         wine_tsx11_unlock();
-!                         mapped = TRUE;
-!                     }
-                  }
-                  else if ((swp_flags & (SWP_NOSIZE | SWP_NOMOVE)) != (SWP_NOSIZE | SWP_NOMOVE))
-                  {
-                      /* resizing from zero size to non-zero -> map */
-                      TRACE( "mapping non zero size or off-screen win %p\n", hwnd );
-                      wine_tsx11_lock();
-!                     if (data->gl_window)
-!                     {
-!                         XMapWindow( data->gl_display, data->gl_window );
-!                         XFlush( data->gl_display );
-!                     }
-!                     if (data->whole_window)
-!                     {
-!                         XMapWindow( display, data->whole_window );
-!                         mapped = TRUE;
-!                         XFlush( display );
-!                     }
-                      wine_tsx11_unlock();
-                  }
-                  SetRect( &old_screen_rect, 0, 0, screen_width, screen_height );
-                  if (fullscreen_state_changed( data, &old_client_rect, &old_screen_rect, &new_fs_state ) || mapped)
-Only in wine-0.9.43/dlls/winex11.drv: winpos.c.orig
-diff -rc wine-0.9.43-orig/dlls/winex11.drv/x11drv.h wine-0.9.43/dlls/winex11.drv/x11drv.h
-*** wine-0.9.43-orig/dlls/winex11.drv/x11drv.h	2007-08-10 18:18:12.000000000 +0200
---- wine-0.9.43/dlls/winex11.drv/x11drv.h	2007-08-21 10:20:19.000000000 +0200
-***************
-*** 122,130 ****
---- 122,132 ----
-    /* X physical device */
-  typedef struct
-  {
-+     Display      *display;
-      HDC           hdc;
-      GC            gc;          /* X Window GC */
-      Drawable      drawable;
-+     Drawable      gl_drawable;
-      RECT          dc_rect;       /* DC rectangle relative to drawable */
-      RECT          drawable_rect; /* Drawable rectangle relative to screen */
-      HRGN          region;        /* Device region (visible region & clip region) */
-***************
-*** 633,639 ****
-  enum x11drv_window_messages
-  {
-      WM_X11DRV_ACQUIRE_SELECTION = 0x80001000,
-!     WM_X11DRV_DELETE_WINDOW
-  };
-  
-  /* x11drv private window data */
---- 635,642 ----
-  enum x11drv_window_messages
-  {
-      WM_X11DRV_ACQUIRE_SELECTION = 0x80001000,
-!     WM_X11DRV_DELETE_WINDOW,
-!     WM_X11DRV_GET_PARENT_INFO
-  };
-  
-  /* x11drv private window data */
-***************
-*** 642,647 ****
---- 645,654 ----
-      HWND        hwnd;           /* hwnd that this private data belongs to */
-      Window      whole_window;   /* X window for the complete window */
-      Window      icon_window;    /* X window for the icon */
-+     Window      gl_window;      /* X window for OpenGL display */
-+     HWND        gl_parent;      /* hwnd that has the drawable the OpenGL display is from */
-+     RECT       *gl_offset;      /* The OpenGL parent window's client_rect */
-+     Display    *gl_display;     /* The display the OpenGL window uses */
-      RECT        window_rect;    /* USER window rectangle relative to parent */
-      RECT        whole_rect;     /* X window rectangle for the whole window relative to parent */
-      RECT        client_rect;    /* client area relative to whole window */
-***************
-*** 655,666 ****
---- 662,679 ----
-  
-  extern struct x11drv_win_data *X11DRV_get_win_data( HWND hwnd );
-  extern Window X11DRV_get_whole_window( HWND hwnd );
-+ extern Display *X11DRV_get_gl_display( HWND hwnd );
-+ extern Window X11DRV_get_gl_window( HWND hwnd );
-+ extern BOOL X11DRV_set_gl_window( HWND hwnd, Window window );
-+ extern BOOL X11DRV_get_visible( HWND hwnd );
-+ extern BOOL X11DRV_set_visible( HWND hwnd, BOOL is_visible );
-  extern BOOL X11DRV_is_window_rect_mapped( const RECT *rect );
-  extern XIC X11DRV_get_ic( HWND hwnd );
-  
-  extern void alloc_window_dce( struct x11drv_win_data *data );
-  extern void free_window_dce( struct x11drv_win_data *data );
-  extern void invalidate_dce( HWND hwnd, const RECT *rect );
-+ extern HWND hwnd_from_dce( struct dce *dce );
-  
-  /* X context to associate a hwnd to an X window */
-  extern XContext winContext;
-Only in wine-0.9.43/dlls/winex11.drv: x11drv.h.orig
diff --git a/pkgs/misc/gxemul/default.nix b/pkgs/misc/gxemul/default.nix
index e7fdc96d32e..e7d0c92a1c5 100644
--- a/pkgs/misc/gxemul/default.nix
+++ b/pkgs/misc/gxemul/default.nix
@@ -12,7 +12,7 @@ let
     optionals = ["libX11"];
     defaultFlags = [ "demos" "doc" ];
   };
-in args.stdenv.mkDerivation {
+in stdenv.mkDerivation {
 
   inherit name;
   inherit (co) /* flags */ buildInputs configureFlags;
diff --git a/pkgs/misc/maven/maven-2.nix b/pkgs/misc/maven/maven-2.nix
new file mode 100644
index 00000000000..be84f212e8b
--- /dev/null
+++ b/pkgs/misc/maven/maven-2.nix
@@ -0,0 +1,21 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "maven-2.0.8-bin";
+
+  src = fetchurl {
+    # TODO mirrors 
+    url = http://apache.linux-mirror.org/maven/binaries/apache-maven-2.0.8-bin.tar.bz2;
+    sha256 = "1wasvqplw7xk04j38vsq94zbrlpdg2k4348bg8730snr6zgaasai";
+  };
+
+  phases = "unpackPhase installPhase";
+
+  installPhase = "
+    ensureDir \$out; mv * \$out
+  ";
+
+  meta = { 
+      description = "Java build tool";
+      homepage = "apache.org";
+    };
+}
diff --git a/pkgs/misc/ntfs-3g/default.nix b/pkgs/misc/ntfs-3g/default.nix
index a319423e99c..5f6a0bdbc5f 100644
--- a/pkgs/misc/ntfs-3g/default.nix
+++ b/pkgs/misc/ntfs-3g/default.nix
@@ -1,15 +1,16 @@
 args: with args;
-stdenv.mkDerivation {
-  name = "ntfs3g-1.826";
+stdenv.mkDerivation rec {
+  name = "ntfs-3g-1.1104";
   src = fetchurl {
-    url = http://www.ntfs-3g.org/ntfs-3g-1.826.tgz;
-    sha256 = "0anxg4nzhc8d8wvxgw78bc2pb2ciim8mflxgcac9p8d3djwdsxyp";
+    url = "${meta.homepage}/${name}.tgz";
+    sha256 = "1m96c3vxm051lpy3kyik9s0m390rj6ngm11xmahfhw61794jzbyp";
   };
   buildInputs = [fuse pkgconfig];
   preConfigure="sed -e 's:/sbin:@sbindir@:' -i src/Makefile.in";
   configureFlags="--enable-shared --disable-static --disable-ldconfig --exec-prefix=\${prefix}";
 
   meta = {
+    homepage = http://www.ntfs-3g.org;
     description = "FUSE-base ntfs driver with full write support";
   };
 }
diff --git a/pkgs/misc/ntfsprogs/default.nix b/pkgs/misc/ntfsprogs/default.nix
new file mode 100644
index 00000000000..8f2e6839309
--- /dev/null
+++ b/pkgs/misc/ntfsprogs/default.nix
@@ -0,0 +1,16 @@
+args: with args;
+args.stdenv.mkDerivation {
+  name = "ntfsprogs-2.0.0";
+
+  src = fetchurl {
+    name = "ntfsprogs-2.0.0.tar.bz2";
+    url = "http://garr.dl.sourceforge.net/sourceforge/linux-ntfs/ntfsprogs-2.0.0.tar.bz2";
+    sha256 = "ad36e19706c7303b10aa0a9bf2c2dd0309b91cd0171f1c9eb361d94a85017432";
+  };
+
+  meta = {
+      description = "ntfs utilities";
+      homepage = http://sourceforge.net/projects/linux-ntfs;
+      license = "GPL";
+  };
+}
diff --git a/pkgs/misc/screensavers/xlockmore/default.nix b/pkgs/misc/screensavers/xlockmore/default.nix
new file mode 100644
index 00000000000..025a2c044eb
--- /dev/null
+++ b/pkgs/misc/screensavers/xlockmore/default.nix
@@ -0,0 +1,30 @@
+{stdenv, fetchurl, pam, x11, freetype}:
+
+stdenv.mkDerivation {
+  # FIXME: Password authentication doesn't work!
+
+  name = "xlockmore-5.24";
+  src = fetchurl {
+    url = http://www.tux.org/~bagleyd/xlock/xlockmore-5.24.tar.bz2;
+    sha256 = "dbee7bbe35c08afcbe419603fae60aee7898bbd85a3175dc788f02ddbb9f5a39";
+  };
+
+  # Optionally, it can use GTK+ as well.
+  buildInputs = [pam x11 freetype];
+
+  # The `xlock' program needs to be linked against Glibc's
+  # `libgcrypt', which contains `crypt(3)'.
+  patches = [ ./makefile-libcrypt.patch ];
+
+  # Don't try to install `xlock' setuid.  Instead, the user should add
+  # it to `security.extraSetuidPrograms'.
+  configureFlags = 
+    "--disable-setuid " + "--enable-pam " +
+    "--enable-appdefaultdir=$out/lib/X11/app-defaults";
+
+  meta = {
+    description = "Xlockmore, a screen locker for the X Window System.";
+    homepage = http://www.tux.org/~bagleyd/xlockmore.html;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/misc/screensavers/xlockmore/makefile-libcrypt.patch b/pkgs/misc/screensavers/xlockmore/makefile-libcrypt.patch
new file mode 100644
index 00000000000..df31a00a13b
--- /dev/null
+++ b/pkgs/misc/screensavers/xlockmore/makefile-libcrypt.patch
@@ -0,0 +1,11 @@
+--- xlockmore-5.24/modes/Makefile.in	2007-01-22 23:02:07.000000000 +0100
++++ xlockmore-5.24/modes/Makefile.in	2008-02-11 17:24:34.000000000 +0100
+@@ -326,7 +326,7 @@ CFLAGS = @CFLAGS@
+ CXXFLAGS = @CXXFLAGS@
+ #CFLAGS = -O
+ #CFLAGS = -g
+-XLOCKLDFLAGS = @XLOCKLDFLAGS@ $(CHECKLDFLAG)
++XLOCKLDFLAGS = @XLOCKLDFLAGS@ $(CHECKLDFLAG) -lcrypt
+ XLIBS = @XLIBS@
+ XLOCKLIBS = $(MODULELIB) @XLOCKLIBS@
+ 
diff --git a/pkgs/misc/tex/auctex/default.nix b/pkgs/misc/tex/auctex/default.nix
index 68599f4b246..117ccf9e3da 100644
--- a/pkgs/misc/tex/auctex/default.nix
+++ b/pkgs/misc/tex/auctex/default.nix
@@ -1,5 +1,5 @@
 { stdenv, fetchurl, emacs, tetex }:
-
+ 
 stdenv.mkDerivation {
   name = "auctex-11.84";
   meta = {
@@ -10,5 +10,6 @@ stdenv.mkDerivation {
     url = http://ftp.gnu.org/pub/gnu/auctex/auctex-11.84.tar.gz;
     md5 = "73970c51221524442c11cde13d0584e9";
   };
+  configureFlags="--with-lispdir=\${out}/emacs/site-lisp --disable-preview";
   buildInputs = [ emacs tetex ];
 }
diff --git a/pkgs/misc/tex/nix/find-includes.pl b/pkgs/misc/tex/nix/find-includes.pl
index 649b16dc35f..9e5fd112bac 100644
--- a/pkgs/misc/tex/nix/find-includes.pl
+++ b/pkgs/misc/tex/nix/find-includes.pl
@@ -59,6 +59,7 @@ while (scalar @workset > 0) {
 	if (/\\input\{(.*)\}/) {
 	    my $fn2 = $1;
             die "absolute path! $fn2" if substr($fn2, 0, 1) eq "/";
+	    push @workset, "$path/$fn2.tex";
 	    push @workset, "$path/$fn2";
 	} elsif (/\\usepackage(\[.*\])?\{(.*)\}/) {
 	    my $fn2 = $2;
diff --git a/pkgs/misc/trac/builder.sh b/pkgs/misc/trac/builder.sh
index a3e97e178a0..76bf0612334 100644
--- a/pkgs/misc/trac/builder.sh
+++ b/pkgs/misc/trac/builder.sh
@@ -1,5 +1,4 @@
 source $stdenv/setup
-source $makeWrapper
 
 unpackPhase
 mkdir -p $out
@@ -7,7 +6,6 @@ cd $name
 $python/bin/python setup.py install --prefix=$out
 
 for i in $(cd $out/bin && ls); do
-	mv $out/bin/$i $out/bin/.orig-$i
-	makeWrapper $out/bin/.orig-$i $out/bin/$i \
-		--set PYTHONPATH "$python/site-packages:$out/lib/python2.4/site-packages:$pysqlite/lib/python2.4/site-packages:$subversion/lib/svn-python:$clearsilver/site-packages"
+    wrapProgram $out/bin/$i \
+        --prefix PYTHONPATH : "$(toPythonPath $python):$(toPythonPath $out):$(toPythonPath $pysqlite):$subversion/lib/svn-python:$clearsilver/site-packages"
 done
diff --git a/pkgs/misc/trac/default.nix b/pkgs/misc/trac/default.nix
index c456c51daff..b93c36843d3 100644
--- a/pkgs/misc/trac/default.nix
+++ b/pkgs/misc/trac/default.nix
@@ -3,13 +3,12 @@
 assert stdenv.system == "i686-linux";
 
 stdenv.mkDerivation {
-	name = "trac-0.9.5";
-	src = fetchurl {
-		url = "http://ftp.edgewall.com/pub/trac/trac-0.9.5.tar.gz";
-		md5 = "3b7d708eaf905cc6ba2b6b10a09a8cf4";
-	};
-	builder = ./builder.sh;
-	inherit stdenv python subversion clearsilver sqlite pysqlite makeWrapper;
+  name = "trac-0.9.5";
+  src = fetchurl {
+    url = "http://ftp.edgewall.com/pub/trac/trac-0.9.5.tar.gz";
+    md5 = "3b7d708eaf905cc6ba2b6b10a09a8cf4";
+  };
+  builder = ./builder.sh;
+  buildInputs = [makeWrapper];
+  inherit stdenv python subversion clearsilver sqlite pysqlite;
 }
-
-
diff --git a/pkgs/misc/xsane/default.nix b/pkgs/misc/xsane/default.nix
index fd7828696d4..e389f17eb76 100644
--- a/pkgs/misc/xsane/default.nix
+++ b/pkgs/misc/xsane/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl, saneBackends, saneFrontends,
 	libX11, gtk, pkgconfig, libusb ? null}:
 stdenv.mkDerivation {
-  name = "xsane-0.97";
+  name = "xsane-0.995";
 
   src = fetchurl {
-    url = ftp://ftp.sane-project.org/pub/sane/xsane/xsane-0.97.tar.gz;
-    md5 = "3d1f889d88c3462594febd53be58c561";
+    url = ftp://ftp.sane-project.org/pub/sane/xsane/xsane-0.995.tar.gz;
+    sha256 = "02rl5bkk3z3k6s04ki14l12vsl5jnx4mri66m1hl799m7hjl5836";
   };
 
   buildInputs = [saneBackends saneFrontends libX11 gtk pkgconfig ] ++
diff --git a/pkgs/os-specific/linux/alsa/library/default.nix b/pkgs/os-specific/linux/alsa/library/default.nix
index 32df29d722f..6ab8143c7ab 100644
--- a/pkgs/os-specific/linux/alsa/library/default.nix
+++ b/pkgs/os-specific/linux/alsa/library/default.nix
@@ -6,4 +6,8 @@ stdenv.mkDerivation {
     url = ftp://ftp.alsa-project.org/pub/lib/alsa-lib-1.0.14.tar.bz2;
 	sha256 = "18xhm53adgss20jnva2nfl9gk46kb5an6ah820pazqn0ykd97rh1";
   };
+
+  meta = {
+	  homepage = http://www.alsa-project.org;
+  };
 }
diff --git a/pkgs/os-specific/linux/alsa/utils/default.nix b/pkgs/os-specific/linux/alsa/utils/default.nix
index ccc49432566..658d8d8e9f7 100644
--- a/pkgs/os-specific/linux/alsa/utils/default.nix
+++ b/pkgs/os-specific/linux/alsa/utils/default.nix
@@ -7,4 +7,8 @@ stdenv.mkDerivation {
     sha256 = "1jx5bwa8abx7aih4lymx4bnrmyip2yb0rp1mza97wpni1q7n6z9h";
   };
   buildInputs = [alsaLib ncurses gettext];
+
+  meta = {
+	  homepage = http://www.alsa-project.org;
+  };
 }
diff --git a/pkgs/os-specific/linux/atheros/0.9.3.3.nix b/pkgs/os-specific/linux/atheros/0.9.3.3.nix
new file mode 100644
index 00000000000..419c136bed2
--- /dev/null
+++ b/pkgs/os-specific/linux/atheros/0.9.3.3.nix
@@ -0,0 +1,35 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://downloads.sourceforge.net/madwifi/madwifi-0.9.3.3.tar.bz2;
+			sha256 = "1dq56dx81wfhpgipbrl3gk2is3g1xvysx2pl6vxyj0dhslkcnf3y";
+		};
+
+		buildInputs = [];
+		configureFlags = [];
+		makeFlags = [''KERNELPATH=${kernel}/lib/modules/*/build'' ''DESTDIR=$out''];
+		patchAR2425x86 = ""; /*(if args ? pci001c_rev01 && args.pci001c_rev01 then
+		fetchurl {
+			url = http://madwifi.org/attachment/ticket/1679/madwifi-ng-0933.ar2425.20071130.i386.patch?format=raw;
+			name = "madwifi-AR2425-x86.patch";
+			sha256 = "11xpx5g9w7ilagvj60prc3s8a3x0n5n4mr0b7nh0lxwrbjdgjjfg";
+		} else "")*/;
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+doPatch = FullDepEntry (if patchAR2425x86 !="" then ''
+	cd hal
+	patch -Np1 -i ${patchAR2425x86}
+'' else "") [minInit doUnpack];
+in
+stdenv.mkDerivation rec {
+	name = "atheros-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doPatch doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Atheros WiFi driver.
+";
+	};
+}
diff --git a/pkgs/os-specific/linux/atheros/r2756.nix b/pkgs/os-specific/linux/atheros/r2756.nix
new file mode 100644
index 00000000000..031404b0395
--- /dev/null
+++ b/pkgs/os-specific/linux/atheros/r2756.nix
@@ -0,0 +1,36 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://snapshots.madwifi.org/madwifi-ng/madwifi-ng-r2756-20071018.tar.gz;
+			sha256 = "0mm1kx9pjvvla792rv7k48yhsa0fpzvd1717g9xzazjsz2mqwzyv";
+		};
+
+		buildInputs = [];
+		configureFlags = [];
+		makeFlags = [''KERNELPATH=${kernel}/lib/modules/*/build'' ''DESTDIR=$out''];
+		patchAR2425x86 = (if args ? pci001c_rev01 && args.pci001c_rev01 then
+		fetchurl {
+			url = http://madwifi.org/attachment/ticket/1679/madwifi-ng-0933.ar2425.20071130.i386.patch?format=raw;
+			name = "madwifi-AR2425-x86.patch";
+			sha256 = "11xpx5g9w7ilagvj60prc3s8a3x0n5n4mr0b7nh0lxwrbjdgjjfg";
+		} else "");
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+doPatch = FullDepEntry (if patchAR2425x86 !="" then ''
+	cd hal
+	patch -Np1 -i ${patchAR2425x86}
+	cd ..
+'' else "") [minInit doUnpack];
+in
+stdenv.mkDerivation rec {
+	name = "atheros-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doPatch doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Atheros WiFi driver.
+";
+	};
+}
diff --git a/pkgs/os-specific/linux/atheros/r3122.nix b/pkgs/os-specific/linux/atheros/r3122.nix
new file mode 100644
index 00000000000..e9fb7bab01a
--- /dev/null
+++ b/pkgs/os-specific/linux/atheros/r3122.nix
@@ -0,0 +1,23 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://snapshots.madwifi.org/madwifi-ng/madwifi-ng-r3122-20080109.tar.gz;
+			sha256 = "188258c6q96n8lb57c0cqsvxp47psninirdax13w4yd07v1rymwd";
+		};
+
+		buildInputs = [];
+		configureFlags = [];
+		makeFlags = [''KERNELPATH=${kernel}/lib/modules/*/build'' ''DESTDIR=$out''];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "atheros-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Atheros WiFi driver.
+";
+	};
+}
diff --git a/pkgs/os-specific/linux/aufs/default.nix b/pkgs/os-specific/linux/aufs/default.nix
new file mode 100644
index 00000000000..2ce510a5b9b
--- /dev/null
+++ b/pkgs/os-specific/linux/aufs/default.nix
@@ -0,0 +1,38 @@
+{stdenv, fetchurl, kernel}:
+
+stdenv.mkDerivation {
+  name = "aufs-20080128";
+  
+  src = fetchurl {
+    url = http://nix.cs.uu.nl/dist/tarballs/aufs-20080128.tar.bz2;
+    sha256 = "0732zp6wfss09x9d6n0a3v65rifn739m9nffi5d3952vglg4va6l";
+  };
+
+  buildPhase = ''
+
+    kernelVersion=$(cd ${kernel}/lib/modules && ls)
+    kernelBuild=$(echo ${kernel}/lib/modules/$kernelVersion/source)
+    tar xvfj ${kernel.src}
+    kernelSource=$(echo $(pwd)/linux-*)
+    cp -prd $kernelBuild/* $kernelSource
+  
+    substituteInPlace fs/aufs/Makefile
+    make KDIR=$kernelSource -f local.mk
+  '';
+
+  installPhase = ''
+    ensureDir $out/bin
+    cp util/aulchown $out/bin
+
+    ensureDir $out/share/man/man5
+    cp util/aufs.5 $out/share/man/man5
+
+    ensureDir $out/lib/modules/$kernelVersion/misc
+    cp aufs.ko $out/lib/modules/$kernelVersion/misc
+  '';
+
+  meta = {
+    description = "Another Unionfs implementation for Linux";
+    homepage = http://aufs.sourceforge.net/;
+  };
+}
diff --git a/pkgs/os-specific/linux/bridge_utils/default.nix b/pkgs/os-specific/linux/bridge_utils/default.nix
new file mode 100644
index 00000000000..b4f5efce22f
--- /dev/null
+++ b/pkgs/os-specific/linux/bridge_utils/default.nix
@@ -0,0 +1,19 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "bridge-utils-1.2";
+
+  src = fetchurl {
+    url = mirror://sourceforge/bridge/bridge-utils-1.2.tar.gz;
+    sha256 = "0jg3z51c2c34byg4zi39j9g4b66js5kanjhid77hpa0jdfmryfy9";
+  };
+
+  buildInputs = [autoconf automake];
+
+  preConfigure="autoreconf";
+
+  meta = { 
+      description = "http://sourceforge.net/projects/bridge/";
+      homepage = [ "http://www.linux-foundation.org/en/Net:Bridge/" "http://sourceforge.net/projects/bridge/" ];
+      license = "GPL";
+  };
+}
diff --git a/pkgs/os-specific/linux/dietlibc/default.nix b/pkgs/os-specific/linux/dietlibc/default.nix
index 9a501188d53..b795cb60da6 100644
--- a/pkgs/os-specific/linux/dietlibc/default.nix
+++ b/pkgs/os-specific/linux/dietlibc/default.nix
@@ -34,4 +34,10 @@ stdenv.mkDerivation {
     #./x86_64-stat64.patch
 
   ];
+
+  meta = {
+    homepage = http://www.fefe.de/dietlibc/;
+    description = "A small implementation of the C library";
+    license = "GPL";
+  };
 }
diff --git a/pkgs/os-specific/linux/dmidecode/2.9.nix b/pkgs/os-specific/linux/dmidecode/2.9.nix
new file mode 100644
index 00000000000..968ab80a4af
--- /dev/null
+++ b/pkgs/os-specific/linux/dmidecode/2.9.nix
@@ -0,0 +1,23 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://download.savannah.gnu.org/releases/dmidecode/dmidecode-2.9.tar.bz2;
+			sha256 = "05g0ln400fhqjspg9h4x0a1dvmwiyjq5rk9q9kimxvywbg1b53l8";
+		};
+
+		buildInputs = [];
+		configureFlags = [];
+		makeFlags = "prefix=\$out";
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "dmidecode-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [ doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Tool to decode Desktop Management Interface and SBIOS data.
+";
+	};
+}
diff --git a/pkgs/os-specific/linux/dvd+rw-tools/7.0.nix b/pkgs/os-specific/linux/dvd+rw-tools/7.0.nix
new file mode 100644
index 00000000000..091f0c910f6
--- /dev/null
+++ b/pkgs/os-specific/linux/dvd+rw-tools/7.0.nix
@@ -0,0 +1,29 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://fy.chalmers.se/~appro/linux/DVD+RW/tools/dvd+rw-tools-7.0.tar.gz;
+			sha256 = "08hljn2vfn794dfrfpp3m245dbpb6nhk40igfpqm6wg9qimc9zy9";
+		};
+
+		buildInputs = [cdrkit m4];
+		configureFlags = [];
+		makeFlags = [" prefix=\$out "];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+	preBuild = FullDepEntry ("
+		sed -e '1i#define INT_MAX __INT_MAX__' -i *.c *.cpp
+		sed -e 's@/usr/local@'\$out'@g' -i Makefile.m4 Makefile
+	") [minInit doUnpack];
+in
+stdenv.mkDerivation rec {
+	name = "dvd+rw-tools-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [preBuild addInputs (doDump "0") doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	DVD+RW tools.
+";
+	};
+}
diff --git a/pkgs/os-specific/linux/firmware/iwlwifi-3945-ucode/default.nix b/pkgs/os-specific/linux/firmware/iwlwifi-3945-ucode/default.nix
new file mode 100644
index 00000000000..c17d29cafa4
--- /dev/null
+++ b/pkgs/os-specific/linux/firmware/iwlwifi-3945-ucode/default.nix
@@ -0,0 +1,19 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "iwlwifi-3945-ucode-2.14.1.5";
+  
+  src = fetchurl {
+    url = http://intellinuxwireless.org/iwlwifi/downloads/iwlwifi-3945-ucode-2.14.1.5.tgz;
+    sha256 = "06gy21qkd4kj6pf3nsz5z3xkgmcafzrm1krywd8lbb8i56i3jkra";
+  };
+  
+  buildPhase = "true";
+
+  installPhase = "ensureDir $out; chmod -x *; cp * $out";
+  
+  meta = {
+    description = "Firmware for the Intel 3945ABG wireless card";
+    homepage = http://intellinuxwireless.org/;
+  };
+}
diff --git a/pkgs/os-specific/linux/firmware/iwlwifi-4965-ucode/default.nix b/pkgs/os-specific/linux/firmware/iwlwifi-4965-ucode/default.nix
new file mode 100644
index 00000000000..3a87cd164cb
--- /dev/null
+++ b/pkgs/os-specific/linux/firmware/iwlwifi-4965-ucode/default.nix
@@ -0,0 +1,19 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation rec {
+  name = "iwlwifi-4965-ucode-4.44.17";
+  
+  src = fetchurl {
+    url = "http://intellinuxwireless.org/iwlwifi/downloads/" + name + ".tgz";
+    sha256 = "1mfnxsp58jvh0njvwaxrkbiggbzr4jd0hk314hxfwyjpjdd2hj6w";
+  };
+  
+  buildPhase = "true";
+
+  installPhase = "ensureDir $out; chmod -x *; cp * $out";
+  
+  meta = {
+    description = "Firmware for the Intel 4965ABG wireless card";
+    homepage = http://intellinuxwireless.org/;
+  };
+}
diff --git a/pkgs/os-specific/linux/firmware/zd1211/default.nix b/pkgs/os-specific/linux/firmware/zd1211/default.nix
new file mode 100644
index 00000000000..1cffb504322
--- /dev/null
+++ b/pkgs/os-specific/linux/firmware/zd1211/default.nix
@@ -0,0 +1,21 @@
+args: with args;
+stdenv.mkDerivation ( rec {
+  pname = "zd1211-firmware";
+  version = "1.4";
+
+  name = "${pname}-${version}";
+  src = fetchurl {
+    url = "http://surfnet.dl.sourceforge.net/sourceforge/zd1211/${name}.tar.bz2";
+    sha256 = "866308f6f59f7075f075d4959dff2ede47735c751251fecd1496df1ba4d338e1";
+  };
+  
+  buildPhase = "true";
+
+  installPhase = "ensureDir $out/zd1211; cp * $out/zd1211";
+  
+  meta = {
+    description = "Firmware for the ZyDAS ZD1211(b) 802.11a/b/g USB WLAN chip";
+    homepage = http://sourceforge.net/projects/zd1211/;
+    license = "GPL";
+  };
+})
diff --git a/pkgs/os-specific/linux/fuse/builder.sh b/pkgs/os-specific/linux/fuse/builder.sh
index 5f0d53954e7..c843ae6183b 100644
--- a/pkgs/os-specific/linux/fuse/builder.sh
+++ b/pkgs/os-specific/linux/fuse/builder.sh
@@ -13,4 +13,6 @@ export UDEV_RULES_PATH=$out/etc/udev/rules.d
 # $PATH.
 export NIX_CFLAGS_COMPILE="-DFUSERMOUNT_DIR=\"/no-such-path\""
 
+export preBuild="sed -e 's@/bin/@$utillinux/bin/@g' -i lib/mount_util.c";
+
 genericBuild
diff --git a/pkgs/os-specific/linux/fuse/default.nix b/pkgs/os-specific/linux/fuse/default.nix
index 28052d7ceb3..7e3bb66b16f 100644
--- a/pkgs/os-specific/linux/fuse/default.nix
+++ b/pkgs/os-specific/linux/fuse/default.nix
@@ -1,11 +1,19 @@
-{stdenv, fetchurl}:
+args: with args;
 
 stdenv.mkDerivation {
-  name = "fuse-2.6.5";
+  name = "fuse-2.7.2";
   builder = ./builder.sh;
   src = fetchurl {
-    url = mirror://sourceforge/fuse/fuse-2.6.5.tar.gz;
-    sha256 = "0901hrhi1z6dwlgvgn75cg2268wvaz53x0knn7jplk6acwir54db";
+    url = mirror://sourceforge/fuse/fuse-2.7.2.tar.gz;
+    sha256 = "1zxssdiirf19mihbnxpy0kiix35d4256b9lani7qwqi7m940jfgv";
+  };
+  configureFlags = [ "--disable-kernel-module"];
+  buildInputs = [ utillinux ];
+  
+  inherit utillinux;
+
+  meta = {
+    homepage = http://fuse.sourceforge.net/;
+    description = "Kernel module and library that allows filesystems to be implemented in user space";
   };
-  configureFlags = [ "--disable-kernel-module" ];
 }
diff --git a/pkgs/os-specific/linux/fxload/default.nix b/pkgs/os-specific/linux/fxload/default.nix
new file mode 100644
index 00000000000..0eb37c0d50e
--- /dev/null
+++ b/pkgs/os-specific/linux/fxload/default.nix
@@ -0,0 +1,39 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "fxload-2002_04_11";
+  
+  src = fetchurl {
+    url = mirror://sourceforge/linux-hotplug/fxload-2002_04_11.tar.gz;
+    sha256 = "1hql93bp3dxrv1p67nc63xsbqwljyynm997ysldrc3n9ifi6s48m";
+  };
+
+  patches = [
+    # Will be needed after linux-headers is updated to >= 2.6.21.
+    #(fetchurl {
+    #  url = "http://sources.gentoo.org/viewcvs.py/*checkout*/gentoo-x86/sys-apps/fxload/files/fxload-20020411-linux-headers-2.6.21.patch?rev=1.1";
+    #  sha256 = "0ij0c8nr1rbyl5wmyv1cklhkxglvsqz32h21cjw4bjm151kgmk7p";
+    #})
+
+    (fetchurl {
+      url = "http://sources.gentoo.org/viewcvs.py/*checkout*/gentoo-x86/sys-apps/fxload/files/fxload-20020411-linux-headers-2.6.19.patch?rev=1.1";
+      sha256 = "05q7c1yvi479q5z91s9ra2rgn589qljgmdl6phqf30pgzf09r0r6";
+    })
+  ];
+
+  preBuild = ''
+    substituteInPlace Makefile --replace /usr /
+    makeFlagsArray=(INSTALL=install prefix=$out)
+  '';
+
+  preInstall = ''
+    ensureDir $out/sbin
+    ensureDir $out/share/man/man8
+    ensureDir $out/share/usb
+  '';
+
+  meta = {
+    homepage = http://linux-hotplug.sourceforge.net/?selected=usb;
+    description = "Tool to upload firmware to Cypress EZ-USB microcontrollers";
+  };
+}
diff --git a/pkgs/os-specific/linux/hal/default.nix b/pkgs/os-specific/linux/hal/default.nix
index 1fc01298105..ce41a29a9fe 100644
--- a/pkgs/os-specific/linux/hal/default.nix
+++ b/pkgs/os-specific/linux/hal/default.nix
@@ -1,8 +1,4 @@
-{ stdenv, fetchurl, pkgconfig, python, pciutils, usbutils, expat
-, libusb, dbus, dbus_glib, glib, libvolume_id, perl, perlXMLParser
-, gettext, zlib /* required by pciutils */, eject, libsmbios
-, udev
-}:
+args: with args;
 
 stdenv.mkDerivation {
   name = "hal-0.5.9";
@@ -13,7 +9,7 @@ stdenv.mkDerivation {
   };
   
   buildInputs = [
-    pkgconfig python pciutils expat libusb dbus dbus_glib glib
+    pkgconfig python pciutils expat libusb dbus.libs dbus_glib glib
     libvolume_id perl perlXMLParser gettext zlib libsmbios
   ];
 
diff --git a/pkgs/os-specific/linux/iputils/builder.sh b/pkgs/os-specific/linux/iputils/builder.sh
index d1b05109aee..b5219c3fefc 100644
--- a/pkgs/os-specific/linux/iputils/builder.sh
+++ b/pkgs/os-specific/linux/iputils/builder.sh
@@ -1,20 +1,11 @@
 source $stdenv/setup
 
-tar zxvf $src
-cd iputils
+makeFlags="KERNEL_INCLUDE=$kernelHeaders/include LIBC_INCLUDE=$glibc/include"
 
-sed -e "s^KERNEL_INCLUDE=.*$^KERNEL_INCLUDE=$kernelHeaders/include^" < Makefile > Makefile.new
-
-mv Makefile.new Makefile
-sed -e "s^LIBC_INCLUDE=.*$^LIBC_INCLUDE=$glibc/include^" < Makefile > Makefile.new
-mv Makefile.new Makefile
-
-#make ping arping tracepath
-make
-
-mkdir -p $out/bin
-mkdir -p $out/sbin
+preConfigure="sed -e 's@check-kernel @@' -i Makefile"
 
+installPhase="
+mkdir -pv $out/bin $out/sbin
 install -c arping $out/sbin/
 install -c ping $out/bin/
 install -c ping6 $out/sbin/
@@ -22,3 +13,6 @@ install -c rdisc $out/sbin/
 install -c tracepath $out/sbin/
 install -c tracepath6 $out/sbin/
 install -c traceroute6 $out/sbin/
+";
+
+genericBuild
diff --git a/pkgs/os-specific/linux/iputils/default.nix b/pkgs/os-specific/linux/iputils/default.nix
index c57cf68fd5d..354419a4109 100644
--- a/pkgs/os-specific/linux/iputils/default.nix
+++ b/pkgs/os-specific/linux/iputils/default.nix
@@ -11,5 +11,5 @@ stdenv.mkDerivation {
   };
 
   inherit kernelHeaders glibc;
-  #buildInputs = [bison flex openssl];
+  patches = [ ./open-max.patch ];
 }
diff --git a/pkgs/os-specific/linux/iputils/open-max.patch b/pkgs/os-specific/linux/iputils/open-max.patch
new file mode 100644
index 00000000000..26bb95bd9d8
--- /dev/null
+++ b/pkgs/os-specific/linux/iputils/open-max.patch
@@ -0,0 +1,30 @@
+--- iputils-s20070202/rdisc.c.open-max	2007-08-07 11:34:03.000000000 +0200
++++ iputils-s20070202/rdisc.c	2007-08-07 11:41:30.000000000 +0200
+@@ -240,14 +240,25 @@
+ {
+ 	int t;
+ 	pid_t pid;
+-	
++	long open_max;
++
+ 	if (trace)
+ 		return;
+ 
++	if ((open_max = sysconf(_SC_OPEN_MAX)) == -1) {
++		if (errno == 0) {
++			(void) fprintf(stderr, "OPEN_MAX is not supported\n");
++		}
++		else {
++			(void) fprintf(stderr, "sysconf() error\n");
++		}
++		exit(1);
++	}
++
+ 	if ((pid=fork()) != 0)
+ 		exit(0);
+ 
+-	for (t = 0; t < OPEN_MAX; t++)
++	for (t = 0; t < open_max; t++)
+ 		if (t != s)
+ 			close(t);
+ 
diff --git a/pkgs/os-specific/linux/iwlwifi/default.nix b/pkgs/os-specific/linux/iwlwifi/default.nix
new file mode 100644
index 00000000000..8859f7346b5
--- /dev/null
+++ b/pkgs/os-specific/linux/iwlwifi/default.nix
@@ -0,0 +1,37 @@
+{stdenv, fetchurl, kernel}:
+
+stdenv.mkDerivation {
+  name = "iwlwifi-1.2.23";
+
+  src = fetchurl {
+    url = http://www.intellinuxwireless.org/iwlwifi/downloads/iwlwifi-1.2.23.tgz;
+    sha256 = "0a4szjgg5b2jj4ax85lakqa951ph6pw5wpwlrw3mnmvcda5ayiip";
+  };
+
+  preBuild = ''
+    substituteInPlace scripts/generate_compatible \
+      --replace '/usr/bin/env /bin/bash' $shell
+    substituteInPlace Makefile \
+      --replace /sbin/depmod true
+
+    # Urgh, we need the complete kernel sources for some header
+    # files.  So unpack the original kernel source tarball and copy
+    # the configured include directory etc. on top of it.
+    kernelVersion=$(cd ${kernel}/lib/modules && ls)
+    kernelBuild=$(echo ${kernel}/lib/modules/$kernelVersion/source)
+    tar xvfj ${kernel.src}
+    kernelSource=$(echo $(pwd)/linux-*)
+    cp -prd $kernelBuild/* $kernelSource
+
+    makeFlags=KSRC=$kernelSource
+    make $makeFlags || true
+    make $makeFlags
+
+    installFlags=KMISC=$out/lib/modules/$kernelVersion/misc
+  ''; # */
+
+  meta = {
+    description = "Intel Wireless WiFi Link drivers for Linux";
+    homepage = http://www.intellinuxwireless.org/;
+  };
+}
diff --git a/pkgs/os-specific/linux/kernel-headers/2.6.23.1.nix b/pkgs/os-specific/linux/kernel-headers/2.6.23.8.nix
index adaa303aa00..b34ec0533be 100644
--- a/pkgs/os-specific/linux/kernel-headers/2.6.23.1.nix
+++ b/pkgs/os-specific/linux/kernel-headers/2.6.23.8.nix
@@ -3,11 +3,11 @@
 assert stdenv.isLinux;
 
 stdenv.mkDerivation {
-  name = "linux-headers-2.6.23.1";
+  name = "linux-headers-2.6.23.8";
   builder = ./builder.sh;
   src = fetchurl {
-    url = "mirror://kernel/linux/kernel/v2.6/linux-2.6.23.1.tar.bz2";
-    sha256 = "0737g83h7jbrlss8782b17mhc3nfn8qfbh5s71flz8pjxmbbmg1m";
+    url = "mirror://kernel/linux/kernel/v2.6/linux-2.6.23.8.tar.bz2";
+    sha256 = "1sp2ww2ya0wyyyq0vdxbn6ydllv9gpmzw2yz66llgvgv32cix534";
   };
 
   platform = 
diff --git a/pkgs/os-specific/linux/kernel-headers/builder.sh b/pkgs/os-specific/linux/kernel-headers/builder.sh
index b2ebbc69485..05392d5fe24 100644
--- a/pkgs/os-specific/linux/kernel-headers/builder.sh
+++ b/pkgs/os-specific/linux/kernel-headers/builder.sh
@@ -1,26 +1,9 @@
 source $stdenv/setup
 
+patchPhase="sed -i '/scsi/d' include/Kbuild"
 
-buildPhase() {
-    make include/linux/version.h
-}
-
-buildPhase=buildPhase
-
-
-installPhase() {
-    mkdir $out
-    mkdir $out/include
-    cp -prvd include/linux include/asm-generic $out/include
-    cp -prvd include/asm-$platform $out/include
-    ln -s asm-$platform $out/include/asm
-    for i in $extraIncludeDirs; do
-	cp -prvd include/asm-$i $out/include
-    done
-    echo -n > $out/include/linux/autoconf.h
-}
-
-installPhase=installPhase
+buildPhase="make mrproper headers_check";
 
+installPhase="make INSTALL_HDR_PATH=$out headers_install"
 
 genericBuild
diff --git a/pkgs/os-specific/linux/kernel-headers/default.nix b/pkgs/os-specific/linux/kernel-headers/default.nix
deleted file mode 100644
index ef94f1b006c..00000000000
--- a/pkgs/os-specific/linux/kernel-headers/default.nix
+++ /dev/null
@@ -1,21 +0,0 @@
-{stdenv, fetchurl}:
-
-assert stdenv.isLinux;
-
-stdenv.mkDerivation {
-  name = "linux-headers-2.6.20.11";
-  builder = ./builder.sh;
-  src = fetchurl {
-    url = "mirror://kernel/linux/kernel/v2.6/linux-2.6.20.11.tar.bz2";
-    sha256 = "1n0xgqckj64ga3l53l8lk1591lfcn6zcrqg3phz2m0y841ck5qlk";
-  };
-
-  platform = 
-    if stdenv.system == "i686-linux" then "i386" else
-    if stdenv.system == "x86_64-linux" then "x86_64" else
-    if stdenv.system == "powerpc-linux" then "powerpc" else
-    abort "don't know what the kernel include directory is called for this platform";
-
-  extraIncludeDirs =
-    if stdenv.system == "powerpc-linux" then ["ppc"] else [];
-}
diff --git a/pkgs/os-specific/linux/kernel/2.6.22-paravirt-nvidia.patch b/pkgs/os-specific/linux/kernel/2.6.22-paravirt-nvidia.patch
deleted file mode 100644
index 15dc34680d0..00000000000
--- a/pkgs/os-specific/linux/kernel/2.6.22-paravirt-nvidia.patch
+++ /dev/null
@@ -1,14 +0,0 @@
-diff -rc linux-2.6.22.1/arch/i386/kernel/paravirt.c linux-2.6.22.1-para/arch/i386/kernel/paravirt.c
-*** linux-2.6.22.1/arch/i386/kernel/paravirt.c	2007-07-20 16:19:35.000000000 +0200
---- linux-2.6.22.1-para/arch/i386/kernel/paravirt.c	2007-07-20 16:20:00.000000000 +0200
-***************
-*** 344,347 ****
-  	.activate_mm = paravirt_nop,
-  };
-  
-! EXPORT_SYMBOL(paravirt_ops);
---- 344,347 ----
-  	.activate_mm = paravirt_nop,
-  };
-  
-! EXPORT_SYMBOL_GPL(paravirt_ops);
diff --git a/pkgs/os-specific/linux/kernel/acerhk/default.nix b/pkgs/os-specific/linux/kernel/acerhk/default.nix
index 577d0f51027..8fe45048d7f 100644
--- a/pkgs/os-specific/linux/kernel/acerhk/default.nix
+++ b/pkgs/os-specific/linux/kernel/acerhk/default.nix
@@ -1,14 +1,14 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "acerhk_kernel_patch-0.5.35";
-  kernel = args.kernel.src;
-  inherit (args) debug;
-  acerhk = args.fetchurl {
+  kernel = kernel.src;
+  inherit debug;
+  acerhk = fetchurl {
     url = http://mirror.switch.ch/mirror/gentoo/distfiles/acerhk-0.5.35.tar.bz2;
     sha256 = "1kg002qraa8vha2cgza3z74d9j46g180g5b44zbv64dsa9n2j4b0";
   };
 
-  buildInputs =(with args; [gnupatch]);
+  buildInputs = [gnupatch];
   
   builder = ./builder.sh;
 
diff --git a/pkgs/os-specific/linux/kernel/config-2.6.23-i686-smp b/pkgs/os-specific/linux/kernel/config-2.6.23-i686-smp
index 5e472930410..86fbe30c521 100644
--- a/pkgs/os-specific/linux/kernel/config-2.6.23-i686-smp
+++ b/pkgs/os-specific/linux/kernel/config-2.6.23-i686-smp
@@ -119,7 +119,7 @@ CONFIG_X86_PC=y
 # CONFIG_X86_GENERICARCH is not set
 # CONFIG_X86_ES7000 is not set
 CONFIG_PARAVIRT=y
-CONFIG_XEN=y
+# CONFIG_XEN is not set
 CONFIG_VMI=y
 # CONFIG_M386 is not set
 # CONFIG_M486 is not set
diff --git a/pkgs/os-specific/linux/kernel/linux-2.6.21_ck.nix b/pkgs/os-specific/linux/kernel/linux-2.6.21_ck.nix
new file mode 100644
index 00000000000..55748d3e9f5
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/linux-2.6.21_ck.nix
@@ -0,0 +1,84 @@
+{ stdenv, fetchurl, perl, mktemp, module_init_tools
+
+  # A list of patches to apply to the kernel.  Each element of this list
+  # should be an attribute set {name, patch} where `name' is a
+  # symbolic name and `patch' is the actual patch.  The patch may
+  # optionally be compressed with gzip or bzip2.
+, kernelPatches ? []
+
+, # Whether to build a User-Mode Linux kernel.
+  userModeLinux ? false
+
+, # Allows you to set your own kernel version suffix (e.g.,
+  # "-my-kernel").
+  localVersion ? ""
+
+, # Your own kernel configuration file, if you don't want to use the
+  # default. 
+  kernelConfig ? null
+
+, # A list of additional statements to be appended to the
+  # configuration file.
+  extraConfig ? []
+}:
+
+assert stdenv.system == "i686-linux" || stdenv.system == "x86_64-linux";
+
+let
+
+  lib = import ../../../lib;
+
+  version = "2.6.21";
+
+in
+
+stdenv.mkDerivation {
+  name = if userModeLinux then "user-mode-linux-${version}" else "linux-${version}";
+  builder = ./builder.sh;
+  
+  src = fetchurl {
+    url = "http://www.kernel.org/pub/linux/kernel/v2.6/linux-2.6.21.tar.bz2";
+    sha256 = "f187b12d70e0a48ce81f0472dfe9504fb5f0f966be339ac9d57dd2b991a74942";
+  };
+  
+  patches = map (p: p.patch) kernelPatches;
+  extraConfig =
+    let addNewlines = map (s: "\n" + s + "\n");
+        configFromPatches =
+          map (p: if p ? extraConfig then p.extraConfig else "") kernelPatches;
+    in lib.concatStrings (addNewlines (configFromPatches ++ extraConfig));
+
+  config =
+    if kernelConfig != null then kernelConfig else
+    if userModeLinux then ./config-2.6.21-uml else
+    if stdenv.system == "i686-linux" then ./config-2.6.21-i686-smp else
+    if stdenv.system == "x86_64-linux" then ./config-2.6.21-x86_64-smp else
+    abort "No kernel configuration for your platform!";
+  
+  buildInputs = [perl mktemp];
+  
+  arch =
+    if userModeLinux then "um" else
+    if stdenv.system == "i686-linux" then "i386" else
+    if stdenv.system == "x86_64-linux" then "x86_64" else
+    abort "Platform ${stdenv.system} is not supported.";
+
+  makeFlags = if userModeLinux then "ARCH=um SHELL=bash" else "";
+
+  inherit module_init_tools;
+
+  allowLocalVersion = false; # don't allow patches to set a suffix
+  inherit localVersion; # but do allow the user to set one.
+
+  meta = {
+    description =
+      (if userModeLinux then
+        "User-Mode Linux"
+       else
+        "The Linux kernel") +
+      (if kernelPatches == [] then "" else
+        " (with patches: "
+        + lib.concatStrings (lib.intersperse ", " (map (x: x.name) kernelPatches))
+        + ")");
+  };
+}
diff --git a/pkgs/os-specific/linux/kernel/linux-2.6.22.nix b/pkgs/os-specific/linux/kernel/linux-2.6.22.nix
index bb51a5f6b52..1abc1470616 100644
--- a/pkgs/os-specific/linux/kernel/linux-2.6.22.nix
+++ b/pkgs/os-specific/linux/kernel/linux-2.6.22.nix
@@ -28,7 +28,7 @@ let
 
   lib = import ../../../lib;
 
-  version = "2.6.22.10";
+  version = "2.6.22.18";
 
 in
 
@@ -38,7 +38,7 @@ stdenv.mkDerivation {
   
   src = fetchurl {
     url = "mirror://kernel/linux/kernel/v2.6/linux-${version}.tar.bz2";
-    sha256 = "0kh196qzm54mvnbrdr9s2q86l9yn2321gnsl5xq44ai2idqp044g";
+    sha256 = "09acj1xr16j9y91gzwzcjhanhcpyac1ah2lc42mfi7d8c0plagry";
   };
   
   patches = map (p: p.patch) kernelPatches;
diff --git a/pkgs/os-specific/linux/kernel/linux-2.6.23.nix b/pkgs/os-specific/linux/kernel/linux-2.6.23.nix
index 1d034e897cc..d4c4b688ab4 100644
--- a/pkgs/os-specific/linux/kernel/linux-2.6.23.nix
+++ b/pkgs/os-specific/linux/kernel/linux-2.6.23.nix
@@ -28,7 +28,7 @@ let
 
   lib = import ../../../lib;
 
-  version = "2.6.23.1";
+  version = "2.6.23.16";
 
 in
 
@@ -38,7 +38,7 @@ stdenv.mkDerivation {
   
   src = fetchurl {
     url = "mirror://kernel/linux/kernel/v2.6/linux-${version}.tar.bz2";
-    sha256 = "0737g83h7jbrlss8782b17mhc3nfn8qfbh5s71flz8pjxmbbmg1m";
+    sha256 = "0drk3981rl5j16s6amb63lai9kpi0vf0kr6avhpd9nikj27bsa83";
   };
   
   patches = map (p: p.patch) kernelPatches;
diff --git a/pkgs/os-specific/linux/kernel/patch-2.6.21-ck1 b/pkgs/os-specific/linux/kernel/patch-2.6.21-ck1
new file mode 100644
index 00000000000..0bf63f5aca3
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/patch-2.6.21-ck1
@@ -0,0 +1,5040 @@
+Index: linux-2.6.21-ck1/Makefile
+===================================================================
+--- linux-2.6.21-ck1.orig/Makefile	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/Makefile	2007-05-04 12:21:37.000000000 +1000
+@@ -1,7 +1,7 @@
+ VERSION = 2
+ PATCHLEVEL = 6
+ SUBLEVEL = 21
+-EXTRAVERSION =
++EXTRAVERSION = -ck1
+ NAME = Nocturnal Monster Puppy
+ 
+ # *DOCUMENTATION*
+Index: linux-2.6.21-ck1/kernel/workqueue.c
+===================================================================
+--- linux-2.6.21-ck1.orig/kernel/workqueue.c	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/kernel/workqueue.c	2007-05-04 12:10:54.000000000 +1000
+@@ -355,8 +355,6 @@ static int worker_thread(void *__cwq)
+ 	if (!cwq->freezeable)
+ 		current->flags |= PF_NOFREEZE;
+ 
+-	set_user_nice(current, -5);
+-
+ 	/* Block and flush all signals */
+ 	sigfillset(&blocked);
+ 	sigprocmask(SIG_BLOCK, &blocked, NULL);
+Index: linux-2.6.21-ck1/fs/proc/array.c
+===================================================================
+--- linux-2.6.21-ck1.orig/fs/proc/array.c	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/fs/proc/array.c	2007-05-04 12:10:54.000000000 +1000
+@@ -165,7 +165,6 @@ static inline char * task_state(struct t
+ 	rcu_read_lock();
+ 	buffer += sprintf(buffer,
+ 		"State:\t%s\n"
+-		"SleepAVG:\t%lu%%\n"
+ 		"Tgid:\t%d\n"
+ 		"Pid:\t%d\n"
+ 		"PPid:\t%d\n"
+@@ -173,7 +172,6 @@ static inline char * task_state(struct t
+ 		"Uid:\t%d\t%d\t%d\t%d\n"
+ 		"Gid:\t%d\t%d\t%d\t%d\n",
+ 		get_task_state(p),
+-		(p->sleep_avg/1024)*100/(1020000000/1024),
+ 	       	p->tgid, p->pid,
+ 	       	pid_alive(p) ? rcu_dereference(p->real_parent)->tgid : 0,
+ 		pid_alive(p) && p->ptrace ? rcu_dereference(p->parent)->pid : 0,
+Index: linux-2.6.21-ck1/include/linux/init_task.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/init_task.h	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/init_task.h	2007-05-04 12:24:19.000000000 +1000
+@@ -102,13 +102,15 @@ extern struct group_info init_groups;
+ 	.prio		= MAX_PRIO-20,					\
+ 	.static_prio	= MAX_PRIO-20,					\
+ 	.normal_prio	= MAX_PRIO-20,					\
++	.rotation	= 0,						\
+ 	.policy		= SCHED_NORMAL,					\
+ 	.cpus_allowed	= CPU_MASK_ALL,					\
+ 	.mm		= NULL,						\
+ 	.active_mm	= &init_mm,					\
+ 	.run_list	= LIST_HEAD_INIT(tsk.run_list),			\
+ 	.ioprio		= 0,						\
+-	.time_slice	= HZ,						\
++	.time_slice	= 1000000000,						\
++	.quota		= 1000000000,						\
+ 	.tasks		= LIST_HEAD_INIT(tsk.tasks),			\
+ 	.ptrace_children= LIST_HEAD_INIT(tsk.ptrace_children),		\
+ 	.ptrace_list	= LIST_HEAD_INIT(tsk.ptrace_list),		\
+@@ -135,6 +137,7 @@ extern struct group_info init_groups;
+ 		.signal = {{0}}},					\
+ 	.blocked	= {{0}},					\
+ 	.alloc_lock	= __SPIN_LOCK_UNLOCKED(tsk.alloc_lock),		\
++	.mutexes_held	= 0,						\
+ 	.journal_info	= NULL,						\
+ 	.cpu_timers	= INIT_CPU_TIMERS(tsk.cpu_timers),		\
+ 	.fs_excl	= ATOMIC_INIT(0),				\
+Index: linux-2.6.21-ck1/include/linux/sched.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/sched.h	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/sched.h	2007-05-04 12:24:19.000000000 +1000
+@@ -34,9 +34,14 @@
+ #define SCHED_FIFO		1
+ #define SCHED_RR		2
+ #define SCHED_BATCH		3
++#define SCHED_ISO		4
++#define SCHED_IDLEPRIO		5
+ 
+ #ifdef __KERNEL__
+ 
++#define SCHED_MAX		SCHED_IDLEPRIO
++#define SCHED_RANGE(policy)	((policy) <= SCHED_MAX)
++
+ struct sched_param {
+ 	int sched_priority;
+ };
+@@ -149,8 +154,7 @@ extern unsigned long weighted_cpuload(co
+ #define EXIT_ZOMBIE		16
+ #define EXIT_DEAD		32
+ /* in tsk->state again */
+-#define TASK_NONINTERACTIVE	64
+-#define TASK_DEAD		128
++#define TASK_DEAD		64
+ 
+ #define __set_task_state(tsk, state_value)		\
+ 	do { (tsk)->state = (state_value); } while (0)
+@@ -522,14 +526,19 @@ struct signal_struct {
+ 
+ #define MAX_USER_RT_PRIO	100
+ #define MAX_RT_PRIO		MAX_USER_RT_PRIO
++#define PRIO_RANGE		(40)
++#define ISO_PRIO		(MAX_RT_PRIO - 1)
+ 
+-#define MAX_PRIO		(MAX_RT_PRIO + 40)
++#define MAX_PRIO		(MAX_RT_PRIO + PRIO_RANGE)
+ 
+-#define rt_prio(prio)		unlikely((prio) < MAX_RT_PRIO)
++#define rt_prio(prio)		unlikely((prio) < ISO_PRIO)
+ #define rt_task(p)		rt_prio((p)->prio)
+ #define batch_task(p)		(unlikely((p)->policy == SCHED_BATCH))
+-#define is_rt_policy(p)		((p) != SCHED_NORMAL && (p) != SCHED_BATCH)
++#define is_rt_policy(policy)	((policy) == SCHED_FIFO || \
++					(policy) == SCHED_RR)
+ #define has_rt_policy(p)	unlikely(is_rt_policy((p)->policy))
++#define iso_task(p)		unlikely((p)->policy == SCHED_ISO)
++#define idleprio_task(p)	unlikely((p)->policy == SCHED_IDLEPRIO)
+ 
+ /*
+  * Some day this will be a full-fledged user tracking system..
+@@ -740,6 +749,22 @@ extern unsigned int max_cache_size;
+ 
+ #endif	/* CONFIG_SMP */
+ 
++/*
++ * A runqueue laden with a single nice 0 task scores a weighted_cpuload of
++ * SCHED_LOAD_SCALE. This function returns 1 if any cpu is laden with a
++ * task of nice 0 or enough lower priority tasks to bring up the
++ * weighted_cpuload
++ */
++static inline int above_background_load(void)
++{
++	unsigned long cpu;
++
++	for_each_online_cpu(cpu) {
++		if (weighted_cpuload(cpu) >= SCHED_LOAD_SCALE)
++			return 1;
++	}
++	return 0;
++}
+ 
+ struct io_context;			/* See blkdev.h */
+ struct cpuset;
+@@ -788,13 +813,6 @@ struct mempolicy;
+ struct pipe_inode_info;
+ struct uts_namespace;
+ 
+-enum sleep_type {
+-	SLEEP_NORMAL,
+-	SLEEP_NONINTERACTIVE,
+-	SLEEP_INTERACTIVE,
+-	SLEEP_INTERRUPTED,
+-};
+-
+ struct prio_array;
+ 
+ struct task_struct {
+@@ -814,20 +832,33 @@ struct task_struct {
+ 	int load_weight;	/* for niceness load balancing purposes */
+ 	int prio, static_prio, normal_prio;
+ 	struct list_head run_list;
++	/*
++	 * This bitmap shows what priorities this task has received quota
++	 * from for this major priority rotation on its current runqueue.
++	 */
++	DECLARE_BITMAP(bitmap, PRIO_RANGE + 1);
+ 	struct prio_array *array;
++	/* Which major runqueue rotation did this task run */
++	unsigned long rotation;
+ 
+ 	unsigned short ioprio;
+ #ifdef CONFIG_BLK_DEV_IO_TRACE
+ 	unsigned int btrace_seq;
+ #endif
+-	unsigned long sleep_avg;
+ 	unsigned long long timestamp, last_ran;
+ 	unsigned long long sched_time; /* sched_clock time spent running */
+-	enum sleep_type sleep_type;
+ 
+ 	unsigned long policy;
+ 	cpumask_t cpus_allowed;
+-	unsigned int time_slice, first_time_slice;
++	/*
++	 * How much this task is entitled to run at the current priority
++	 * before being requeued at a lower priority.
++	 */
++	int time_slice;
++	/* Is this the very first time_slice this task has ever run. */
++	unsigned int first_time_slice;
++	/* How much this task receives at each priority level */
++	int quota;
+ 
+ #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
+ 	struct sched_info sched_info;
+@@ -992,6 +1023,7 @@ struct task_struct {
+ 	struct held_lock held_locks[MAX_LOCK_DEPTH];
+ 	unsigned int lockdep_recursion;
+ #endif
++	unsigned long mutexes_held;
+ 
+ /* journalling filesystem info */
+ 	void *journal_info;
+@@ -1156,8 +1188,10 @@ static inline void put_task_struct(struc
+ #define PF_SWAPWRITE	0x00800000	/* Allowed to write to swap */
+ #define PF_SPREAD_PAGE	0x01000000	/* Spread page cache over cpuset */
+ #define PF_SPREAD_SLAB	0x02000000	/* Spread some slab caches over cpuset */
++#define PF_ISOREF	0x04000000	/* SCHED_ISO task has used up quota */
+ #define PF_MEMPOLICY	0x10000000	/* Non-default NUMA mempolicy */
+ #define PF_MUTEX_TESTER	0x20000000	/* Thread belongs to the rt mutex tester */
++#define PF_NONSLEEP	0x40000000	/* Waiting on in-kernel activity */
+ 
+ /*
+  * Only the _current_ task can read/write to tsk->flags, but other
+Index: linux-2.6.21-ck1/kernel/sched.c
+===================================================================
+--- linux-2.6.21-ck1.orig/kernel/sched.c	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/kernel/sched.c	2007-05-04 12:24:22.000000000 +1000
+@@ -16,6 +16,7 @@
+  *		by Davide Libenzi, preemptible kernel bits by Robert Love.
+  *  2003-09-03	Interactivity tuning by Con Kolivas.
+  *  2004-04-02	Scheduler domains code by Nick Piggin
++ *  2007-03-02	Staircase deadline scheduling policy by Con Kolivas
+  */
+ 
+ #include <linux/mm.h>
+@@ -52,6 +53,7 @@
+ #include <linux/tsacct_kern.h>
+ #include <linux/kprobes.h>
+ #include <linux/delayacct.h>
++#include <linux/log2.h>
+ #include <asm/tlb.h>
+ 
+ #include <asm/unistd.h>
+@@ -83,126 +85,85 @@ unsigned long long __attribute__((weak))
+ #define USER_PRIO(p)		((p)-MAX_RT_PRIO)
+ #define TASK_USER_PRIO(p)	USER_PRIO((p)->static_prio)
+ #define MAX_USER_PRIO		(USER_PRIO(MAX_PRIO))
++#define SCHED_PRIO(p)		((p)+MAX_RT_PRIO)
+ 
+-/*
+- * Some helpers for converting nanosecond timing to jiffy resolution
+- */
+-#define NS_TO_JIFFIES(TIME)	((TIME) / (1000000000 / HZ))
++/* Some helpers for converting to/from various scales.*/
+ #define JIFFIES_TO_NS(TIME)	((TIME) * (1000000000 / HZ))
+-
+-/*
+- * These are the 'tuning knobs' of the scheduler:
+- *
+- * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
+- * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
+- * Timeslices get refilled after they expire.
+- */
+-#define MIN_TIMESLICE		max(5 * HZ / 1000, 1)
+-#define DEF_TIMESLICE		(100 * HZ / 1000)
+-#define ON_RUNQUEUE_WEIGHT	 30
+-#define CHILD_PENALTY		 95
+-#define PARENT_PENALTY		100
+-#define EXIT_WEIGHT		  3
+-#define PRIO_BONUS_RATIO	 25
+-#define MAX_BONUS		(MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
+-#define INTERACTIVE_DELTA	  2
+-#define MAX_SLEEP_AVG		(DEF_TIMESLICE * MAX_BONUS)
+-#define STARVATION_LIMIT	(MAX_SLEEP_AVG)
+-#define NS_MAX_SLEEP_AVG	(JIFFIES_TO_NS(MAX_SLEEP_AVG))
+-
+-/*
+- * If a task is 'interactive' then we reinsert it in the active
+- * array after it has expired its current timeslice. (it will not
+- * continue to run immediately, it will still roundrobin with
+- * other interactive tasks.)
+- *
+- * This part scales the interactivity limit depending on niceness.
+- *
+- * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
+- * Here are a few examples of different nice levels:
+- *
+- *  TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
+- *  TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
+- *  TASK_INTERACTIVE(  0): [1,1,1,1,0,0,0,0,0,0,0]
+- *  TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
+- *  TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
+- *
+- * (the X axis represents the possible -5 ... 0 ... +5 dynamic
+- *  priority range a task can explore, a value of '1' means the
+- *  task is rated interactive.)
+- *
+- * Ie. nice +19 tasks can never get 'interactive' enough to be
+- * reinserted into the active array. And only heavily CPU-hog nice -20
+- * tasks will be expired. Default nice 0 tasks are somewhere between,
+- * it takes some effort for them to get interactive, but it's not
+- * too hard.
+- */
+-
+-#define CURRENT_BONUS(p) \
+-	(NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
+-		MAX_SLEEP_AVG)
+-
+-#define GRANULARITY	(10 * HZ / 1000 ? : 1)
+-
+-#ifdef CONFIG_SMP
+-#define TIMESLICE_GRANULARITY(p)	(GRANULARITY * \
+-		(1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
+-			num_online_cpus())
+-#else
+-#define TIMESLICE_GRANULARITY(p)	(GRANULARITY * \
+-		(1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
+-#endif
+-
+-#define SCALE(v1,v1_max,v2_max) \
+-	(v1) * (v2_max) / (v1_max)
+-
+-#define DELTA(p) \
+-	(SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
+-		INTERACTIVE_DELTA)
+-
+-#define TASK_INTERACTIVE(p) \
+-	((p)->prio <= (p)->static_prio - DELTA(p))
+-
+-#define INTERACTIVE_SLEEP(p) \
+-	(JIFFIES_TO_NS(MAX_SLEEP_AVG * \
+-		(MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
+-
+-#define TASK_PREEMPTS_CURR(p, rq) \
+-	((p)->prio < (rq)->curr->prio)
+-
+-#define SCALE_PRIO(x, prio) \
+-	max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
+-
+-static unsigned int static_prio_timeslice(int static_prio)
+-{
+-	if (static_prio < NICE_TO_PRIO(0))
+-		return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
+-	else
+-		return SCALE_PRIO(DEF_TIMESLICE, static_prio);
+-}
+-
+-/*
+- * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
+- * to time slice values: [800ms ... 100ms ... 5ms]
+- *
+- * The higher a thread's priority, the bigger timeslices
+- * it gets during one round of execution. But even the lowest
+- * priority thread gets MIN_TIMESLICE worth of execution time.
++#define MS_TO_NS(TIME)		((TIME) * 1000000)
++#define MS_TO_US(TIME)		((TIME) * 1000)
++#define US_TO_MS(TIME)		((TIME) / 1000)
++
++#define TASK_PREEMPTS_CURR(p, curr)	((p)->prio < (curr)->prio)
++
++/*
++ * This is the time all tasks within the same priority round robin.
++ * Value is in ms and set to a minimum of 8ms. Scales with number of cpus.
++ * Tunable via /proc interface.
++ */
++int rr_interval __read_mostly = 6;
++int sched_interactive __read_mostly = 1;
++
++/*
++ * sched_iso_cpu - sysctl which determines the cpu percentage SCHED_ISO tasks
++ * are allowed to run (over ISO_PERIOD seconds) as real time tasks.
++ * sched_iso_period - sysctl which determines the number of seconds over
++ * which cpu usage of SCHED_ISO tasks is averaged to determine if they are
++ * exceeding their allowable bandwidth.
++*/
++int sched_iso_cpu __read_mostly = 80;
++int sched_iso_period __read_mostly = 5;
++
++#define ISO_PERIOD	((sched_iso_period * HZ) + 1)
++
++/*
++ * This contains a bitmap for each dynamic priority level with empty slots
++ * for the valid priorities each different nice level can have. It allows
++ * us to stagger the slots where differing priorities run in a way that
++ * keeps latency differences between different nice levels at a minimum.
++ * The purpose of a pre-generated matrix is for rapid lookup of next slot in
++ * O(1) time without having to recalculate every time priority gets demoted.
++ * All nice levels use priority slot 39 as this allows less niced tasks to
++ * get all priority slots better than that before expiration is forced.
++ * ie, where 0 means a slot for that priority, priority running from left to
++ * right is from prio 0 to prio 39:
++ * nice -20 0000000000000000000000000000000000000000
++ * nice -10 1000100010001000100010001000100010010000
++ * nice   0 1010101010101010101010101010101010101010
++ * nice   5 1011010110110101101101011011010110110110
++ * nice  10 1110111011101110111011101110111011101110
++ * nice  15 1111111011111110111111101111111011111110
++ * nice  19 1111111111111111111111111111111111111110
+  */
++static unsigned long prio_matrix[PRIO_RANGE][BITS_TO_LONGS(PRIO_RANGE)]
++				 __read_mostly;
+ 
+-static inline unsigned int task_timeslice(struct task_struct *p)
+-{
+-	return static_prio_timeslice(p->static_prio);
+-}
++struct rq;
+ 
+ /*
+  * These are the runqueue data structures:
+  */
+-
+ struct prio_array {
+-	unsigned int nr_active;
+-	DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
+-	struct list_head queue[MAX_PRIO];
++	/* Tasks queued at each priority */
++	struct list_head queue[MAX_PRIO + 1];
++
++	/*
++	 * The bitmap of priorities queued for this array. While the expired
++	 * array will never have realtime tasks on it, it is simpler to have
++	 * equal sized bitmaps for a cheap array swap. Include 1 bit for
++	 * delimiter.
++	 */
++	DECLARE_BITMAP(prio_bitmap, MAX_PRIO + 1);
++
++	/*
++	 * The best static priority (of the dynamic priority tasks) queued
++	 * this array.
++	 */
++	int best_static_prio;
++
++#ifdef CONFIG_SMP
++	/* For convenience looks back at rq */
++	struct rq *rq;
++#endif
+ };
+ 
+ /*
+@@ -234,14 +195,28 @@ struct rq {
+ 	 */
+ 	unsigned long nr_uninterruptible;
+ 
+-	unsigned long expired_timestamp;
+ 	/* Cached timestamp set by update_cpu_clock() */
+ 	unsigned long long most_recent_timestamp;
+ 	struct task_struct *curr, *idle;
+ 	unsigned long next_balance;
+ 	struct mm_struct *prev_mm;
+-	struct prio_array *active, *expired, arrays[2];
+-	int best_expired_prio;
++
++	struct prio_array *active, *expired, *idleprio, arrays[2];
++	unsigned long *dyn_bitmap, *exp_bitmap;
++
++	/*
++	 * The current dynamic priority level this runqueue is at per static
++	 * priority level.
++	 */
++	int prio_level[PRIO_RANGE];
++
++	/* How many times we have rotated the priority queue */
++	unsigned long prio_rotation;
++	unsigned long iso_ticks;
++	unsigned short iso_refractory;
++
++	/* Number of idleprio tasks running */
++	unsigned long nr_idleprio;
+ 	atomic_t nr_iowait;
+ 
+ #ifdef CONFIG_SMP
+@@ -579,12 +554,9 @@ static inline struct rq *this_rq_lock(vo
+ #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
+ /*
+  * Called when a process is dequeued from the active array and given
+- * the cpu.  We should note that with the exception of interactive
+- * tasks, the expired queue will become the active queue after the active
+- * queue is empty, without explicitly dequeuing and requeuing tasks in the
+- * expired queue.  (Interactive tasks may be requeued directly to the
+- * active queue, thus delaying tasks in the expired queue from running;
+- * see scheduler_tick()).
++ * the cpu.  We should note that the expired queue will become the active
++ * queue after the active queue is empty, without explicitly dequeuing and
++ * requeuing tasks in the expired queue.
+  *
+  * This function is only called from sched_info_arrive(), rather than
+  * dequeue_task(). Even though a task may be queued and dequeued multiple
+@@ -682,71 +654,304 @@ sched_info_switch(struct task_struct *pr
+ #define sched_info_switch(t, next)	do { } while (0)
+ #endif /* CONFIG_SCHEDSTATS || CONFIG_TASK_DELAY_ACCT */
+ 
++static int idleprio_suitable(struct task_struct *p)
++{
++	return (!p->mutexes_held && !freezing(p) && !signal_pending(p) &&
++		!(p->flags & (PF_NONSLEEP | PF_EXITING)));
++}
++
++static int idleprio(const struct task_struct *p)
++{
++	return (p->prio == MAX_PRIO);
++}
++
++static inline int task_queued(struct task_struct *task)
++{
++	return !list_empty(&task->run_list);
++}
++
++static inline void set_dynamic_bit(struct task_struct *p, struct rq *rq)
++{
++	__set_bit(p->prio, p->array->prio_bitmap);
++}
++
+ /*
+- * Adding/removing a task to/from a priority array:
++ * Removing from a runqueue.
+  */
+-static void dequeue_task(struct task_struct *p, struct prio_array *array)
++static void dequeue_task(struct task_struct *p, struct rq *rq)
+ {
+-	array->nr_active--;
+-	list_del(&p->run_list);
+-	if (list_empty(array->queue + p->prio))
+-		__clear_bit(p->prio, array->bitmap);
++	list_del_init(&p->run_list);
++	if (idleprio_task(p) && idleprio(p))
++		rq->nr_idleprio--;
++	else if (list_empty(p->array->queue + p->prio))
++		__clear_bit(p->prio, p->array->prio_bitmap);
+ }
+ 
+-static void enqueue_task(struct task_struct *p, struct prio_array *array)
++static void reset_first_time_slice(struct task_struct *p)
+ {
+-	sched_info_queued(p);
+-	list_add_tail(&p->run_list, array->queue + p->prio);
+-	__set_bit(p->prio, array->bitmap);
+-	array->nr_active++;
++	if (unlikely(p->first_time_slice))
++		p->first_time_slice = 0;
++}
++
++/*
++ * The task is being queued on a fresh array so it has its entitlement
++ * bitmap cleared.
++ */
++static void task_new_array(struct task_struct *p, struct rq *rq,
++			   struct prio_array *array)
++{
++	bitmap_zero(p->bitmap, PRIO_RANGE);
++	p->rotation = rq->prio_rotation;
++	p->time_slice = p->quota;
+ 	p->array = array;
++	reset_first_time_slice(p);
++}
++
++/* Find the first slot from the relevant prio_matrix entry */
++static int first_prio_slot(struct task_struct *p)
++{
++	if (unlikely(p->policy == SCHED_BATCH))
++		return p->static_prio;
++	return SCHED_PRIO(find_first_zero_bit(
++		prio_matrix[USER_PRIO(p->static_prio)], PRIO_RANGE));
+ }
+ 
+ /*
+- * Put task to the end of the run list without the overhead of dequeue
+- * followed by enqueue.
++ * In sched_interactive mode priority allocation occurs per process per rq
++ * array swap. In !sched_interactive mode all waking tasks must obey the
++ * current prio level of all other tasks running per array swap.
+  */
+-static void requeue_task(struct task_struct *p, struct prio_array *array)
++static int minprio(struct rq *rq, int uprio)
+ {
+-	list_move_tail(&p->run_list, array->queue + p->prio);
++	if (sched_interactive)
++		return MAX_RT_PRIO;
++	return rq->prio_level[uprio];
+ }
+ 
+-static inline void
+-enqueue_task_head(struct task_struct *p, struct prio_array *array)
++/*
++ * Find the first unused slot by this task that is also in its prio_matrix
++ * level. SCHED_BATCH tasks do not use the priority matrix. They only take
++ * priority slots from their static_prio and above.
++ */
++static int next_entitled_slot(struct task_struct *p, struct rq *rq)
+ {
+-	list_add(&p->run_list, array->queue + p->prio);
+-	__set_bit(p->prio, array->bitmap);
+-	array->nr_active++;
+-	p->array = array;
++	int search_prio = MAX_RT_PRIO, uprio = USER_PRIO(p->static_prio);
++	struct prio_array *array = rq->active;
++	DECLARE_BITMAP(tmp, PRIO_RANGE);
++
++	/*
++	 * Go straight to expiration if there are higher priority tasks
++	 * already expired.
++	 */
++	if (p->static_prio > rq->expired->best_static_prio)
++		return MAX_PRIO;
++	if (!rq->prio_level[uprio])
++		rq->prio_level[uprio] = MAX_RT_PRIO;
++	/*
++	 * Only priorities equal to the prio_level and above for their
++	 * static_prio are acceptable, and only if it's not better than
++	 * a queued better static_prio's prio_level.
++	 */
++	if (p->static_prio < array->best_static_prio) {
++		if (likely(p->policy != SCHED_BATCH))
++			array->best_static_prio = p->static_prio;
++	} else if (p->static_prio == array->best_static_prio) {
++		search_prio = minprio(rq, uprio);
++	} else {
++		int i;
++
++		search_prio = minprio(rq, uprio);
++		/* A bound O(n) function, worst case n is 40 */
++		for (i = array->best_static_prio; i <= p->static_prio ; i++) {
++			if (!rq->prio_level[USER_PRIO(i)])
++				rq->prio_level[USER_PRIO(i)] = MAX_RT_PRIO;
++			search_prio = max(search_prio,
++				      rq->prio_level[USER_PRIO(i)]);
++		}
++	}
++	if (unlikely(p->policy == SCHED_BATCH)) {
++		search_prio = max(search_prio, p->static_prio);
++		return SCHED_PRIO(find_next_zero_bit(p->bitmap, PRIO_RANGE,
++				  USER_PRIO(search_prio)));
++	}
++	bitmap_or(tmp, p->bitmap, prio_matrix[uprio], PRIO_RANGE);
++	return SCHED_PRIO(find_next_zero_bit(tmp, PRIO_RANGE,
++		USER_PRIO(search_prio)));
++}
++
++static void queue_expired(struct task_struct *p, struct rq *rq)
++{
++	task_new_array(p, rq, rq->expired);
++	p->prio = p->normal_prio = first_prio_slot(p);
++	if (p->static_prio < rq->expired->best_static_prio)
++		rq->expired->best_static_prio = p->static_prio;
++	reset_first_time_slice(p);
+ }
+ 
++#ifdef CONFIG_SMP
+ /*
+- * __normal_prio - return the priority that is based on the static
+- * priority but is modified by bonuses/penalties.
+- *
+- * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
+- * into the -5 ... 0 ... +5 bonus/penalty range.
+- *
+- * We use 25% of the full 0...39 priority range so that:
+- *
+- * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
+- * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
+- *
+- * Both properties are important to certain workloads.
++ * If we're waking up a task that was previously on a different runqueue,
++ * update its data appropriately. Note we may be reading data from src_rq->
++ * outside of lock, but the occasional inaccurate result should be harmless.
+  */
++ static void update_if_moved(struct task_struct *p, struct rq *rq)
++{
++	struct rq *src_rq = p->array->rq;
+ 
+-static inline int __normal_prio(struct task_struct *p)
++	if (src_rq == rq)
++		return;
++	/*
++	 * Only need to set p->array when p->rotation == rq->prio_rotation as
++	 * they will be set in recalc_task_prio when != rq->prio_rotation.
++	 */
++	if (p->rotation == src_rq->prio_rotation) {
++		p->rotation = rq->prio_rotation;
++		if (p->array == src_rq->expired)
++			p->array = rq->expired;
++		else
++			p->array = rq->active;
++	} else
++		p->rotation = 0;
++}
++#else
++static inline void update_if_moved(struct task_struct *p, struct rq *rq)
++{
++}
++#endif
++
++static inline int isoprio_suitable(struct task_struct *p)
+ {
+-	int bonus, prio;
++	return !(p->flags & PF_ISOREF);
++}
+ 
+-	bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
++static int task_timeslice(struct task_struct *p);
+ 
+-	prio = p->static_prio - bonus;
+-	if (prio < MAX_RT_PRIO)
+-		prio = MAX_RT_PRIO;
+-	if (prio > MAX_PRIO-1)
+-		prio = MAX_PRIO-1;
+-	return prio;
++/*
++ * recalc_task_prio determines what priority a non rt_task will be
++ * queued at. If the task has already been running during this runqueue's
++ * major rotation (rq->prio_rotation) then it continues at the same
++ * priority if it has tick entitlement left. If it does not have entitlement
++ * left, it finds the next priority slot according to its nice value that it
++ * has not extracted quota from. If it has not run during this major
++ * rotation, it starts at the next_entitled_slot and has its bitmap quota
++ * cleared. If it does not have any slots left it has all its slots reset and
++ * is queued on the expired at its first_prio_slot.
++ */
++static void recalc_task_prio(struct task_struct *p, struct rq *rq)
++{
++	struct prio_array *array = rq->active;
++	int queue_prio;
++
++	if (iso_task(p)) {
++		if (isoprio_suitable(p)) {
++			/*
++			 * If SCHED_ISO tasks have not used up their real time
++			 * quota they have run just better than highest
++			 * SCHED_NORMAL priority. Otherwise they run as
++			 * SCHED_NORMAL.
++			 */
++			p->prio = p->normal_prio = ISO_PRIO;
++			p->array = rq->active;
++			if (p->time_slice <= 0)
++				p->time_slice = p->quota;
++			return;
++		} else if (p->prio == ISO_PRIO) {
++			/* Just about to be demoted to SCHED_NORMAL */
++			p->time_slice = 0;
++		}
++	} else if (idleprio_task(p)) {
++		if (idleprio_suitable(p)) {
++			/*
++			 * If suitable idleprio_tasks are queued at MAX_PRIO
++			 * only on the idleprio array. Their time_slice is
++			 * their full task_timeslice as they cooperatively
++			 * multitask.
++			 */
++			p->prio = p->normal_prio = MAX_PRIO;
++			p->array = rq->idleprio;
++			if (p->time_slice <= 0)
++				p->time_slice = task_timeslice(p);
++			return;
++		}
++		/*
++		 * If unsuitable idleprio_tasks are queued equivalent to
++		 * nice 19 tasks on the expired array.
++		 */
++		p->flags &= ~PF_NONSLEEP;
++		p->prio = p->normal_prio = MAX_PRIO - 1;
++		p->array = rq->expired;
++		if (p->time_slice <= 0 || p->time_slice > p->quota)
++			p->time_slice = p->quota;
++		return;
++	}
++
++	update_if_moved(p, rq);
++	if (p->rotation == rq->prio_rotation) {
++		if (p->array == array) {
++			if (p->time_slice > 0)
++				return;
++			p->time_slice = p->quota;
++		} else if (p->array == rq->expired) {
++			queue_expired(p, rq);
++			return;
++		} else
++			task_new_array(p, rq, array);
++	} else
++		task_new_array(p, rq, array);
++
++	queue_prio = next_entitled_slot(p, rq);
++	if (queue_prio >= MAX_PRIO) {
++		queue_expired(p, rq);
++		return;
++	}
++	p->prio = p->normal_prio = queue_prio;
++	__set_bit(USER_PRIO(p->prio), p->bitmap);
++}
++
++/*
++ * Adding to a runqueue. The dynamic priority queue that it is added to is
++ * determined by recalc_task_prio() above.
++ */
++static inline void __enqueue_task(struct task_struct *p, struct rq *rq)
++{
++	if (rt_task(p))
++		p->array = rq->active;
++	else
++		recalc_task_prio(p, rq);
++
++	if (idleprio_task(p) && idleprio(p))
++		rq->nr_idleprio++;
++	sched_info_queued(p);
++	set_dynamic_bit(p, rq);
++}
++
++static void enqueue_task(struct task_struct *p, struct rq *rq)
++{
++	__enqueue_task(p, rq);
++	list_add_tail(&p->run_list, p->array->queue + p->prio);
++}
++
++static inline void enqueue_task_head(struct task_struct *p, struct rq *rq)
++{
++	__enqueue_task(p, rq);
++	list_add(&p->run_list, p->array->queue + p->prio);
++}
++
++/*
++ * requeue_task is only called when p->static_prio does not change. p->prio
++ * can change with dynamic tasks.
++ */
++static void requeue_task(struct task_struct *p, struct rq *rq,
++			 struct prio_array *old_array, int old_prio)
++{
++	if (p->array == rq->expired)
++		queue_expired(p, rq);
++	list_move_tail(&p->run_list, p->array->queue + p->prio);
++	if (!rt_task(p)) {
++		if (list_empty(old_array->queue + old_prio))
++			__clear_bit(old_prio, old_array->prio_bitmap);
++		set_dynamic_bit(p, rq);
++	}
+ }
+ 
+ /*
+@@ -759,20 +964,29 @@ static inline int __normal_prio(struct t
+  */
+ 
+ /*
+- * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
+- * If static_prio_timeslice() is ever changed to break this assumption then
+- * this code will need modification
+- */
+-#define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
+-#define LOAD_WEIGHT(lp) \
+-	(((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
+-#define PRIO_TO_LOAD_WEIGHT(prio) \
+-	LOAD_WEIGHT(static_prio_timeslice(prio))
+-#define RTPRIO_TO_LOAD_WEIGHT(rp) \
+-	(PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
++ * task_timeslice - the total duration a task can run during one major
++ * rotation. Returns value in milliseconds as the smallest value can be 1.
++ */
++static int task_timeslice(struct task_struct *p)
++{
++	int slice = p->quota;	/* quota is in us */
++
++	if (!rt_task(p))
++		slice += (PRIO_RANGE - 1 - TASK_USER_PRIO(p)) * slice;
++	return US_TO_MS(slice);
++}
++
++/*
++ * The load weight is basically the task_timeslice in ms. Realtime tasks are
++ * special cased to be proportionately larger than nice -20 by their
++ * rt_priority. The weight for rt tasks can only be arbitrary at best.
++ */
++#define RTPRIO_TO_LOAD_WEIGHT(rp)	(rr_interval * 20 * (40 + rp))
+ 
+ static void set_load_weight(struct task_struct *p)
+ {
++	int load_weight;
++
+ 	if (has_rt_policy(p)) {
+ #ifdef CONFIG_SMP
+ 		if (p == task_rq(p)->migration_thread)
+@@ -781,12 +995,19 @@ static void set_load_weight(struct task_
+ 			 * Giving its load any weight will skew balancing
+ 			 * adversely.
+ 			 */
+-			p->load_weight = 0;
++			load_weight = 0;
+ 		else
+ #endif
+-			p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
++			load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
+ 	} else
+-		p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
++		load_weight = task_timeslice(p);
++	/*
++	 * idleprio tasks have much lower weight than SCHED_NORMAL tasks but
++	 * still need to be weighted to allow balancing to occur.
++	 */
++	if (likely(!idleprio_task(p)))
++		load_weight *= PRIO_RANGE;
++	p->load_weight = load_weight;
+ }
+ 
+ static inline void
+@@ -814,28 +1035,38 @@ static inline void dec_nr_running(struct
+ }
+ 
+ /*
+- * Calculate the expected normal priority: i.e. priority
+- * without taking RT-inheritance into account. Might be
+- * boosted by interactivity modifiers. Changes upon fork,
+- * setprio syscalls, and whenever the interactivity
+- * estimator recalculates.
++ * __activate_task - move a task to the runqueue.
+  */
+-static inline int normal_prio(struct task_struct *p)
++static inline void __activate_task(struct task_struct *p, struct rq *rq)
+ {
+-	int prio;
++	enqueue_task(p, rq);
++	inc_nr_running(p, rq);
++}
+ 
++/*
++ * __activate_idle_task - move idle task to the _front_ of runqueue.
++ */
++static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
++{
++	enqueue_task_head(p, rq);
++	inc_nr_running(p, rq);
++}
++
++static inline int normal_prio(struct task_struct *p)
++{
+ 	if (has_rt_policy(p))
+-		prio = MAX_RT_PRIO-1 - p->rt_priority;
++		return MAX_RT_PRIO-1 - p->rt_priority;
++	/* Other tasks all have normal_prio set in recalc_task_prio */
++	if (likely(p->prio >= MAX_RT_PRIO && p->prio < MAX_PRIO))
++		return p->prio;
+ 	else
+-		prio = __normal_prio(p);
+-	return prio;
++		return p->static_prio;
+ }
+ 
+ /*
+  * Calculate the current priority, i.e. the priority
+  * taken into account by the scheduler. This value might
+- * be boosted by RT tasks, or might be boosted by
+- * interactivity modifiers. Will be RT if the task got
++ * be boosted by RT tasks as it will be RT if the task got
+  * RT-boosted. If not then it returns p->normal_prio.
+  */
+ static int effective_prio(struct task_struct *p)
+@@ -852,111 +1083,41 @@ static int effective_prio(struct task_st
+ }
+ 
+ /*
+- * __activate_task - move a task to the runqueue.
++ * All tasks have quotas based on rr_interval. RT tasks all get rr_interval.
++ * From nice 1 to 19 they are smaller than it only if they are at least one
++ * tick still. Below nice 0 they get progressively larger.
++ * ie nice -6..0 = rr_interval. nice -10 = 2.5 * rr_interval
++ * nice -20 = 10 * rr_interval. nice 1-19 = rr_interval / 2.
++ * Value returned is in microseconds.
+  */
+-static void __activate_task(struct task_struct *p, struct rq *rq)
++static inline unsigned int rr_quota(struct task_struct *p)
+ {
+-	struct prio_array *target = rq->active;
++	int nice = TASK_NICE(p), rr = rr_interval;
+ 
+-	if (batch_task(p))
+-		target = rq->expired;
+-	enqueue_task(p, target);
+-	inc_nr_running(p, rq);
+-}
+-
+-/*
+- * __activate_idle_task - move idle task to the _front_ of runqueue.
+- */
+-static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
+-{
+-	enqueue_task_head(p, rq->active);
+-	inc_nr_running(p, rq);
++	if (!rt_task(p)) {
++		if (nice < -6) {
++			rr *= nice * nice;
++			rr /= 40;
++		} else if (nice > 0)
++			rr = rr / 2 ? : 1;
++	}
++	return MS_TO_US(rr);
+ }
+ 
+-/*
+- * Recalculate p->normal_prio and p->prio after having slept,
+- * updating the sleep-average too:
+- */
+-static int recalc_task_prio(struct task_struct *p, unsigned long long now)
++/* Every time we set the quota we need to set the load weight */
++static void set_quota(struct task_struct *p)
+ {
+-	/* Caller must always ensure 'now >= p->timestamp' */
+-	unsigned long sleep_time = now - p->timestamp;
+-
+-	if (batch_task(p))
+-		sleep_time = 0;
+-
+-	if (likely(sleep_time > 0)) {
+-		/*
+-		 * This ceiling is set to the lowest priority that would allow
+-		 * a task to be reinserted into the active array on timeslice
+-		 * completion.
+-		 */
+-		unsigned long ceiling = INTERACTIVE_SLEEP(p);
+-
+-		if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
+-			/*
+-			 * Prevents user tasks from achieving best priority
+-			 * with one single large enough sleep.
+-			 */
+-			p->sleep_avg = ceiling;
+-			/*
+-			 * Using INTERACTIVE_SLEEP() as a ceiling places a
+-			 * nice(0) task 1ms sleep away from promotion, and
+-			 * gives it 700ms to round-robin with no chance of
+-			 * being demoted.  This is more than generous, so
+-			 * mark this sleep as non-interactive to prevent the
+-			 * on-runqueue bonus logic from intervening should
+-			 * this task not receive cpu immediately.
+-			 */
+-			p->sleep_type = SLEEP_NONINTERACTIVE;
+-		} else {
+-			/*
+-			 * Tasks waking from uninterruptible sleep are
+-			 * limited in their sleep_avg rise as they
+-			 * are likely to be waiting on I/O
+-			 */
+-			if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
+-				if (p->sleep_avg >= ceiling)
+-					sleep_time = 0;
+-				else if (p->sleep_avg + sleep_time >=
+-					 ceiling) {
+-						p->sleep_avg = ceiling;
+-						sleep_time = 0;
+-				}
+-			}
+-
+-			/*
+-			 * This code gives a bonus to interactive tasks.
+-			 *
+-			 * The boost works by updating the 'average sleep time'
+-			 * value here, based on ->timestamp. The more time a
+-			 * task spends sleeping, the higher the average gets -
+-			 * and the higher the priority boost gets as well.
+-			 */
+-			p->sleep_avg += sleep_time;
+-
+-		}
+-		if (p->sleep_avg > NS_MAX_SLEEP_AVG)
+-			p->sleep_avg = NS_MAX_SLEEP_AVG;
+-	}
+-
+-	return effective_prio(p);
++	p->quota = rr_quota(p);
++	set_load_weight(p);
+ }
+ 
+ /*
+  * activate_task - move a task to the runqueue and do priority recalculation
+- *
+- * Update all the scheduling statistics stuff. (sleep average
+- * calculation, priority modifiers, etc.)
+  */
+ static void activate_task(struct task_struct *p, struct rq *rq, int local)
+ {
+-	unsigned long long now;
+-
+-	if (rt_task(p))
+-		goto out;
++	unsigned long long now = sched_clock();
+ 
+-	now = sched_clock();
+ #ifdef CONFIG_SMP
+ 	if (!local) {
+ 		/* Compensate for drifting sched_clock */
+@@ -977,32 +1138,9 @@ static void activate_task(struct task_st
+ 				     (now - p->timestamp) >> 20);
+ 	}
+ 
+-	p->prio = recalc_task_prio(p, now);
+-
+-	/*
+-	 * This checks to make sure it's not an uninterruptible task
+-	 * that is now waking up.
+-	 */
+-	if (p->sleep_type == SLEEP_NORMAL) {
+-		/*
+-		 * Tasks which were woken up by interrupts (ie. hw events)
+-		 * are most likely of interactive nature. So we give them
+-		 * the credit of extending their sleep time to the period
+-		 * of time they spend on the runqueue, waiting for execution
+-		 * on a CPU, first time around:
+-		 */
+-		if (in_interrupt())
+-			p->sleep_type = SLEEP_INTERRUPTED;
+-		else {
+-			/*
+-			 * Normal first-time wakeups get a credit too for
+-			 * on-runqueue time, but it will be weighted down:
+-			 */
+-			p->sleep_type = SLEEP_INTERACTIVE;
+-		}
+-	}
++	set_quota(p);
++	p->prio = effective_prio(p);
+ 	p->timestamp = now;
+-out:
+ 	__activate_task(p, rq);
+ }
+ 
+@@ -1012,8 +1150,7 @@ out:
+ static void deactivate_task(struct task_struct *p, struct rq *rq)
+ {
+ 	dec_nr_running(p, rq);
+-	dequeue_task(p, p->array);
+-	p->array = NULL;
++	dequeue_task(p, rq);
+ }
+ 
+ /*
+@@ -1095,7 +1232,7 @@ migrate_task(struct task_struct *p, int 
+ 	 * If the task is not on a runqueue (and not running), then
+ 	 * it is sufficient to simply update the task's cpu field.
+ 	 */
+-	if (!p->array && !task_running(rq, p)) {
++	if (!task_queued(p) && !task_running(rq, p)) {
+ 		set_task_cpu(p, dest_cpu);
+ 		return 0;
+ 	}
+@@ -1126,7 +1263,7 @@ void wait_task_inactive(struct task_stru
+ repeat:
+ 	rq = task_rq_lock(p, &flags);
+ 	/* Must be off runqueue entirely, not preempted. */
+-	if (unlikely(p->array || task_running(rq, p))) {
++	if (unlikely(task_queued(p) || task_running(rq, p))) {
+ 		/* If it's preempted, we yield.  It could be a while. */
+ 		preempted = !task_running(rq, p);
+ 		task_rq_unlock(rq, &flags);
+@@ -1391,6 +1528,31 @@ static inline int wake_idle(int cpu, str
+ }
+ #endif
+ 
++/*
++ * We need to have a special definition for an idle runqueue when testing
++ * for preemption on CONFIG_HOTPLUG_CPU as the idle task may be scheduled as
++ * a realtime task in sched_idle_next.
++ */
++#ifdef CONFIG_HOTPLUG_CPU
++#define rq_idle(rq)	((rq)->curr == (rq)->idle && !rt_task((rq)->curr))
++#else
++#define rq_idle(rq)	((rq)->curr == (rq)->idle)
++#endif
++
++static inline int task_preempts_curr(struct task_struct *p, struct rq *rq)
++{
++	struct task_struct *curr = rq->curr;
++
++	return ((p->array == task_rq(p)->active &&
++		TASK_PREEMPTS_CURR(p, curr)) || rq_idle(rq));
++}
++
++static inline void try_preempt(struct task_struct *p, struct rq *rq)
++{
++	if (task_preempts_curr(p, rq))
++		resched_task(rq->curr);
++}
++
+ /***
+  * try_to_wake_up - wake up a thread
+  * @p: the to-be-woken-up thread
+@@ -1422,7 +1584,7 @@ static int try_to_wake_up(struct task_st
+ 	if (!(old_state & state))
+ 		goto out;
+ 
+-	if (p->array)
++	if (task_queued(p))
+ 		goto out_running;
+ 
+ 	cpu = task_cpu(p);
+@@ -1515,7 +1677,7 @@ out_set_cpu:
+ 		old_state = p->state;
+ 		if (!(old_state & state))
+ 			goto out;
+-		if (p->array)
++		if (task_queued(p))
+ 			goto out_running;
+ 
+ 		this_cpu = smp_processor_id();
+@@ -1524,25 +1686,9 @@ out_set_cpu:
+ 
+ out_activate:
+ #endif /* CONFIG_SMP */
+-	if (old_state == TASK_UNINTERRUPTIBLE) {
++	if (old_state == TASK_UNINTERRUPTIBLE)
+ 		rq->nr_uninterruptible--;
+-		/*
+-		 * Tasks on involuntary sleep don't earn
+-		 * sleep_avg beyond just interactive state.
+-		 */
+-		p->sleep_type = SLEEP_NONINTERACTIVE;
+-	} else
+-
+-	/*
+-	 * Tasks that have marked their sleep as noninteractive get
+-	 * woken up with their sleep average not weighted in an
+-	 * interactive way.
+-	 */
+-		if (old_state & TASK_NONINTERACTIVE)
+-			p->sleep_type = SLEEP_NONINTERACTIVE;
+ 
+-
+-	activate_task(p, rq, cpu == this_cpu);
+ 	/*
+ 	 * Sync wakeups (i.e. those types of wakeups where the waker
+ 	 * has indicated that it will leave the CPU in short order)
+@@ -1551,15 +1697,22 @@ out_activate:
+ 	 * the waker guarantees that the freshly woken up task is going
+ 	 * to be considered on this CPU.)
+ 	 */
+-	if (!sync || cpu != this_cpu) {
+-		if (TASK_PREEMPTS_CURR(p, rq))
+-			resched_task(rq->curr);
+-	}
++	activate_task(p, rq, cpu == this_cpu);
++	if (!sync || cpu != this_cpu)
++		try_preempt(p, rq);
+ 	success = 1;
+ 
+ out_running:
+ 	p->state = TASK_RUNNING;
+ out:
++	/*
++	 * Special case when freezing we need to reschedule idleprio tasks
++	 * as SCHED_NORMAL or else they'll never freeze
++	 */
++	if (idleprio_task(p) && freezing(p) && idleprio(p)) {
++		dequeue_task(p, rq);
++		enqueue_task(p, rq);
++	}
+ 	task_rq_unlock(rq, &flags);
+ 
+ 	return success;
+@@ -1577,7 +1730,6 @@ int fastcall wake_up_state(struct task_s
+ 	return try_to_wake_up(p, state, 0);
+ }
+ 
+-static void task_running_tick(struct rq *rq, struct task_struct *p);
+ /*
+  * Perform scheduler related setup for a newly forked process p.
+  * p is forked by current.
+@@ -1605,7 +1757,6 @@ void fastcall sched_fork(struct task_str
+ 	p->prio = current->normal_prio;
+ 
+ 	INIT_LIST_HEAD(&p->run_list);
+-	p->array = NULL;
+ #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
+ 	if (unlikely(sched_info_on()))
+ 		memset(&p->sched_info, 0, sizeof(p->sched_info));
+@@ -1617,30 +1768,31 @@ void fastcall sched_fork(struct task_str
+ 	/* Want to start with kernel preemption disabled. */
+ 	task_thread_info(p)->preempt_count = 1;
+ #endif
++	if (unlikely(p->policy == SCHED_FIFO))
++		goto out;
+ 	/*
+ 	 * Share the timeslice between parent and child, thus the
+ 	 * total amount of pending timeslices in the system doesn't change,
+ 	 * resulting in more scheduling fairness.
+ 	 */
+ 	local_irq_disable();
+-	p->time_slice = (current->time_slice + 1) >> 1;
+-	/*
+-	 * The remainder of the first timeslice might be recovered by
+-	 * the parent if the child exits early enough.
+-	 */
+-	p->first_time_slice = 1;
+-	current->time_slice >>= 1;
+-	p->timestamp = sched_clock();
+-	if (unlikely(!current->time_slice)) {
++	if (current->time_slice > 0) {
++		current->time_slice /= 2;
++		if (current->time_slice)
++			p->time_slice = current->time_slice;
++		else
++			p->time_slice = 1;
+ 		/*
+-		 * This case is rare, it happens when the parent has only
+-		 * a single jiffy left from its timeslice. Taking the
+-		 * runqueue lock is not a problem.
++		 * The remainder of the first timeslice might be recovered by
++		 * the parent if the child exits early enough.
+ 		 */
+-		current->time_slice = 1;
+-		task_running_tick(cpu_rq(cpu), current);
+-	}
++		p->first_time_slice = 1;
++	} else
++		p->time_slice = 0;
++
++	p->timestamp = sched_clock();
+ 	local_irq_enable();
++out:
+ 	put_cpu();
+ }
+ 
+@@ -1662,38 +1814,16 @@ void fastcall wake_up_new_task(struct ta
+ 	this_cpu = smp_processor_id();
+ 	cpu = task_cpu(p);
+ 
+-	/*
+-	 * We decrease the sleep average of forking parents
+-	 * and children as well, to keep max-interactive tasks
+-	 * from forking tasks that are max-interactive. The parent
+-	 * (current) is done further down, under its lock.
+-	 */
+-	p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
+-		CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
+-
+-	p->prio = effective_prio(p);
+-
+ 	if (likely(cpu == this_cpu)) {
++		activate_task(p, rq, 1);
+ 		if (!(clone_flags & CLONE_VM)) {
+ 			/*
+ 			 * The VM isn't cloned, so we're in a good position to
+ 			 * do child-runs-first in anticipation of an exec. This
+ 			 * usually avoids a lot of COW overhead.
+ 			 */
+-			if (unlikely(!current->array))
+-				__activate_task(p, rq);
+-			else {
+-				p->prio = current->prio;
+-				p->normal_prio = current->normal_prio;
+-				list_add_tail(&p->run_list, &current->run_list);
+-				p->array = current->array;
+-				p->array->nr_active++;
+-				inc_nr_running(p, rq);
+-			}
+ 			set_need_resched();
+-		} else
+-			/* Run child last */
+-			__activate_task(p, rq);
++		}
+ 		/*
+ 		 * We skip the following code due to cpu == this_cpu
+ 	 	 *
+@@ -1710,19 +1840,16 @@ void fastcall wake_up_new_task(struct ta
+ 		 */
+ 		p->timestamp = (p->timestamp - this_rq->most_recent_timestamp)
+ 					+ rq->most_recent_timestamp;
+-		__activate_task(p, rq);
+-		if (TASK_PREEMPTS_CURR(p, rq))
+-			resched_task(rq->curr);
++		activate_task(p, rq, 0);
++		try_preempt(p, rq);
+ 
+ 		/*
+ 		 * Parent and child are on different CPUs, now get the
+-		 * parent runqueue to update the parent's ->sleep_avg:
++		 * parent runqueue to update the parent's ->flags:
+ 		 */
+ 		task_rq_unlock(rq, &flags);
+ 		this_rq = task_rq_lock(current, &flags);
+ 	}
+-	current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
+-		PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
+ 	task_rq_unlock(this_rq, &flags);
+ }
+ 
+@@ -1737,23 +1864,17 @@ void fastcall wake_up_new_task(struct ta
+  */
+ void fastcall sched_exit(struct task_struct *p)
+ {
++	struct task_struct *parent;
+ 	unsigned long flags;
+ 	struct rq *rq;
+ 
+-	/*
+-	 * If the child was a (relative-) CPU hog then decrease
+-	 * the sleep_avg of the parent as well.
+-	 */
+-	rq = task_rq_lock(p->parent, &flags);
+-	if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
+-		p->parent->time_slice += p->time_slice;
+-		if (unlikely(p->parent->time_slice > task_timeslice(p)))
+-			p->parent->time_slice = task_timeslice(p);
+-	}
+-	if (p->sleep_avg < p->parent->sleep_avg)
+-		p->parent->sleep_avg = p->parent->sleep_avg /
+-		(EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
+-		(EXIT_WEIGHT + 1);
++	parent = p->parent;
++	rq = task_rq_lock(parent, &flags);
++	if (p->first_time_slice > 0 && task_cpu(p) == task_cpu(parent)) {
++		parent->time_slice += p->time_slice;
++		if (unlikely(parent->time_slice > parent->quota))
++			parent->time_slice = parent->quota;
++	}
+ 	task_rq_unlock(rq, &flags);
+ }
+ 
+@@ -2085,23 +2206,17 @@ void sched_exec(void)
+  * pull_task - move a task from a remote runqueue to the local runqueue.
+  * Both runqueues must be locked.
+  */
+-static void pull_task(struct rq *src_rq, struct prio_array *src_array,
+-		      struct task_struct *p, struct rq *this_rq,
+-		      struct prio_array *this_array, int this_cpu)
++static void pull_task(struct rq *src_rq, struct task_struct *p,
++		      struct rq *this_rq, int this_cpu)
+ {
+-	dequeue_task(p, src_array);
++	dequeue_task(p, src_rq);
+ 	dec_nr_running(p, src_rq);
+ 	set_task_cpu(p, this_cpu);
+ 	inc_nr_running(p, this_rq);
+-	enqueue_task(p, this_array);
++	enqueue_task(p, this_rq);
+ 	p->timestamp = (p->timestamp - src_rq->most_recent_timestamp)
+ 				+ this_rq->most_recent_timestamp;
+-	/*
+-	 * Note that idle threads have a prio of MAX_PRIO, for this test
+-	 * to be always true for them.
+-	 */
+-	if (TASK_PREEMPTS_CURR(p, this_rq))
+-		resched_task(this_rq->curr);
++	try_preempt(p, this_rq);
+ }
+ 
+ /*
+@@ -2144,7 +2259,16 @@ int can_migrate_task(struct task_struct 
+ 	return 1;
+ }
+ 
+-#define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
++static inline int rq_best_prio(struct rq *rq)
++{
++	int best_prio, exp_prio;
++
++	best_prio = sched_find_first_bit(rq->dyn_bitmap);
++	exp_prio = find_next_bit(rq->exp_bitmap, MAX_PRIO, MAX_RT_PRIO);
++	if (unlikely(best_prio > exp_prio))
++		best_prio = exp_prio;
++	return best_prio;
++}
+ 
+ /*
+  * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
+@@ -2160,7 +2284,7 @@ static int move_tasks(struct rq *this_rq
+ {
+ 	int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
+ 	    best_prio_seen, skip_for_load;
+-	struct prio_array *array, *dst_array;
++	struct prio_array *array;
+ 	struct list_head *head, *curr;
+ 	struct task_struct *tmp;
+ 	long rem_load_move;
+@@ -2187,31 +2311,29 @@ static int move_tasks(struct rq *this_rq
+ 	 * be cache-cold, thus switching CPUs has the least effect
+ 	 * on them.
+ 	 */
+-	if (busiest->expired->nr_active) {
+-		array = busiest->expired;
+-		dst_array = this_rq->expired;
+-	} else {
+-		array = busiest->active;
+-		dst_array = this_rq->active;
+-	}
+-
++	array = busiest->expired;
+ new_array:
+-	/* Start searching at priority 0: */
+-	idx = 0;
++	/* Expired arrays don't have RT tasks so they're always MAX_RT_PRIO+ */
++	if (array == busiest->expired)
++		idx = MAX_RT_PRIO;
++	else
++		idx = 0;
+ skip_bitmap:
+ 	if (!idx)
+-		idx = sched_find_first_bit(array->bitmap);
++		idx = sched_find_first_bit(array->prio_bitmap);
+ 	else
+-		idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
+-	if (idx >= MAX_PRIO) {
+-		if (array == busiest->expired && busiest->active->nr_active) {
++		idx = find_next_bit(array->prio_bitmap, MAX_PRIO, idx);
++	if (idx == MAX_PRIO) {
++		if (array == busiest->idleprio && busiest->nr_idleprio)
++			goto found_idleprio;
++		if (array == busiest->expired) {
+ 			array = busiest->active;
+-			dst_array = this_rq->active;
+ 			goto new_array;
+ 		}
+ 		goto out;
+ 	}
+ 
++found_idleprio:
+ 	head = array->queue + idx;
+ 	curr = head->prev;
+ skip_queue:
+@@ -2233,11 +2355,22 @@ skip_queue:
+ 		best_prio_seen |= idx == best_prio;
+ 		if (curr != head)
+ 			goto skip_queue;
++		if (idx == MAX_PRIO) {
++			/*
++			 * Occurs either when balancing idleprio tasks or
++			 * there really are no more tasks to find.
++			 */
++			if (array == busiest->expired) {
++				array = busiest->active;
++				goto new_array;
++			}
++			goto out;
++		}
+ 		idx++;
+ 		goto skip_bitmap;
+ 	}
+ 
+-	pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
++	pull_task(busiest, tmp, this_rq, this_cpu);
+ 	pulled++;
+ 	rem_load_move -= tmp->load_weight;
+ 
+@@ -2250,6 +2383,13 @@ skip_queue:
+ 			this_best_prio = idx;
+ 		if (curr != head)
+ 			goto skip_queue;
++		if (idx == MAX_PRIO) {
++			if (array == busiest->expired) {
++				array = busiest->active;
++				goto new_array;
++			}
++			goto out;
++		}
+ 		idx++;
+ 		goto skip_bitmap;
+ 	}
+@@ -3013,11 +3153,36 @@ EXPORT_PER_CPU_SYMBOL(kstat);
+ /*
+  * This is called on clock ticks and on context switches.
+  * Bank in p->sched_time the ns elapsed since the last tick or switch.
++ * CPU scheduler quota accounting is also performed here in microseconds.
++ * The value returned from sched_clock() occasionally gives bogus values so
++ * some sanity checking is required.
+  */
+-static inline void
+-update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
++static void
++update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now,
++		 int tick)
+ {
+-	p->sched_time += now - p->last_ran;
++	long time_diff = now - p->last_ran;
++
++	if (tick) {
++		/*
++		 * Called from scheduler_tick() there should be less than two
++		 * jiffies worth, and not negative/overflow.
++		 */
++		if (time_diff > JIFFIES_TO_NS(2) || time_diff < 0)
++			time_diff = JIFFIES_TO_NS(1);
++	} else {
++		/*
++		 * Called from context_switch there should be less than one
++		 * jiffy worth, and not negative/overflow. There should be
++		 * some time banked here so use a nominal 1us.
++		 */
++		if (time_diff > JIFFIES_TO_NS(1) || time_diff < 1)
++			time_diff = 1000;
++	}
++	/* time_slice accounting is done in usecs to avoid overflow on 32bit */
++	if (p != rq->idle && p->policy != SCHED_FIFO)
++		p->time_slice -= time_diff / 1000;
++	p->sched_time += time_diff;
+ 	p->last_ran = rq->most_recent_timestamp = now;
+ }
+ 
+@@ -3038,27 +3203,6 @@ unsigned long long current_sched_time(co
+ }
+ 
+ /*
+- * We place interactive tasks back into the active array, if possible.
+- *
+- * To guarantee that this does not starve expired tasks we ignore the
+- * interactivity of a task if the first expired task had to wait more
+- * than a 'reasonable' amount of time. This deadline timeout is
+- * load-dependent, as the frequency of array switched decreases with
+- * increasing number of running tasks. We also ignore the interactivity
+- * if a better static_prio task has expired:
+- */
+-static inline int expired_starving(struct rq *rq)
+-{
+-	if (rq->curr->static_prio > rq->best_expired_prio)
+-		return 1;
+-	if (!STARVATION_LIMIT || !rq->expired_timestamp)
+-		return 0;
+-	if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
+-		return 1;
+-	return 0;
+-}
+-
+-/*
+  * Account user cpu time to a process.
+  * @p: the process that the cpu time gets accounted to
+  * @hardirq_offset: the offset to subtract from hardirq_count()
+@@ -3073,7 +3217,7 @@ void account_user_time(struct task_struc
+ 
+ 	/* Add user time to cpustat. */
+ 	tmp = cputime_to_cputime64(cputime);
+-	if (TASK_NICE(p) > 0)
++	if (TASK_NICE(p) > 0 || idleprio_task(p))
+ 		cpustat->nice = cputime64_add(cpustat->nice, tmp);
+ 	else
+ 		cpustat->user = cputime64_add(cpustat->user, tmp);
+@@ -3131,87 +3275,94 @@ void account_steal_time(struct task_stru
+ 		cpustat->steal = cputime64_add(cpustat->steal, tmp);
+ }
+ 
+-static void task_running_tick(struct rq *rq, struct task_struct *p)
++/*
++ * The task has used up its quota of running in this prio_level so it must be
++ * dropped a priority level, all managed by recalc_task_prio().
++ */
++static void task_expired_entitlement(struct rq *rq, struct task_struct *p)
+ {
+-	if (p->array != rq->active) {
+-		/* Task has expired but was not scheduled yet */
+-		set_tsk_need_resched(p);
++	int overrun;
++
++	reset_first_time_slice(p);
++	if (rt_task(p)) {
++		p->time_slice += p->quota;
++		list_move_tail(&p->run_list, p->array->queue + p->prio);
+ 		return;
+ 	}
+-	spin_lock(&rq->lock);
++	overrun = p->time_slice;
++	dequeue_task(p, rq);
++	enqueue_task(p, rq);
+ 	/*
+-	 * The task was running during this tick - update the
+-	 * time slice counter. Note: we do not update a thread's
+-	 * priority until it either goes to sleep or uses up its
+-	 * timeslice. This makes it possible for interactive tasks
+-	 * to use up their timeslices at their highest priority levels.
++	 * Subtract any extra time this task ran over its time_slice; ie
++	 * overrun will either be 0 or negative.
+ 	 */
+-	if (rt_task(p)) {
+-		/*
+-		 * RR tasks need a special form of timeslice management.
+-		 * FIFO tasks have no timeslices.
+-		 */
+-		if ((p->policy == SCHED_RR) && !--p->time_slice) {
+-			p->time_slice = task_timeslice(p);
+-			p->first_time_slice = 0;
+-			set_tsk_need_resched(p);
++	p->time_slice += overrun;
++}
+ 
+-			/* put it at the end of the queue: */
+-			requeue_task(p, rq->active);
+-		}
+-		goto out_unlock;
++/*
++ * Test if SCHED_ISO tasks have run longer than their alloted period as RT
++ * tasks and set the refractory flag if necessary. There is 10% hysteresis
++ * for unsetting the flag.
++ */
++static unsigned int test_ret_isorefractory(struct rq *rq)
++{
++	if (likely(!rq->iso_refractory)) {
++		if (rq->iso_ticks / ISO_PERIOD > sched_iso_cpu)
++			rq->iso_refractory = 1;
++	} else {
++		if (rq->iso_ticks / ISO_PERIOD < (sched_iso_cpu * 90 / 100))
++			rq->iso_refractory = 0;
+ 	}
+-	if (!--p->time_slice) {
+-		dequeue_task(p, rq->active);
+-		set_tsk_need_resched(p);
+-		p->prio = effective_prio(p);
+-		p->time_slice = task_timeslice(p);
+-		p->first_time_slice = 0;
++	return rq->iso_refractory;
++}
+ 
+-		if (!rq->expired_timestamp)
+-			rq->expired_timestamp = jiffies;
+-		if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
+-			enqueue_task(p, rq->expired);
+-			if (p->static_prio < rq->best_expired_prio)
+-				rq->best_expired_prio = p->static_prio;
+-		} else
+-			enqueue_task(p, rq->active);
+-	} else {
+-		/*
+-		 * Prevent a too long timeslice allowing a task to monopolize
+-		 * the CPU. We do this by splitting up the timeslice into
+-		 * smaller pieces.
+-		 *
+-		 * Note: this does not mean the task's timeslices expire or
+-		 * get lost in any way, they just might be preempted by
+-		 * another task of equal priority. (one with higher
+-		 * priority would have preempted this task already.) We
+-		 * requeue this task to the end of the list on this priority
+-		 * level, which is in essence a round-robin of tasks with
+-		 * equal priority.
+-		 *
+-		 * This only applies to tasks in the interactive
+-		 * delta range with at least TIMESLICE_GRANULARITY to requeue.
+-		 */
+-		if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
+-			p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
+-			(p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
+-			(p->array == rq->active)) {
++/* No SCHED_ISO task was running so decrease rq->iso_ticks */
++static inline void no_iso_tick(struct rq *rq)
++{
++	rq->iso_ticks = rq->iso_ticks * (ISO_PERIOD - 1) / ISO_PERIOD;
++}
+ 
+-			requeue_task(p, rq->active);
+-			set_tsk_need_resched(p);
+-		}
++/* This manages tasks that have run out of timeslice during a scheduler_tick */
++static void task_running_tick(struct rq *rq, struct task_struct *p)
++{
++	/*
++	 * If a SCHED_ISO task is running we increment the iso_ticks. In
++	 * order to prevent SCHED_ISO tasks from causing starvation in the
++	 * presence of true RT tasks we account those as iso_ticks as well.
++	 */
++	if ((rt_task(p) || (iso_task(p) && !rq->iso_refractory))) {
++		if (rq->iso_ticks <= (ISO_PERIOD * 100) - 100)
++			rq->iso_ticks += 100;
++	} else
++		no_iso_tick(rq);
++
++	if (iso_task(p)) {
++		if (unlikely(test_ret_isorefractory(rq))) {
++			if (isoprio_suitable(p)) {
++				/*
++				 * SCHED_ISO task is running as RT and limit
++				 * has been hit. Set the PF_ISOREF flag and
++				 * force it to reschedule as SCHED_NORMAL
++				 * by zeroing its time_slice
++				 */
++				p->flags |= PF_ISOREF;
++				p->time_slice = 0;
++			}
++		} else
++			p->flags &= ~PF_ISOREF;
+ 	}
+-out_unlock:
+-	spin_unlock(&rq->lock);
++	/* SCHED_FIFO tasks never run out of timeslice. */
++	if (p->time_slice > 0 || p->policy == SCHED_FIFO)
++		return;
++	/* p->time_slice <= 0 */
++	set_tsk_need_resched(p);
++	if (likely(task_queued(p)))
++		task_expired_entitlement(rq, p);
+ }
+ 
+ /*
+  * This function gets called by the timer code, with HZ frequency.
+  * We call it with interrupts disabled.
+- *
+- * It also gets called by the fork code, when changing the parent's
+- * timeslices.
+  */
+ void scheduler_tick(void)
+ {
+@@ -3220,10 +3371,14 @@ void scheduler_tick(void)
+ 	int cpu = smp_processor_id();
+ 	struct rq *rq = cpu_rq(cpu);
+ 
+-	update_cpu_clock(p, rq, now);
++	update_cpu_clock(p, rq, now, 1);
+ 
++	spin_lock(&rq->lock);
+ 	if (p != rq->idle)
+ 		task_running_tick(rq, p);
++	else
++		no_iso_tick(rq);
++	spin_unlock(&rq->lock);
+ #ifdef CONFIG_SMP
+ 	update_load(rq);
+ 	if (time_after_eq(jiffies, rq->next_balance))
+@@ -3269,10 +3424,80 @@ EXPORT_SYMBOL(sub_preempt_count);
+ 
+ #endif
+ 
+-static inline int interactive_sleep(enum sleep_type sleep_type)
++static void reset_prio_levels(struct rq *rq)
++{
++	rq->active->best_static_prio = MAX_PRIO - 1;
++	rq->expired->best_static_prio = MAX_PRIO - 1;
++	memset(rq->prio_level, 0, sizeof(int) * PRIO_RANGE);
++}
++
++/*
++ * Only tasks running are SCHED_IDLEPRIO. Set the active array to the
++ * idleprio array and if it isn't already active
++ */
++static struct task_struct *next_idleprio_task(struct rq *rq)
+ {
+-	return (sleep_type == SLEEP_INTERACTIVE ||
+-		sleep_type == SLEEP_INTERRUPTED);
++	struct prio_array *array = rq->active;
++	struct list_head *queue;
++
++	if (array != rq->idleprio) {
++		rq->active = rq->idleprio;
++		rq->expired = array;
++		array = rq->active;
++		rq->exp_bitmap = rq->expired->prio_bitmap;
++		rq->dyn_bitmap = rq->active->prio_bitmap;
++	}
++	rq->prio_rotation++;
++	reset_prio_levels(rq);
++	queue = array->queue + MAX_PRIO;
++	return list_entry(queue->next, struct task_struct, run_list);
++}
++
++/*
++ * next_dynamic_task finds the next suitable dynamic task.
++ */
++static inline struct task_struct *next_dynamic_task(struct rq *rq, int idx)
++{
++	struct prio_array *array = rq->active;
++	struct task_struct *next;
++	struct list_head *queue;
++	int nstatic;
++
++retry:
++	if (unlikely(rq->nr_running == rq->nr_idleprio))
++		return next_idleprio_task(rq);
++	if (idx >= MAX_PRIO) {
++		/* There are no more tasks in the active array. Swap arrays */
++		array = rq->expired;
++		rq->expired = rq->active;
++		rq->active = array;
++		rq->exp_bitmap = rq->expired->prio_bitmap;
++		rq->dyn_bitmap = rq->active->prio_bitmap;
++		rq->prio_rotation++;
++		idx = find_next_bit(rq->dyn_bitmap, MAX_PRIO, MAX_RT_PRIO);
++		reset_prio_levels(rq);
++	}
++	queue = array->queue + idx;
++	next = list_entry(queue->next, struct task_struct, run_list);
++	if (unlikely(next->time_slice <= 0 && !(iso_task(next) &&
++	    isoprio_suitable(next)))) {
++		/*
++		 * Unlucky enough that this task ran out of time_slice
++		 * before it hit a scheduler_tick so it should have its
++		 * priority reassessed and choose another task (possibly
++		 * the same one)
++		 */
++		task_expired_entitlement(rq, next);
++		idx = find_next_bit(rq->dyn_bitmap, MAX_PRIO, MAX_RT_PRIO);
++		goto retry;
++	}
++	next->rotation = rq->prio_rotation;
++	nstatic = next->static_prio;
++	if (nstatic < array->best_static_prio)
++		array->best_static_prio = nstatic;
++	if (idx > rq->prio_level[USER_PRIO(nstatic)])
++		rq->prio_level[USER_PRIO(nstatic)] = idx;
++	return next;
+ }
+ 
+ /*
+@@ -3281,13 +3506,11 @@ static inline int interactive_sleep(enum
+ asmlinkage void __sched schedule(void)
+ {
+ 	struct task_struct *prev, *next;
+-	struct prio_array *array;
+ 	struct list_head *queue;
+ 	unsigned long long now;
+-	unsigned long run_time;
+-	int cpu, idx, new_prio;
+ 	long *switch_count;
+ 	struct rq *rq;
++	int cpu, idx;
+ 
+ 	/*
+ 	 * Test if we are atomic.  Since do_exit() needs to call into
+@@ -3323,18 +3546,6 @@ need_resched_nonpreemptible:
+ 
+ 	schedstat_inc(rq, sched_cnt);
+ 	now = sched_clock();
+-	if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
+-		run_time = now - prev->timestamp;
+-		if (unlikely((long long)(now - prev->timestamp) < 0))
+-			run_time = 0;
+-	} else
+-		run_time = NS_MAX_SLEEP_AVG;
+-
+-	/*
+-	 * Tasks charged proportionately less run_time at high sleep_avg to
+-	 * delay them losing their interactive status
+-	 */
+-	run_time /= (CURRENT_BONUS(prev) ? : 1);
+ 
+ 	spin_lock_irq(&rq->lock);
+ 
+@@ -3345,8 +3556,10 @@ need_resched_nonpreemptible:
+ 				unlikely(signal_pending(prev))))
+ 			prev->state = TASK_RUNNING;
+ 		else {
+-			if (prev->state == TASK_UNINTERRUPTIBLE)
++			if (prev->state == TASK_UNINTERRUPTIBLE) {
++				prev->flags |= PF_NONSLEEP;
+ 				rq->nr_uninterruptible++;
++			}
+ 			deactivate_task(prev, rq);
+ 		}
+ 	}
+@@ -3356,59 +3569,29 @@ need_resched_nonpreemptible:
+ 		idle_balance(cpu, rq);
+ 		if (!rq->nr_running) {
+ 			next = rq->idle;
+-			rq->expired_timestamp = 0;
+ 			goto switch_tasks;
+ 		}
+ 	}
+ 
+-	array = rq->active;
+-	if (unlikely(!array->nr_active)) {
+-		/*
+-		 * Switch the active and expired arrays.
+-		 */
+-		schedstat_inc(rq, sched_switch);
+-		rq->active = rq->expired;
+-		rq->expired = array;
+-		array = rq->active;
+-		rq->expired_timestamp = 0;
+-		rq->best_expired_prio = MAX_PRIO;
++	idx = sched_find_first_bit(rq->dyn_bitmap);
++	if (likely(idx > ISO_PRIO))
++		next = next_dynamic_task(rq, idx);
++	else {
++		queue = rq->active->queue + idx;
++		next = list_entry(queue->next, struct task_struct, run_list);
+ 	}
+-
+-	idx = sched_find_first_bit(array->bitmap);
+-	queue = array->queue + idx;
+-	next = list_entry(queue->next, struct task_struct, run_list);
+-
+-	if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
+-		unsigned long long delta = now - next->timestamp;
+-		if (unlikely((long long)(now - next->timestamp) < 0))
+-			delta = 0;
+-
+-		if (next->sleep_type == SLEEP_INTERACTIVE)
+-			delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
+-
+-		array = next->array;
+-		new_prio = recalc_task_prio(next, next->timestamp + delta);
+-
+-		if (unlikely(next->prio != new_prio)) {
+-			dequeue_task(next, array);
+-			next->prio = new_prio;
+-			enqueue_task(next, array);
+-		}
+-	}
+-	next->sleep_type = SLEEP_NORMAL;
+ switch_tasks:
+-	if (next == rq->idle)
++	if (next == rq->idle) {
++		reset_prio_levels(rq);
++		rq->prio_rotation++;
+ 		schedstat_inc(rq, sched_goidle);
++	}
+ 	prefetch(next);
+ 	prefetch_stack(next);
+ 	clear_tsk_need_resched(prev);
+ 	rcu_qsctr_inc(task_cpu(prev));
+ 
+-	update_cpu_clock(prev, rq, now);
+-
+-	prev->sleep_avg -= run_time;
+-	if ((long)prev->sleep_avg <= 0)
+-		prev->sleep_avg = 0;
++	update_cpu_clock(prev, rq, now, 0);
+ 	prev->timestamp = prev->last_ran = now;
+ 
+ 	sched_info_switch(prev, next);
+@@ -3844,29 +4027,22 @@ EXPORT_SYMBOL(sleep_on_timeout);
+  */
+ void rt_mutex_setprio(struct task_struct *p, int prio)
+ {
+-	struct prio_array *array;
+ 	unsigned long flags;
++	int queued, oldprio;
+ 	struct rq *rq;
+-	int oldprio;
+ 
+ 	BUG_ON(prio < 0 || prio > MAX_PRIO);
+ 
+ 	rq = task_rq_lock(p, &flags);
+ 
+ 	oldprio = p->prio;
+-	array = p->array;
+-	if (array)
+-		dequeue_task(p, array);
++	queued = task_queued(p);
++	if (queued)
++		dequeue_task(p, rq);
+ 	p->prio = prio;
+ 
+-	if (array) {
+-		/*
+-		 * If changing to an RT priority then queue it
+-		 * in the active array!
+-		 */
+-		if (rt_task(p))
+-			array = rq->active;
+-		enqueue_task(p, array);
++	if (queued) {
++		enqueue_task(p, rq);
+ 		/*
+ 		 * Reschedule if we are currently running on this runqueue and
+ 		 * our priority decreased, or if we are not currently running on
+@@ -3875,8 +4051,8 @@ void rt_mutex_setprio(struct task_struct
+ 		if (task_running(rq, p)) {
+ 			if (p->prio > oldprio)
+ 				resched_task(rq->curr);
+-		} else if (TASK_PREEMPTS_CURR(p, rq))
+-			resched_task(rq->curr);
++		} else
++			try_preempt(p, rq);
+ 	}
+ 	task_rq_unlock(rq, &flags);
+ }
+@@ -3885,8 +4061,7 @@ void rt_mutex_setprio(struct task_struct
+ 
+ void set_user_nice(struct task_struct *p, long nice)
+ {
+-	struct prio_array *array;
+-	int old_prio, delta;
++	int queued, old_prio,delta;
+ 	unsigned long flags;
+ 	struct rq *rq;
+ 
+@@ -3907,26 +4082,27 @@ void set_user_nice(struct task_struct *p
+ 		p->static_prio = NICE_TO_PRIO(nice);
+ 		goto out_unlock;
+ 	}
+-	array = p->array;
+-	if (array) {
+-		dequeue_task(p, array);
++	queued = task_queued(p);
++	if (queued) {
++		dequeue_task(p, rq);
+ 		dec_raw_weighted_load(rq, p);
+ 	}
+ 
+ 	p->static_prio = NICE_TO_PRIO(nice);
+-	set_load_weight(p);
+ 	old_prio = p->prio;
+ 	p->prio = effective_prio(p);
++	set_quota(p);
+ 	delta = p->prio - old_prio;
+ 
+-	if (array) {
+-		enqueue_task(p, array);
++	if (queued) {
++		enqueue_task(p, rq);
+ 		inc_raw_weighted_load(rq, p);
+ 		/*
+ 		 * If the task increased its priority or is running and
+ 		 * lowered its priority, then reschedule its CPU:
+ 		 */
+-		if (delta < 0 || (delta > 0 && task_running(rq, p)))
++		if (delta < 0 || ((delta > 0 || idleprio_task(p)) &&
++		    task_running(rq, p)))
+ 			resched_task(rq->curr);
+ 	}
+ out_unlock:
+@@ -3996,7 +4172,7 @@ asmlinkage long sys_nice(int increment)
+  *
+  * This is the priority value as seen by users in /proc.
+  * RT tasks are offset by -200. Normal tasks are centered
+- * around 0, value goes from -16 to +15.
++ * around 0, value goes from 0 to +39.
+  */
+ int task_prio(const struct task_struct *p)
+ {
+@@ -4043,19 +4219,14 @@ static inline struct task_struct *find_p
+ /* Actually do priority change: must hold rq lock. */
+ static void __setscheduler(struct task_struct *p, int policy, int prio)
+ {
+-	BUG_ON(p->array);
++	BUG_ON(task_queued(p));
+ 
+ 	p->policy = policy;
+ 	p->rt_priority = prio;
+ 	p->normal_prio = normal_prio(p);
+ 	/* we are holding p->pi_lock already */
+ 	p->prio = rt_mutex_getprio(p);
+-	/*
+-	 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
+-	 */
+-	if (policy == SCHED_BATCH)
+-		p->sleep_avg = 0;
+-	set_load_weight(p);
++	set_quota(p);
+ }
+ 
+ /**
+@@ -4069,19 +4240,27 @@ static void __setscheduler(struct task_s
+ int sched_setscheduler(struct task_struct *p, int policy,
+ 		       struct sched_param *param)
+ {
+-	int retval, oldprio, oldpolicy = -1;
+-	struct prio_array *array;
++	struct sched_param zero_param = { .sched_priority = 0 };
++	int queued, retval, oldprio, oldpolicy = -1;
+ 	unsigned long flags;
+ 	struct rq *rq;
+ 
+ 	/* may grab non-irq protected spin_locks */
+ 	BUG_ON(in_interrupt());
++	if (is_rt_policy(policy) && !capable(CAP_SYS_NICE)) {
++		/*
++		 * If the caller requested an RT policy without having the
++		 * necessary rights, we downgrade the policy to SCHED_ISO.
++		 * We also set the parameter to zero to pass the checks.
++		 */
++		policy = SCHED_ISO;
++		param = &zero_param;
++	}
+ recheck:
+ 	/* double check policy once rq lock held */
+ 	if (policy < 0)
+ 		policy = oldpolicy = p->policy;
+-	else if (policy != SCHED_FIFO && policy != SCHED_RR &&
+-			policy != SCHED_NORMAL && policy != SCHED_BATCH)
++	else if (!SCHED_RANGE(policy))
+ 		return -EINVAL;
+ 	/*
+ 	 * Valid priorities for SCHED_FIFO and SCHED_RR are
+@@ -4116,6 +4295,31 @@ recheck:
+ 			if (param->sched_priority > p->rt_priority &&
+ 			    param->sched_priority > rlim_rtprio)
+ 				return -EPERM;
++		} else {
++			switch (p->policy) {
++				/*
++				 * Can only downgrade policies but not back to
++				 * SCHED_NORMAL
++				 */
++				case SCHED_ISO:
++					if (policy == SCHED_ISO)
++						goto out;
++					if (policy == SCHED_NORMAL)
++						return -EPERM;
++					break;
++				case SCHED_BATCH:
++					if (policy == SCHED_BATCH)
++						goto out;
++					if (policy != SCHED_IDLEPRIO)
++					    	return -EPERM;
++					break;
++				case SCHED_IDLEPRIO:
++					if (policy == SCHED_IDLEPRIO)
++						goto out;
++					return -EPERM;
++				default:
++					break;
++			}
+ 		}
+ 
+ 		/* can't change other user's priorities */
+@@ -4124,6 +4328,11 @@ recheck:
+ 			return -EPERM;
+ 	}
+ 
++	if (!(p->mm) && policy == SCHED_IDLEPRIO) {
++		/* Don't allow kernel threads to be SCHED_IDLEPRIO. */
++		return -EINVAL;
++	}
++
+ 	retval = security_task_setscheduler(p, policy, param);
+ 	if (retval)
+ 		return retval;
+@@ -4144,12 +4353,12 @@ recheck:
+ 		spin_unlock_irqrestore(&p->pi_lock, flags);
+ 		goto recheck;
+ 	}
+-	array = p->array;
+-	if (array)
++	queued = task_queued(p);
++	if (queued)
+ 		deactivate_task(p, rq);
+ 	oldprio = p->prio;
+ 	__setscheduler(p, policy, param->sched_priority);
+-	if (array) {
++	if (queued) {
+ 		__activate_task(p, rq);
+ 		/*
+ 		 * Reschedule if we are currently running on this runqueue and
+@@ -4159,14 +4368,15 @@ recheck:
+ 		if (task_running(rq, p)) {
+ 			if (p->prio > oldprio)
+ 				resched_task(rq->curr);
+-		} else if (TASK_PREEMPTS_CURR(p, rq))
+-			resched_task(rq->curr);
++		} else
++			try_preempt(p, rq);
+ 	}
+ 	__task_rq_unlock(rq);
+ 	spin_unlock_irqrestore(&p->pi_lock, flags);
+ 
+ 	rt_mutex_adjust_pi(p);
+ 
++out:
+ 	return 0;
+ }
+ EXPORT_SYMBOL_GPL(sched_setscheduler);
+@@ -4433,41 +4643,34 @@ asmlinkage long sys_sched_getaffinity(pi
+  * sys_sched_yield - yield the current processor to other threads.
+  *
+  * This function yields the current CPU by moving the calling thread
+- * to the expired array. If there are no other threads running on this
+- * CPU then this function will return.
++ * to the expired array if SCHED_NORMAL or the end of its current priority
++ * queue if a realtime task. If there are no other threads running on this
++ * cpu this function will return.
+  */
+ asmlinkage long sys_sched_yield(void)
+ {
+ 	struct rq *rq = this_rq_lock();
+-	struct prio_array *array = current->array, *target = rq->expired;
++	struct task_struct *p = current;
+ 
+ 	schedstat_inc(rq, yld_cnt);
+-	/*
+-	 * We implement yielding by moving the task into the expired
+-	 * queue.
+-	 *
+-	 * (special rule: RT tasks will just roundrobin in the active
+-	 *  array.)
+-	 */
+-	if (rt_task(current))
+-		target = rq->active;
+-
+-	if (array->nr_active == 1) {
+-		schedstat_inc(rq, yld_act_empty);
+-		if (!rq->expired->nr_active)
+-			schedstat_inc(rq, yld_both_empty);
+-	} else if (!rq->expired->nr_active)
+-		schedstat_inc(rq, yld_exp_empty);
+-
+-	if (array != target) {
+-		dequeue_task(current, array);
+-		enqueue_task(current, target);
+-	} else
+-		/*
+-		 * requeue_task is cheaper so perform that if possible.
+-		 */
+-		requeue_task(current, array);
++	if (rq->nr_running == 1)
++		schedstat_inc(rq, yld_both_empty);
++	else {
++		struct prio_array *old_array = p->array;
++		int old_prio = p->prio;
++
++		if (idleprio_task(p)) {
++			dequeue_task(p, rq);
++			enqueue_task(p, rq);
++			goto out_release;
++		}
++		/* p->prio will be updated in requeue_task via queue_expired */
++		if (!rt_task(p))
++			p->array = rq->expired;
++		requeue_task(p, rq, old_array, old_prio);
++	}
+ 
++out_release:
+ 	/*
+ 	 * Since we are going to call schedule() anyway, there's
+ 	 * no need to preempt or enable interrupts:
+@@ -4619,6 +4822,8 @@ asmlinkage long sys_sched_get_priority_m
+ 		break;
+ 	case SCHED_NORMAL:
+ 	case SCHED_BATCH:
++	case SCHED_ISO:
++	case SCHED_IDLEPRIO:
+ 		ret = 0;
+ 		break;
+ 	}
+@@ -4643,6 +4848,8 @@ asmlinkage long sys_sched_get_priority_m
+ 		break;
+ 	case SCHED_NORMAL:
+ 	case SCHED_BATCH:
++	case SCHED_ISO:
++	case SCHED_IDLEPRIO:
+ 		ret = 0;
+ 	}
+ 	return ret;
+@@ -4676,8 +4883,8 @@ long sys_sched_rr_get_interval(pid_t pid
+ 	if (retval)
+ 		goto out_unlock;
+ 
+-	jiffies_to_timespec(p->policy == SCHED_FIFO ?
+-				0 : task_timeslice(p), &t);
++	t = ns_to_timespec(p->policy == SCHED_FIFO ? 0 :
++			   MS_TO_NS(task_timeslice(p)));
+ 	read_unlock(&tasklist_lock);
+ 	retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
+ out_nounlock:
+@@ -4771,10 +4978,10 @@ void __cpuinit init_idle(struct task_str
+ 	struct rq *rq = cpu_rq(cpu);
+ 	unsigned long flags;
+ 
+-	idle->timestamp = sched_clock();
+-	idle->sleep_avg = 0;
+-	idle->array = NULL;
+-	idle->prio = idle->normal_prio = MAX_PRIO;
++	bitmap_zero(idle->bitmap, PRIO_RANGE);
++	idle->timestamp = idle->last_ran = sched_clock();
++	idle->array = rq->active;
++	idle->prio = idle->normal_prio = NICE_TO_PRIO(0);
+ 	idle->state = TASK_RUNNING;
+ 	idle->cpus_allowed = cpumask_of_cpu(cpu);
+ 	set_task_cpu(idle, cpu);
+@@ -4893,7 +5100,7 @@ static int __migrate_task(struct task_st
+ 		goto out;
+ 
+ 	set_task_cpu(p, dest_cpu);
+-	if (p->array) {
++	if (task_queued(p)) {
+ 		/*
+ 		 * Sync timestamp with rq_dest's before activating.
+ 		 * The same thing could be achieved by doing this step
+@@ -4904,8 +5111,7 @@ static int __migrate_task(struct task_st
+ 				+ rq_dest->most_recent_timestamp;
+ 		deactivate_task(p, rq_src);
+ 		__activate_task(p, rq_dest);
+-		if (TASK_PREEMPTS_CURR(p, rq_dest))
+-			resched_task(rq_dest->curr);
++		try_preempt(p, rq_dest);
+ 	}
+ 	ret = 1;
+ out:
+@@ -5194,7 +5400,7 @@ migration_call(struct notifier_block *nf
+ 		/* Idle task back to normal (off runqueue, low prio) */
+ 		rq = task_rq_lock(rq->idle, &flags);
+ 		deactivate_task(rq->idle, rq);
+-		rq->idle->static_prio = MAX_PRIO;
++		rq->idle->static_prio = NICE_TO_PRIO(0);
+ 		__setscheduler(rq->idle, SCHED_NORMAL, 0);
+ 		migrate_dead_tasks(cpu);
+ 		task_rq_unlock(rq, &flags);
+@@ -6706,6 +6912,13 @@ void __init sched_init_smp(void)
+ 	/* Move init over to a non-isolated CPU */
+ 	if (set_cpus_allowed(current, non_isolated_cpus) < 0)
+ 		BUG();
++
++	/*
++	 * Assume that every added cpu gives us slightly less overall latency
++	 * allowing us to increase the base rr_interval, but in a non linear
++	 * fashion.
++	 */
++	rr_interval *= 1 + ilog2(num_online_cpus());
+ }
+ #else
+ void __init sched_init_smp(void)
+@@ -6727,6 +6940,16 @@ void __init sched_init(void)
+ {
+ 	int i, j, k;
+ 
++	/* Generate the priority matrix */
++	for (i = 0; i < PRIO_RANGE; i++) {
++		bitmap_fill(prio_matrix[i], PRIO_RANGE);
++		j = PRIO_RANGE * PRIO_RANGE / (PRIO_RANGE - i);
++		for (k = 0; k <= PRIO_RANGE * (PRIO_RANGE - 1); k += j) {
++			__clear_bit(PRIO_RANGE - 1 - (k / PRIO_RANGE),
++				    prio_matrix[i]);
++		}
++	}
++
+ 	for_each_possible_cpu(i) {
+ 		struct prio_array *array;
+ 		struct rq *rq;
+@@ -6734,12 +6957,20 @@ void __init sched_init(void)
+ 		rq = cpu_rq(i);
+ 		spin_lock_init(&rq->lock);
+ 		lockdep_set_class(&rq->lock, &rq->rq_lock_key);
++		rq->iso_ticks = 0;
+ 		rq->nr_running = 0;
++		rq->nr_idleprio = 0;
++		rq->prio_rotation = 0;
+ 		rq->active = rq->arrays;
++		rq->idleprio = rq->active;
+ 		rq->expired = rq->arrays + 1;
+-		rq->best_expired_prio = MAX_PRIO;
++		reset_prio_levels(rq);
++		rq->dyn_bitmap = rq->active->prio_bitmap;
++		rq->exp_bitmap = rq->expired->prio_bitmap;
+ 
+ #ifdef CONFIG_SMP
++		rq->active->rq = rq;
++		rq->expired->rq = rq;
+ 		rq->sd = NULL;
+ 		for (j = 1; j < 3; j++)
+ 			rq->cpu_load[j] = 0;
+@@ -6752,16 +6983,16 @@ void __init sched_init(void)
+ 		atomic_set(&rq->nr_iowait, 0);
+ 
+ 		for (j = 0; j < 2; j++) {
++
+ 			array = rq->arrays + j;
+-			for (k = 0; k < MAX_PRIO; k++) {
++			for (k = 0; k <= MAX_PRIO; k++)
+ 				INIT_LIST_HEAD(array->queue + k);
+-				__clear_bit(k, array->bitmap);
+-			}
+-			// delimiter for bitsearch
+-			__set_bit(MAX_PRIO, array->bitmap);
++			bitmap_zero(array->prio_bitmap, MAX_PRIO);
++			/* delimiter for bitsearch */
++			__set_bit(MAX_PRIO, array->prio_bitmap);
+ 		}
+-	}
+ 
++	}
+ 	set_load_weight(&init_task);
+ 
+ #ifdef CONFIG_SMP
+@@ -6815,24 +7046,24 @@ EXPORT_SYMBOL(__might_sleep);
+ #ifdef CONFIG_MAGIC_SYSRQ
+ void normalize_rt_tasks(void)
+ {
+-	struct prio_array *array;
+ 	struct task_struct *p;
+ 	unsigned long flags;
+ 	struct rq *rq;
++	int queued;
+ 
+ 	read_lock_irq(&tasklist_lock);
+ 	for_each_process(p) {
+-		if (!rt_task(p))
++		if (!rt_task(p) && !iso_task(p))
+ 			continue;
+ 
+ 		spin_lock_irqsave(&p->pi_lock, flags);
+ 		rq = __task_rq_lock(p);
+ 
+-		array = p->array;
+-		if (array)
++		queued = task_queued(p);
++		if (queued)
+ 			deactivate_task(p, task_rq(p));
+ 		__setscheduler(p, SCHED_NORMAL, 0);
+-		if (array) {
++		if (queued) {
+ 			__activate_task(p, task_rq(p));
+ 			resched_task(rq->curr);
+ 		}
+Index: linux-2.6.21-ck1/Documentation/sysctl/kernel.txt
+===================================================================
+--- linux-2.6.21-ck1.orig/Documentation/sysctl/kernel.txt	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/Documentation/sysctl/kernel.txt	2007-05-04 12:10:55.000000000 +1000
+@@ -25,6 +25,9 @@ show up in /proc/sys/kernel:
+ - domainname
+ - hostname
+ - hotplug
++- interactive
++- iso_cpu
++- iso_period
+ - java-appletviewer           [ binfmt_java, obsolete ]
+ - java-interpreter            [ binfmt_java, obsolete ]
+ - kstack_depth_to_print       [ X86 only ]
+@@ -43,6 +46,7 @@ show up in /proc/sys/kernel:
+ - printk
+ - real-root-dev               ==> Documentation/initrd.txt
+ - reboot-cmd                  [ SPARC only ]
++- rr_interval
+ - rtsig-max
+ - rtsig-nr
+ - sem
+@@ -164,6 +168,40 @@ Default value is "/sbin/hotplug".
+ 
+ ==============================================================
+ 
++interactive:
++
++The staircase-deadline cpu scheduler can be set in either purely
++forward-looking mode for absolutely rigid fairness and cpu distribution
++according to nice level, or it can allow a small per-process history
++to smooth out cpu usage perturbations common in interactive tasks by
++enabling this sysctl. While small fairness issues can arise with this
++enabled, overall fairness is usually still strongly maintained and
++starvation is never possible. Enabling this can significantly smooth
++out 3d graphics and games.
++
++Default value is 1 (enabled).
++
++==============================================================
++
++iso_cpu:
++
++This sets the percentage cpu that the unprivileged SCHED_ISO tasks can
++run effectively at realtime priority, averaged over a rolling iso_period
++seconds.
++
++Set to 80 (percent) by default.
++
++==============================================================
++
++iso_period:
++
++This sets the number of seconds over which SCHED_ISO cpu usage is averaged
++to see if it exceeds its allocated cpu bandwidth.
++
++Set to 5 (seconds) by default.
++
++==============================================================
++
+ l2cr: (PPC only)
+ 
+ This flag controls the L2 cache of G3 processor boards. If
+@@ -288,6 +326,19 @@ rebooting. ???
+ 
+ ==============================================================
+ 
++rr_interval:
++
++This is the smallest duration that any cpu process scheduling unit
++will run for. Increasing this value can increase throughput of cpu
++bound tasks substantially but at the expense of increased latencies
++overall. This value is in milliseconds and the default value chosen
++depends on the number of cpus available at scheduler initialisation
++with a minimum of 8.
++
++Valid values are from 1-5000.
++
++==============================================================
++
+ rtsig-max & rtsig-nr:
+ 
+ The file rtsig-max can be used to tune the maximum number
+Index: linux-2.6.21-ck1/kernel/sysctl.c
+===================================================================
+--- linux-2.6.21-ck1.orig/kernel/sysctl.c	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/kernel/sysctl.c	2007-05-04 12:24:21.000000000 +1000
+@@ -22,6 +22,7 @@
+ #include <linux/mm.h>
+ #include <linux/swap.h>
+ #include <linux/slab.h>
++#include <linux/swap-prefetch.h>
+ #include <linux/sysctl.h>
+ #include <linux/proc_fs.h>
+ #include <linux/capability.h>
+@@ -70,12 +71,17 @@ extern int suid_dumpable;
+ extern char core_pattern[];
+ extern int pid_max;
+ extern int min_free_kbytes;
++extern int vm_tail_largefiles;
+ extern int printk_ratelimit_jiffies;
+ extern int printk_ratelimit_burst;
+ extern int pid_max_min, pid_max_max;
+ extern int sysctl_drop_caches;
+ extern int percpu_pagelist_fraction;
+ extern int compat_log;
++extern int rr_interval;
++extern int sched_interactive;
++extern int sched_iso_cpu;
++extern int sched_iso_period;
+ 
+ /* this is needed for the proc_dointvec_minmax for [fs_]overflow UID and GID */
+ static int maxolduid = 65535;
+@@ -159,6 +165,14 @@ int sysctl_legacy_va_layout;
+ #endif
+ 
+ 
++/* Constants for minimum and maximum testing.
++   We use these as one-element integer vectors. */
++static int __read_mostly zero;
++static int __read_mostly one = 1;
++static int __read_mostly one_hundred = 100;
++static int __read_mostly five_thousand = 5000;
++
++
+ /* The default sysctl tables: */
+ 
+ static ctl_table root_table[] = {
+@@ -499,6 +513,47 @@ static ctl_table kern_table[] = {
+ 		.mode		= 0444,
+ 		.proc_handler	= &proc_dointvec,
+ 	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "rr_interval",
++		.data		= &rr_interval,
++		.maxlen		= sizeof (int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec_minmax,
++		.strategy	= &sysctl_intvec,
++		.extra1		= &one,
++		.extra2		= &five_thousand,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "interactive",
++		.data		= &sched_interactive,
++		.maxlen		= sizeof(int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "iso_cpu",
++		.data		= &sched_iso_cpu,
++		.maxlen		= sizeof (int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec_minmax,
++		.strategy	= &sysctl_intvec,
++		.extra1		= &zero,
++		.extra2		= &one_hundred,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "iso_period",
++		.data		= &sched_iso_period,
++		.maxlen		= sizeof (int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec_minmax,
++		.strategy	= &sysctl_intvec,
++		.extra1		= &one,
++		.extra2		= &one_hundred,
++	},
+ #if defined(CONFIG_X86_LOCAL_APIC) && defined(CONFIG_X86)
+ 	{
+ 		.ctl_name       = KERN_UNKNOWN_NMI_PANIC,
+@@ -607,12 +662,6 @@ static ctl_table kern_table[] = {
+ 	{ .ctl_name = 0 }
+ };
+ 
+-/* Constants for minimum and maximum testing in vm_table.
+-   We use these as one-element integer vectors. */
+-static int zero;
+-static int one_hundred = 100;
+-
+-
+ static ctl_table vm_table[] = {
+ 	{
+ 		.ctl_name	= VM_OVERCOMMIT_MEMORY,
+@@ -693,16 +742,32 @@ static ctl_table vm_table[] = {
+ 		.proc_handler	= &proc_dointvec,
+ 	},
+ 	{
+-		.ctl_name	= VM_SWAPPINESS,
+-		.procname	= "swappiness",
+-		.data		= &vm_swappiness,
+-		.maxlen		= sizeof(vm_swappiness),
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "mapped",
++		.data		= &vm_mapped,
++		.maxlen		= sizeof(vm_mapped),
+ 		.mode		= 0644,
+ 		.proc_handler	= &proc_dointvec_minmax,
+ 		.strategy	= &sysctl_intvec,
+ 		.extra1		= &zero,
+ 		.extra2		= &one_hundred,
+ 	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "hardmaplimit",
++		.data		= &vm_hardmaplimit,
++		.maxlen		= sizeof(int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "tail_largefiles",
++		.data		= &vm_tail_largefiles,
++		.maxlen		= sizeof(int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
+ #ifdef CONFIG_HUGETLB_PAGE
+ 	 {
+ 		.ctl_name	= VM_HUGETLB_PAGES,
+@@ -859,6 +924,16 @@ static ctl_table vm_table[] = {
+ 		.extra1		= &zero,
+ 	},
+ #endif
++#ifdef CONFIG_SWAP_PREFETCH
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "swap_prefetch",
++		.data		= &swap_prefetch,
++		.maxlen		= sizeof(swap_prefetch),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
++#endif
+ 	{ .ctl_name = 0 }
+ };
+ 
+Index: linux-2.6.21-ck1/fs/pipe.c
+===================================================================
+--- linux-2.6.21-ck1.orig/fs/pipe.c	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/fs/pipe.c	2007-05-04 12:10:54.000000000 +1000
+@@ -41,12 +41,7 @@ void pipe_wait(struct pipe_inode_info *p
+ {
+ 	DEFINE_WAIT(wait);
+ 
+-	/*
+-	 * Pipes are system-local resources, so sleeping on them
+-	 * is considered a noninteractive wait:
+-	 */
+-	prepare_to_wait(&pipe->wait, &wait,
+-			TASK_INTERRUPTIBLE | TASK_NONINTERACTIVE);
++	prepare_to_wait(&pipe->wait, &wait, TASK_INTERRUPTIBLE);
+ 	if (pipe->inode)
+ 		mutex_unlock(&pipe->inode->i_mutex);
+ 	schedule();
+Index: linux-2.6.21-ck1/Documentation/sched-design.txt
+===================================================================
+--- linux-2.6.21-ck1.orig/Documentation/sched-design.txt	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/Documentation/sched-design.txt	2007-05-04 12:10:54.000000000 +1000
+@@ -1,11 +1,14 @@
+-		   Goals, Design and Implementation of the
+-		      new ultra-scalable O(1) scheduler
++ Goals, Design and Implementation of the ultra-scalable O(1) scheduler by
++ Ingo Molnar and theStaircase Deadline cpu scheduler policy designed by
++ Con Kolivas.
+ 
+ 
+-  This is an edited version of an email Ingo Molnar sent to
+-  lkml on 4 Jan 2002.  It describes the goals, design, and
+-  implementation of Ingo's new ultra-scalable O(1) scheduler.
+-  Last Updated: 18 April 2002.
++  This was originally an edited version of an email Ingo Molnar sent to
++  lkml on 4 Jan 2002.  It describes the goals, design, and implementation
++  of Ingo's ultra-scalable O(1) scheduler. It now contains a description
++  of the Staircase Deadline priority scheduler that was built on this
++  design.
++  Last Updated: Fri, 4 May 2007
+ 
+ 
+ Goal
+@@ -163,3 +166,222 @@ certain code paths and data constructs. 
+ code is smaller than the old one.
+ 
+ 	Ingo
++
++
++Staircase Deadline cpu scheduler policy
++================================================
++
++Design summary
++==============
++
++A novel design which incorporates a foreground-background descending priority
++system (the staircase) via a bandwidth allocation matrix according to nice
++level.
++
++
++Features
++========
++
++A starvation free, strict fairness O(1) scalable design with interactivity
++as good as the above restrictions can provide. There is no interactivity
++estimator, no sleep/run measurements and only simple fixed accounting.
++The design has strict enough a design and accounting that task behaviour
++can be modelled and maximum scheduling latencies can be predicted by
++the virtual deadline mechanism that manages runqueues. The prime concern
++in this design is to maintain fairness at all costs determined by nice level,
++yet to maintain as good interactivity as can be allowed within the
++constraints of strict fairness.
++
++
++Design description
++==================
++
++SD works off the principle of providing each task a quota of runtime that it is
++allowed to run at a number of priority levels determined by its static priority
++(ie. its nice level). If the task uses up its quota it has its priority
++decremented to the next level determined by a priority matrix. Once every
++runtime quota has been consumed of every priority level, a task is queued on the
++"expired" array. When no other tasks exist with quota, the expired array is
++activated and fresh quotas are handed out. This is all done in O(1).
++
++Design details
++==============
++
++Each task keeps a record of its own entitlement of cpu time. Most of the rest of
++these details apply to non-realtime tasks as rt task management is straight
++forward.
++
++Each runqueue keeps a record of what major epoch it is up to in the
++rq->prio_rotation field which is incremented on each major epoch. It also
++keeps a record of the current prio_level for each static priority task.
++
++Each task keeps a record of what major runqueue epoch it was last running
++on in p->rotation. It also keeps a record of what priority levels it has
++already been allocated quota from during this epoch in a bitmap p->bitmap.
++
++The only tunable that determines all other details is the RR_INTERVAL. This
++is set to 8ms, and is scaled gently upwards with more cpus. This value is
++tunable via a /proc interface.
++
++All tasks are initially given a quota based on RR_INTERVAL. This is equal to
++RR_INTERVAL between nice values of -6 and 0, half that size above nice 0, and
++progressively larger for nice values from -1 to -20. This is assigned to
++p->quota and only changes with changes in nice level.
++
++As a task is first queued, it checks in recalc_task_prio to see if it has run at
++this runqueue's current priority rotation. If it has not, it will have its
++p->prio level set according to the first slot in a "priority matrix" and will be
++given a p->time_slice equal to the p->quota, and has its allocation bitmap bit
++set in p->bitmap for this prio level. It is then queued on the current active
++priority array.
++
++If a task has already been running during this major epoch, and it has
++p->time_slice left and the rq->prio_quota for the task's p->prio still
++has quota, it will be placed back on the active array, but no more quota
++will be added.
++
++If a task has been running during this major epoch, but does not have
++p->time_slice left, it will find the next lowest priority in its bitmap that it
++has not been allocated quota from. It then gets the a full quota in
++p->time_slice. It is then queued on the current active priority array at the
++newly determined lower priority.
++
++If a task has been running during this major epoch, and does not have
++any entitlement left in p->bitmap and no time_slice left, it will have its
++bitmap cleared, and be queued at its best prio again, but on the expired
++priority array.
++
++When a task is queued, it has its relevant bit set in the array->prio_bitmap.
++
++p->time_slice is stored in nanosconds and is updated via update_cpu_clock on
++schedule() and scheduler_tick. If p->time_slice is below zero then the
++recalc_task_prio is readjusted and the task rescheduled.
++
++
++Priority Matrix
++===============
++
++In order to minimise the latencies between tasks of different nice levels
++running concurrently, the dynamic priority slots where different nice levels
++are queued are dithered instead of being sequential. What this means is that
++there are 40 priority slots where a task may run during one major rotation,
++and the allocation of slots is dependant on nice level. In the
++following table, a zero represents a slot where the task may run.
++
++PRIORITY:0..................20.................39
++nice -20 0000000000000000000000000000000000000000
++nice -10 1000100010001000100010001000100010010000
++nice   0 1010101010101010101010101010101010101010
++nice   5 1011010110110101101101011011010110110110
++nice  10 1110111011101110111011101110111011101110
++nice  15 1111111011111110111111101111111011111110
++nice  19 1111111111111111111111111111111111111110
++
++As can be seen, a nice -20 task runs in every priority slot whereas a nice 19
++task only runs one slot per major rotation. This dithered table allows for the
++smallest possible maximum latencies between tasks of varying nice levels, thus
++allowing vastly different nice levels to be used.
++
++SCHED_BATCH tasks are managed slightly differently, receiving only the top
++slots from its priority bitmap giving it equal cpu as SCHED_NORMAL, but
++slightly higher latencies.
++
++
++Modelling deadline behaviour
++============================
++
++As the accounting in this design is hard and not modified by sleep average
++calculations or interactivity modifiers, it is possible to accurately
++predict the maximum latency that a task may experience under different
++conditions. This is a virtual deadline mechanism enforced by mandatory
++timeslice expiration and not outside bandwidth measurement.
++
++The maximum duration a task can run during one major epoch is determined by its
++nice value. Nice 0 tasks can run at 19 different priority levels for RR_INTERVAL
++duration during each epoch. Nice 10 tasks can run at 9 priority levels for each
++epoch, and so on. The table in the priority matrix above demonstrates how this
++is enforced.
++
++Therefore the maximum duration a runqueue epoch can take is determined by
++the number of tasks running, and their nice level. After that, the maximum
++duration it can take before a task can wait before it get scheduled is
++determined by the position of its first slot on the matrix.
++
++In the following examples, these are _worst case scenarios_ and would rarely
++occur, but can be modelled nonetheless to determine the maximum possible
++latency.
++
++So for example, if two nice 0 tasks are running, and one has just expired as
++another is activated for the first time receiving a full quota for this
++runqueue rotation, the first task will wait:
++
++nr_tasks * max_duration + nice_difference * rr_interval
++1 * 19 * RR_INTERVAL + 0 = 152ms
++
++In the presence of a nice 10 task, a nice 0 task would wait a maximum of
++1 * 10 * RR_INTERVAL + 0 = 80ms
++
++In the presence of a nice 0 task, a nice 10 task would wait a maximum of
++1 * 19 * RR_INTERVAL + 1 * RR_INTERVAL = 160ms
++
++More useful than these values, though, are the average latencies which are
++a matter of determining the average distance between priority slots of
++different nice values and multiplying them by the tasks' quota. For example
++in the presence of a nice -10 task, a nice 0 task will wait either one or
++two slots. Given that nice -10 tasks have a quota 2.5 times the RR_INTERVAL,
++this means the latencies will alternate between 2.5 and 5 RR_INTERVALs or
++20 and 40ms respectively (on uniprocessor at 1000HZ).
++
++
++Achieving interactivity
++=======================
++
++A requirement of this scheduler design was to achieve good interactivity
++despite being a completely fair deadline based design. The disadvantage of
++designs that try to achieve interactivity is that they usually do so at
++the expense of maintaining fairness. As cpu speeds increase, the requirement
++for some sort of metered unfairness towards interactive tasks becomes a less
++desirable phenomenon, but low latency and fairness remains mandatory to
++good interactive performance.
++
++This design relies on the fact that interactive tasks, by their nature,
++sleep often. Most fair scheduling designs end up penalising such tasks
++indirectly giving them less than their fair possible share because of the
++sleep, and have to use a mechanism of bonusing their priority to offset
++this based on the duration they sleep. This becomes increasingly inaccurate
++as the number of running tasks rises and more tasks spend time waiting on
++runqueues rather than sleeping, and it is impossible to tell whether the
++task that's waiting on a runqueue only intends to run for a short period and
++then sleep again after than runqueue wait. Furthermore, all such designs rely
++on a period of time to pass to accumulate some form of statistic on the task
++before deciding on how much to give them preference. The shorter this period,
++the more rapidly bursts of cpu ruin the interactive tasks behaviour. The
++longer this period, the longer it takes for interactive tasks to get low
++scheduling latencies and fair cpu.
++
++This design does not measure sleep time at all. Interactive tasks that sleep
++often will wake up having consumed very little if any of their quota for
++the current major priority rotation. The longer they have slept, the less
++likely they are to even be on the current major priority rotation. Once
++woken up, though, they get to use up a their full quota for that epoch,
++whether part of a quota remains or a full quota. Overall, however, they
++can still only run as much cpu time for that epoch as any other task of the
++same nice level. This means that two tasks behaving completely differently
++from fully cpu bound to waking/sleeping extremely frequently will still
++get the same quota of cpu, but the latter will be using its quota for that
++epoch in bursts rather than continuously. This guarantees that interactive
++tasks get the same amount of cpu as cpu bound ones.
++
++The other requirement of interactive tasks is also to obtain low latencies
++for when they are scheduled. Unlike fully cpu bound tasks and the maximum
++latencies possible described in the modelling deadline behaviour section
++above, tasks that sleep will wake up with quota available usually at the
++current runqueue's priority_level or better. This means that the most latency
++they are likely to see is one RR_INTERVAL, and often they will preempt the
++current task if it is not of a sleeping nature. This then guarantees very
++low latency for interactive tasks, and the lowest latencies for the least
++cpu bound tasks.
++
++
++Fri, 4 May 2007
++Con Kolivas <kernel@kolivas.org>
+Index: linux-2.6.21-ck1/kernel/softirq.c
+===================================================================
+--- linux-2.6.21-ck1.orig/kernel/softirq.c	2007-05-04 12:10:52.000000000 +1000
++++ linux-2.6.21-ck1/kernel/softirq.c	2007-05-04 12:10:54.000000000 +1000
+@@ -488,7 +488,7 @@ void __init softirq_init(void)
+ 
+ static int ksoftirqd(void * __bind_cpu)
+ {
+-	set_user_nice(current, 19);
++	set_user_nice(current, 15);
+ 	current->flags |= PF_NOFREEZE;
+ 
+ 	set_current_state(TASK_INTERRUPTIBLE);
+Index: linux-2.6.21-ck1/kernel/fork.c
+===================================================================
+--- linux-2.6.21-ck1.orig/kernel/fork.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/kernel/fork.c	2007-05-04 12:24:19.000000000 +1000
+@@ -1060,6 +1060,7 @@ static struct task_struct *copy_process(
+ 	p->io_context = NULL;
+ 	p->io_wait = NULL;
+ 	p->audit_context = NULL;
++	p->mutexes_held = 0;
+ 	cpuset_fork(p);
+ #ifdef CONFIG_NUMA
+  	p->mempolicy = mpol_copy(p->mempolicy);
+Index: linux-2.6.21-ck1/kernel/mutex.c
+===================================================================
+--- linux-2.6.21-ck1.orig/kernel/mutex.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/kernel/mutex.c	2007-05-04 12:24:19.000000000 +1000
+@@ -60,6 +60,16 @@ EXPORT_SYMBOL(__mutex_init);
+ static void fastcall noinline __sched
+ __mutex_lock_slowpath(atomic_t *lock_count);
+ 
++static inline void inc_mutex_count(void)
++{
++	current->mutexes_held++;
++}
++
++static inline void dec_mutex_count(void)
++{
++	current->mutexes_held--;
++}
++
+ /***
+  * mutex_lock - acquire the mutex
+  * @lock: the mutex to be acquired
+@@ -89,6 +99,7 @@ void inline fastcall __sched mutex_lock(
+ 	 * 'unlocked' into 'locked' state.
+ 	 */
+ 	__mutex_fastpath_lock(&lock->count, __mutex_lock_slowpath);
++	inc_mutex_count();
+ }
+ 
+ EXPORT_SYMBOL(mutex_lock);
+@@ -114,6 +125,7 @@ void fastcall __sched mutex_unlock(struc
+ 	 * into 'unlocked' state:
+ 	 */
+ 	__mutex_fastpath_unlock(&lock->count, __mutex_unlock_slowpath);
++	dec_mutex_count();
+ }
+ 
+ EXPORT_SYMBOL(mutex_unlock);
+@@ -283,9 +295,14 @@ __mutex_lock_interruptible_slowpath(atom
+  */
+ int fastcall __sched mutex_lock_interruptible(struct mutex *lock)
+ {
++	int ret;
++
+ 	might_sleep();
+-	return __mutex_fastpath_lock_retval
++	ret = __mutex_fastpath_lock_retval
+ 			(&lock->count, __mutex_lock_interruptible_slowpath);
++	if (likely(!ret))
++		inc_mutex_count();
++	return ret;
+ }
+ 
+ EXPORT_SYMBOL(mutex_lock_interruptible);
+@@ -340,8 +357,12 @@ static inline int __mutex_trylock_slowpa
+  */
+ int fastcall __sched mutex_trylock(struct mutex *lock)
+ {
+-	return __mutex_fastpath_trylock(&lock->count,
++	int ret = __mutex_fastpath_trylock(&lock->count,
+ 					__mutex_trylock_slowpath);
++
++	if (likely(ret))
++		inc_mutex_count();
++	return ret;
+ }
+ 
+ EXPORT_SYMBOL(mutex_trylock);
+Index: linux-2.6.21-ck1/block/cfq-iosched.c
+===================================================================
+--- linux-2.6.21-ck1.orig/block/cfq-iosched.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/block/cfq-iosched.c	2007-05-04 12:24:19.000000000 +1000
+@@ -1258,10 +1258,12 @@ static void cfq_init_prio_data(struct cf
+ 			printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
+ 		case IOPRIO_CLASS_NONE:
+ 			/*
+-			 * no prio set, place us in the middle of the BE classes
++			 * Select class and ioprio according to policy and nice
+ 			 */
++			cfqq->ioprio_class = task_policy_ioprio_class(tsk);
+ 			cfqq->ioprio = task_nice_ioprio(tsk);
+-			cfqq->ioprio_class = IOPRIO_CLASS_BE;
++			if (cfqq->ioprio_class == IOPRIO_CLASS_IDLE)
++				cfq_clear_cfqq_idle_window(cfqq);
+ 			break;
+ 		case IOPRIO_CLASS_RT:
+ 			cfqq->ioprio = task_ioprio(tsk);
+Index: linux-2.6.21-ck1/include/linux/ioprio.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/ioprio.h	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/ioprio.h	2007-05-04 12:24:19.000000000 +1000
+@@ -22,7 +22,7 @@
+  * class, the default for any process. IDLE is the idle scheduling class, it
+  * is only served when no one else is using the disk.
+  */
+-enum {
++enum ioprio_class {
+ 	IOPRIO_CLASS_NONE,
+ 	IOPRIO_CLASS_RT,
+ 	IOPRIO_CLASS_BE,
+@@ -51,8 +51,25 @@ static inline int task_ioprio(struct tas
+ 	return IOPRIO_PRIO_DATA(task->ioprio);
+ }
+ 
++static inline enum ioprio_class
++	task_policy_ioprio_class(struct task_struct *task)
++{
++	if (rt_task(task))
++		return IOPRIO_CLASS_RT;
++	if (idleprio_task(task))
++		return IOPRIO_CLASS_IDLE;
++	return IOPRIO_CLASS_BE;
++}
++
+ static inline int task_nice_ioprio(struct task_struct *task)
+ {
++	if (rt_task(task))
++		return (MAX_RT_PRIO - task->rt_priority) * IOPRIO_BE_NR /
++			(MAX_RT_PRIO + 1);
++	if (iso_task(task))
++		return 0;
++	if (idleprio_task(task))
++		return IOPRIO_BE_NR - 1;
+ 	return (task_nice(task) + 20) / 5;
+ }
+ 
+Index: linux-2.6.21-ck1/Documentation/sysctl/vm.txt
+===================================================================
+--- linux-2.6.21-ck1.orig/Documentation/sysctl/vm.txt	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/Documentation/sysctl/vm.txt	2007-05-04 12:24:21.000000000 +1000
+@@ -22,6 +22,8 @@ Currently, these files are in /proc/sys/
+ - dirty_background_ratio
+ - dirty_expire_centisecs
+ - dirty_writeback_centisecs
++- hardmaplimit
++- mapped
+ - max_map_count
+ - min_free_kbytes
+ - laptop_mode
+@@ -31,12 +33,13 @@ Currently, these files are in /proc/sys/
+ - min_unmapped_ratio
+ - min_slab_ratio
+ - panic_on_oom
++- swap_prefetch
+ 
+ ==============================================================
+ 
+ dirty_ratio, dirty_background_ratio, dirty_expire_centisecs,
+ dirty_writeback_centisecs, vfs_cache_pressure, laptop_mode,
+-block_dump, swap_token_timeout, drop-caches:
++block_dump, swap_token_timeout, drop-caches, tail_largefiles:
+ 
+ See Documentation/filesystems/proc.txt
+ 
+@@ -86,6 +89,27 @@ for swap because we only cluster swap da
+ 
+ ==============================================================
+ 
++hardmaplimit:
++
++This flag makes the vm adhere to the mapped value as closely as possible
++except in the most extreme vm stress where doing so would provoke an out
++of memory condition (see mapped below).
++
++Enabled by default.
++
++==============================================================
++
++mapped:
++
++This is the percentage ram that is filled with mapped pages (applications)
++before the vm will start reclaiming mapped pages by moving them to swap.
++It is altered by the relative stress of the vm at the time so is not
++strictly adhered to to prevent provoking out of memory kills.
++
++Set to 66 by default.
++
++==============================================================
++
+ max_map_count:
+ 
+ This file contains the maximum number of memory map areas a process
+@@ -205,3 +229,14 @@ rather than killing rogue processes, set
+ 
+ The default value is 0.
+ 
++==============================================================
++
++swap_prefetch
++
++This enables or disables the swap prefetching feature. When the virtual
++memory subsystem has been extremely idle for at least 5 seconds it will start
++copying back pages from swap into the swapcache and keep a copy in swap. In
++practice it can take many minutes before the vm is idle enough.
++
++The default value is 1.
++
+Index: linux-2.6.21-ck1/include/linux/swap.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/swap.h	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/swap.h	2007-05-04 12:24:20.000000000 +1000
+@@ -180,6 +180,7 @@ extern unsigned int nr_free_pagecache_pa
+ /* linux/mm/swap.c */
+ extern void FASTCALL(lru_cache_add(struct page *));
+ extern void FASTCALL(lru_cache_add_active(struct page *));
++extern void FASTCALL(lru_cache_add_tail(struct page *));
+ extern void FASTCALL(activate_page(struct page *));
+ extern void FASTCALL(mark_page_accessed(struct page *));
+ extern void lru_add_drain(void);
+@@ -188,9 +189,11 @@ extern int rotate_reclaimable_page(struc
+ extern void swap_setup(void);
+ 
+ /* linux/mm/vmscan.c */
+-extern unsigned long try_to_free_pages(struct zone **, gfp_t);
++extern unsigned long try_to_free_pages(struct zone **, gfp_t,
++				       struct task_struct *p);
+ extern unsigned long shrink_all_memory(unsigned long nr_pages);
+-extern int vm_swappiness;
++extern int vm_mapped;
++extern int vm_hardmaplimit;
+ extern int remove_mapping(struct address_space *mapping, struct page *page);
+ extern long vm_total_pages;
+ 
+@@ -237,6 +240,7 @@ extern void free_pages_and_swap_cache(st
+ extern struct page * lookup_swap_cache(swp_entry_t);
+ extern struct page * read_swap_cache_async(swp_entry_t, struct vm_area_struct *vma,
+ 					   unsigned long addr);
++extern int add_to_swap_cache(struct page *page, swp_entry_t entry);
+ /* linux/mm/swapfile.c */
+ extern long total_swap_pages;
+ extern unsigned int nr_swapfiles;
+Index: linux-2.6.21-ck1/init/Kconfig
+===================================================================
+--- linux-2.6.21-ck1.orig/init/Kconfig	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/init/Kconfig	2007-05-04 12:24:20.000000000 +1000
+@@ -101,6 +101,28 @@ config SWAP
+ 	  used to provide more virtual memory than the actual RAM present
+ 	  in your computer.  If unsure say Y.
+ 
++config SWAP_PREFETCH
++	bool "Support for prefetching swapped memory"
++	depends on SWAP
++	default y
++	---help---
++	  This option will allow the kernel to prefetch swapped memory pages
++	  when idle. The pages will be kept on both swap and in swap_cache
++	  thus avoiding the need for further I/O if either ram or swap space
++	  is required.
++
++	  What this will do on workstations is slowly bring back applications
++	  that have swapped out after memory intensive workloads back into
++	  physical ram if you have free ram at a later stage and the machine
++	  is relatively idle. This means that when you come back to your
++	  computer after leaving it idle for a while, applications will come
++	  to life faster. Note that your swap usage will appear to increase
++	  but these are cached pages, can be dropped freely by the vm, and it
++	  should stabilise around 50% swap usage maximum.
++
++	  Workstations and multiuser workstation servers will most likely want
++	  to say Y.
++
+ config SYSVIPC
+ 	bool "System V IPC"
+ 	---help---
+Index: linux-2.6.21-ck1/mm/Makefile
+===================================================================
+--- linux-2.6.21-ck1.orig/mm/Makefile	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/mm/Makefile	2007-05-04 12:24:20.000000000 +1000
+@@ -17,6 +17,7 @@ ifeq ($(CONFIG_MMU)$(CONFIG_BLOCK),yy)
+ obj-y			+= bounce.o
+ endif
+ obj-$(CONFIG_SWAP)	+= page_io.o swap_state.o swapfile.o thrash.o
++obj-$(CONFIG_SWAP_PREFETCH) += swap_prefetch.o
+ obj-$(CONFIG_HUGETLBFS)	+= hugetlb.o
+ obj-$(CONFIG_NUMA) 	+= mempolicy.o
+ obj-$(CONFIG_SPARSEMEM)	+= sparse.o
+Index: linux-2.6.21-ck1/mm/swap.c
+===================================================================
+--- linux-2.6.21-ck1.orig/mm/swap.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/mm/swap.c	2007-05-04 12:24:21.000000000 +1000
+@@ -17,6 +17,7 @@
+ #include <linux/sched.h>
+ #include <linux/kernel_stat.h>
+ #include <linux/swap.h>
++#include <linux/swap-prefetch.h>
+ #include <linux/mman.h>
+ #include <linux/pagemap.h>
+ #include <linux/pagevec.h>
+@@ -176,6 +177,7 @@ EXPORT_SYMBOL(mark_page_accessed);
+  */
+ static DEFINE_PER_CPU(struct pagevec, lru_add_pvecs) = { 0, };
+ static DEFINE_PER_CPU(struct pagevec, lru_add_active_pvecs) = { 0, };
++static DEFINE_PER_CPU(struct pagevec, lru_add_tail_pvecs) = { 0, };
+ 
+ void fastcall lru_cache_add(struct page *page)
+ {
+@@ -197,6 +199,31 @@ void fastcall lru_cache_add_active(struc
+ 	put_cpu_var(lru_add_active_pvecs);
+ }
+ 
++static void __pagevec_lru_add_tail(struct pagevec *pvec)
++{
++	int i;
++	struct zone *zone = NULL;
++
++	for (i = 0; i < pagevec_count(pvec); i++) {
++		struct page *page = pvec->pages[i];
++		struct zone *pagezone = page_zone(page);
++
++		if (pagezone != zone) {
++			if (zone)
++				spin_unlock_irq(&zone->lru_lock);
++			zone = pagezone;
++			spin_lock_irq(&zone->lru_lock);
++		}
++		BUG_ON(PageLRU(page));
++		SetPageLRU(page);
++		add_page_to_inactive_list_tail(zone, page);
++	}
++	if (zone)
++		spin_unlock_irq(&zone->lru_lock);
++	release_pages(pvec->pages, pvec->nr, pvec->cold);
++	pagevec_reinit(pvec);
++}
++
+ static void __lru_add_drain(int cpu)
+ {
+ 	struct pagevec *pvec = &per_cpu(lru_add_pvecs, cpu);
+@@ -207,6 +234,9 @@ static void __lru_add_drain(int cpu)
+ 	pvec = &per_cpu(lru_add_active_pvecs, cpu);
+ 	if (pagevec_count(pvec))
+ 		__pagevec_lru_add_active(pvec);
++	pvec = &per_cpu(lru_add_tail_pvecs, cpu);
++	if (pagevec_count(pvec))
++		__pagevec_lru_add_tail(pvec);
+ }
+ 
+ void lru_add_drain(void)
+@@ -403,6 +433,20 @@ void __pagevec_lru_add_active(struct pag
+ }
+ 
+ /*
++ * Function used uniquely to put pages back to the lru at the end of the
++ * inactive list to preserve the lru order.
++ */
++void fastcall lru_cache_add_tail(struct page *page)
++{
++	struct pagevec *pvec = &get_cpu_var(lru_add_tail_pvecs);
++
++	page_cache_get(page);
++	if (!pagevec_add(pvec, page))
++		__pagevec_lru_add_tail(pvec);
++	put_cpu_var(lru_add_pvecs);
++}
++
++/*
+  * Try to drop buffers from the pages in a pagevec
+  */
+ void pagevec_strip(struct pagevec *pvec)
+@@ -514,6 +558,9 @@ void __init swap_setup(void)
+ 	 * Right now other parts of the system means that we
+ 	 * _really_ don't want to cluster much more
+ 	 */
++
++	prepare_swap_prefetch();
++
+ #ifdef CONFIG_HOTPLUG_CPU
+ 	hotcpu_notifier(cpu_swap_callback, 0);
+ #endif
+Index: linux-2.6.21-ck1/mm/swap_prefetch.c
+===================================================================
+--- /dev/null	1970-01-01 00:00:00.000000000 +0000
++++ linux-2.6.21-ck1/mm/swap_prefetch.c	2007-05-04 12:24:20.000000000 +1000
+@@ -0,0 +1,581 @@
++/*
++ * linux/mm/swap_prefetch.c
++ *
++ * Copyright (C) 2005-2006 Con Kolivas
++ *
++ * Written by Con Kolivas <kernel@kolivas.org>
++ *
++ * This program is free software; you can redistribute it and/or modify
++ * it under the terms of the GNU General Public License version 2 as
++ * published by the Free Software Foundation.
++ */
++
++#include <linux/fs.h>
++#include <linux/mm.h>
++#include <linux/swap.h>
++#include <linux/swap-prefetch.h>
++#include <linux/ioprio.h>
++#include <linux/kthread.h>
++#include <linux/pagemap.h>
++#include <linux/syscalls.h>
++#include <linux/writeback.h>
++#include <linux/vmstat.h>
++#include <linux/freezer.h>
++
++/*
++ * Time to delay prefetching if vm is busy or prefetching unsuccessful. There
++ * needs to be at least this duration of idle time meaning in practice it can
++ * be much longer
++ */
++#define PREFETCH_DELAY	(HZ * 5)
++
++/* sysctl - enable/disable swap prefetching */
++int swap_prefetch __read_mostly = 1;
++
++struct swapped_root {
++	unsigned long		busy;		/* vm busy */
++	spinlock_t		lock;		/* protects all data */
++	struct list_head	list;		/* MRU list of swapped pages */
++	struct radix_tree_root	swap_tree;	/* Lookup tree of pages */
++	unsigned int		count;		/* Number of entries */
++	unsigned int		maxcount;	/* Maximum entries allowed */
++	struct kmem_cache	*cache;		/* Of struct swapped_entry */
++};
++
++static struct swapped_root swapped = {
++	.lock		= SPIN_LOCK_UNLOCKED,
++	.list  		= LIST_HEAD_INIT(swapped.list),
++	.swap_tree	= RADIX_TREE_INIT(GFP_ATOMIC),
++};
++
++static struct task_struct *kprefetchd_task;
++
++/*
++ * We check to see no part of the vm is busy. If it is this will interrupt
++ * trickle_swap and wait another PREFETCH_DELAY. Purposefully racy.
++ */
++inline void delay_swap_prefetch(void)
++{
++	if (!test_bit(0, &swapped.busy))
++		__set_bit(0, &swapped.busy);
++}
++
++/*
++ * Drop behind accounting which keeps a list of the most recently used swap
++ * entries.
++ */
++void add_to_swapped_list(struct page *page)
++{
++	struct swapped_entry *entry;
++	unsigned long index, flags;
++	int wakeup;
++
++	if (!swap_prefetch)
++		return;
++
++	wakeup = 0;
++
++	spin_lock_irqsave(&swapped.lock, flags);
++	if (swapped.count >= swapped.maxcount) {
++		/*
++		 * We limit the number of entries to 2/3 of physical ram.
++		 * Once the number of entries exceeds this we start removing
++		 * the least recently used entries.
++		 */
++		entry = list_entry(swapped.list.next,
++			struct swapped_entry, swapped_list);
++		radix_tree_delete(&swapped.swap_tree, entry->swp_entry.val);
++		list_del(&entry->swapped_list);
++		swapped.count--;
++	} else {
++		entry = kmem_cache_alloc(swapped.cache, GFP_ATOMIC);
++		if (unlikely(!entry))
++			/* bad, can't allocate more mem */
++			goto out_locked;
++	}
++
++	index = page_private(page);
++	entry->swp_entry.val = index;
++	/*
++	 * On numa we need to store the node id to ensure that we prefetch to
++	 * the same node it came from.
++	 */
++	store_swap_entry_node(entry, page);
++
++	if (likely(!radix_tree_insert(&swapped.swap_tree, index, entry))) {
++		/*
++		 * If this is the first entry, kprefetchd needs to be
++		 * (re)started.
++		 */
++		if (!swapped.count)
++			wakeup = 1;
++		list_add(&entry->swapped_list, &swapped.list);
++		swapped.count++;
++	}
++
++out_locked:
++	spin_unlock_irqrestore(&swapped.lock, flags);
++
++	/* Do the wakeup outside the lock to shorten lock hold time. */
++	if (wakeup)
++		wake_up_process(kprefetchd_task);
++
++	return;
++}
++
++/*
++ * Removes entries from the swapped_list. The radix tree allows us to quickly
++ * look up the entry from the index without having to iterate over the whole
++ * list.
++ */
++void remove_from_swapped_list(const unsigned long index)
++{
++	struct swapped_entry *entry;
++	unsigned long flags;
++
++	if (list_empty(&swapped.list))
++		return;
++
++	spin_lock_irqsave(&swapped.lock, flags);
++	entry = radix_tree_delete(&swapped.swap_tree, index);
++	if (likely(entry)) {
++		list_del_init(&entry->swapped_list);
++		swapped.count--;
++		kmem_cache_free(swapped.cache, entry);
++	}
++	spin_unlock_irqrestore(&swapped.lock, flags);
++}
++
++enum trickle_return {
++	TRICKLE_SUCCESS,
++	TRICKLE_FAILED,
++	TRICKLE_DELAY,
++};
++
++struct node_stats {
++	unsigned long	last_free;
++	/* Free ram after a cycle of prefetching */
++	unsigned long	current_free;
++	/* Free ram on this cycle of checking prefetch_suitable */
++	unsigned long	prefetch_watermark;
++	/* Maximum amount we will prefetch to */
++	unsigned long	highfree[MAX_NR_ZONES];
++	/* The amount of free ram before we start prefetching */
++	unsigned long	lowfree[MAX_NR_ZONES];
++	/* The amount of free ram where we will stop prefetching */
++	unsigned long	*pointfree[MAX_NR_ZONES];
++	/* highfree or lowfree depending on whether we've hit a watermark */
++};
++
++/*
++ * prefetch_stats stores the free ram data of each node and this is used to
++ * determine if a node is suitable for prefetching into.
++ */
++struct prefetch_stats {
++	nodemask_t	prefetch_nodes;
++	/* Which nodes are currently suited to prefetching */
++	unsigned long	prefetched_pages;
++	/* Total pages we've prefetched on this wakeup of kprefetchd */
++	struct node_stats node[MAX_NUMNODES];
++};
++
++static struct prefetch_stats sp_stat;
++
++/*
++ * This tries to read a swp_entry_t into swap cache for swap prefetching.
++ * If it returns TRICKLE_DELAY we should delay further prefetching.
++ */
++static enum trickle_return trickle_swap_cache_async(const swp_entry_t entry,
++	const int node)
++{
++	enum trickle_return ret = TRICKLE_FAILED;
++	struct page *page;
++
++	read_lock_irq(&swapper_space.tree_lock);
++	/* Entry may already exist */
++	page = radix_tree_lookup(&swapper_space.page_tree, entry.val);
++	read_unlock_irq(&swapper_space.tree_lock);
++	if (page) {
++		remove_from_swapped_list(entry.val);
++		goto out;
++	}
++
++	/*
++	 * Get a new page to read from swap. We have already checked the
++	 * watermarks so __alloc_pages will not call on reclaim.
++	 */
++	page = alloc_pages_node(node, GFP_HIGHUSER & ~__GFP_WAIT, 0);
++	if (unlikely(!page)) {
++		ret = TRICKLE_DELAY;
++		goto out;
++	}
++
++	if (add_to_swap_cache(page, entry)) {
++		/* Failed to add to swap cache */
++		goto out_release;
++	}
++
++	/* Add them to the tail of the inactive list to preserve LRU order */
++	lru_cache_add_tail(page);
++	if (unlikely(swap_readpage(NULL, page))) {
++		ret = TRICKLE_DELAY;
++		goto out_release;
++	}
++
++	sp_stat.prefetched_pages++;
++	sp_stat.node[node].last_free--;
++
++	ret = TRICKLE_SUCCESS;
++out_release:
++	page_cache_release(page);
++out:
++	return ret;
++}
++
++static void clear_last_prefetch_free(void)
++{
++	int node;
++
++	/*
++	 * Reset the nodes suitable for prefetching to all nodes. We could
++	 * update the data to take into account memory hotplug if desired..
++	 */
++	sp_stat.prefetch_nodes = node_online_map;
++	for_each_node_mask(node, sp_stat.prefetch_nodes) {
++		struct node_stats *ns = &sp_stat.node[node];
++
++		ns->last_free = 0;
++	}
++}
++
++static void clear_current_prefetch_free(void)
++{
++	int node;
++
++	sp_stat.prefetch_nodes = node_online_map;
++	for_each_node_mask(node, sp_stat.prefetch_nodes) {
++		struct node_stats *ns = &sp_stat.node[node];
++
++		ns->current_free = 0;
++	}
++}
++
++/*
++ * This updates the high and low watermarks of amount of free ram in each
++ * node used to start and stop prefetching. We prefetch from pages_high * 4
++ * down to pages_high * 3.
++ */
++static void examine_free_limits(void)
++{
++	struct zone *z;
++
++	for_each_zone(z) {
++		struct node_stats *ns;
++		int idx;
++
++		if (!populated_zone(z))
++			continue;
++
++		ns = &sp_stat.node[z->zone_pgdat->node_id];
++		idx = zone_idx(z);
++		ns->lowfree[idx] = z->pages_high * 3;
++		ns->highfree[idx] = ns->lowfree[idx] + z->pages_high;
++
++		if (zone_page_state(z, NR_FREE_PAGES) > ns->highfree[idx]) {
++			/*
++			 * We've gotten above the high watermark of free pages
++			 * so we can start prefetching till we get to the low
++			 * watermark.
++			 */
++			ns->pointfree[idx] = &ns->lowfree[idx];
++		}
++	}
++}
++
++/*
++ * We want to be absolutely certain it's ok to start prefetching.
++ */
++static int prefetch_suitable(void)
++{
++	unsigned long limit;
++	struct zone *z;
++	int node, ret = 0, test_pagestate = 0;
++
++	/* Purposefully racy */
++	if (test_bit(0, &swapped.busy)) {
++		__clear_bit(0, &swapped.busy);
++		goto out;
++	}
++
++	/*
++	 * get_page_state and above_background_load are expensive so we only
++	 * perform them every SWAP_CLUSTER_MAX prefetched_pages.
++	 * We test to see if we're above_background_load as disk activity
++	 * even at low priority can cause interrupt induced scheduling
++	 * latencies.
++	 */
++	if (!(sp_stat.prefetched_pages % SWAP_CLUSTER_MAX)) {
++		if (above_background_load())
++			goto out;
++		test_pagestate = 1;
++	}
++
++	clear_current_prefetch_free();
++
++	/*
++	 * Have some hysteresis between where page reclaiming and prefetching
++	 * will occur to prevent ping-ponging between them.
++	 */
++	for_each_zone(z) {
++		struct node_stats *ns;
++		unsigned long free;
++		int idx;
++
++		if (!populated_zone(z))
++			continue;
++
++		node = z->zone_pgdat->node_id;
++		ns = &sp_stat.node[node];
++		idx = zone_idx(z);
++
++		free = zone_page_state(z, NR_FREE_PAGES);
++		if (free < *ns->pointfree[idx]) {
++			/*
++			 * Free pages have dropped below the low watermark so
++			 * we won't start prefetching again till we hit the
++			 * high watermark of free pages.
++			 */
++			ns->pointfree[idx] = &ns->highfree[idx];
++			node_clear(node, sp_stat.prefetch_nodes);
++			continue;
++		}
++		ns->current_free += free;
++	}
++
++	/*
++	 * We iterate over each node testing to see if it is suitable for
++	 * prefetching and clear the nodemask if it is not.
++	 */
++	for_each_node_mask(node, sp_stat.prefetch_nodes) {
++		struct node_stats *ns = &sp_stat.node[node];
++
++		/*
++		 * We check to see that pages are not being allocated
++		 * elsewhere at any significant rate implying any
++		 * degree of memory pressure (eg during file reads)
++		 */
++		if (ns->last_free) {
++			if (ns->current_free + SWAP_CLUSTER_MAX <
++			    ns->last_free) {
++				ns->last_free = ns->current_free;
++				node_clear(node,
++					sp_stat.prefetch_nodes);
++				continue;
++			}
++		} else
++			ns->last_free = ns->current_free;
++
++		if (!test_pagestate)
++			continue;
++
++		/* We shouldn't prefetch when we are doing writeback */
++		if (node_page_state(node, NR_WRITEBACK)) {
++			node_clear(node, sp_stat.prefetch_nodes);
++			continue;
++		}
++
++		/*
++		 * >2/3 of the ram on this node is mapped, slab, swapcache or
++		 * dirty, we need to leave some free for pagecache.
++		 */
++		limit = node_page_state(node, NR_FILE_PAGES);
++		limit += node_page_state(node, NR_SLAB_RECLAIMABLE);
++		limit += node_page_state(node, NR_SLAB_UNRECLAIMABLE);
++		limit += node_page_state(node, NR_FILE_DIRTY);
++		limit += node_page_state(node, NR_UNSTABLE_NFS);
++		limit += total_swapcache_pages;
++		if (limit > ns->prefetch_watermark) {
++			node_clear(node, sp_stat.prefetch_nodes);
++			continue;
++		}
++	}
++
++	if (nodes_empty(sp_stat.prefetch_nodes))
++		goto out;
++
++	/* Survived all that? Hooray we can prefetch! */
++	ret = 1;
++out:
++	return ret;
++}
++
++/*
++ * Get previous swapped entry when iterating over all entries. swapped.lock
++ * should be held and we should already ensure that entry exists.
++ */
++static inline struct swapped_entry *prev_swapped_entry
++	(struct swapped_entry *entry)
++{
++	return list_entry(entry->swapped_list.prev->prev,
++		struct swapped_entry, swapped_list);
++}
++
++/*
++ * trickle_swap is the main function that initiates the swap prefetching. It
++ * first checks to see if the busy flag is set, and does not prefetch if it
++ * is, as the flag implied we are low on memory or swapping in currently.
++ * Otherwise it runs until prefetch_suitable fails which occurs when the
++ * vm is busy, we prefetch to the watermark, or the list is empty or we have
++ * iterated over all entries
++ */
++static enum trickle_return trickle_swap(void)
++{
++	enum trickle_return ret = TRICKLE_DELAY;
++	struct swapped_entry *entry;
++	unsigned long flags;
++
++	/*
++	 * If laptop_mode is enabled don't prefetch to avoid hard drives
++	 * doing unnecessary spin-ups
++	 */
++	if (!swap_prefetch || laptop_mode)
++		return ret;
++
++	examine_free_limits();
++	entry = NULL;
++
++	for ( ; ; ) {
++		swp_entry_t swp_entry;
++		int node;
++
++		if (!prefetch_suitable())
++			break;
++
++		spin_lock_irqsave(&swapped.lock, flags);
++		if (list_empty(&swapped.list)) {
++			ret = TRICKLE_FAILED;
++			spin_unlock_irqrestore(&swapped.lock, flags);
++			break;
++		}
++
++		if (!entry) {
++			/*
++			 * This sets the entry for the first iteration. It
++			 * also is a safeguard against the entry disappearing
++			 * while the lock is not held.
++			 */
++			entry = list_entry(swapped.list.prev,
++				struct swapped_entry, swapped_list);
++		} else if (entry->swapped_list.prev == swapped.list.next) {
++			/*
++			 * If we have iterated over all entries and there are
++			 * still entries that weren't swapped out there may
++			 * be a reason we could not swap them back in so
++			 * delay attempting further prefetching.
++			 */
++			spin_unlock_irqrestore(&swapped.lock, flags);
++			break;
++		}
++
++		node = get_swap_entry_node(entry);
++		if (!node_isset(node, sp_stat.prefetch_nodes)) {
++			/*
++			 * We found an entry that belongs to a node that is
++			 * not suitable for prefetching so skip it.
++			 */
++			entry = prev_swapped_entry(entry);
++			spin_unlock_irqrestore(&swapped.lock, flags);
++			continue;
++		}
++		swp_entry = entry->swp_entry;
++		entry = prev_swapped_entry(entry);
++		spin_unlock_irqrestore(&swapped.lock, flags);
++
++		if (trickle_swap_cache_async(swp_entry, node) == TRICKLE_DELAY)
++			break;
++	}
++
++	if (sp_stat.prefetched_pages) {
++		lru_add_drain();
++		sp_stat.prefetched_pages = 0;
++	}
++	return ret;
++}
++
++static int kprefetchd(void *__unused)
++{
++	struct sched_param param = { .sched_priority = 0 };
++
++	sched_setscheduler(current, SCHED_BATCH, &param);
++	set_user_nice(current, 19);
++	/* Set ioprio to lowest if supported by i/o scheduler */
++	sys_ioprio_set(IOPRIO_WHO_PROCESS, 0, IOPRIO_CLASS_IDLE);
++
++	/* kprefetchd has nothing to do until it is woken up the first time */
++	set_current_state(TASK_INTERRUPTIBLE);
++	schedule();
++
++	do {
++		try_to_freeze();
++
++		/*
++		 * TRICKLE_FAILED implies no entries left - we do not schedule
++		 * a wakeup, and further delay the next one.
++		 */
++		if (trickle_swap() == TRICKLE_FAILED) {
++			set_current_state(TASK_INTERRUPTIBLE);
++			schedule();
++		}
++		clear_last_prefetch_free();
++		schedule_timeout_interruptible(PREFETCH_DELAY);
++	} while (!kthread_should_stop());
++
++	return 0;
++}
++
++/*
++ * Create kmem cache for swapped entries
++ */
++void __init prepare_swap_prefetch(void)
++{
++	struct zone *zone;
++
++	swapped.cache = kmem_cache_create("swapped_entry",
++		sizeof(struct swapped_entry), 0, SLAB_PANIC, NULL, NULL);
++
++	/*
++	 * Set max number of entries to 2/3 the size of physical ram  as we
++	 * only ever prefetch to consume 2/3 of the ram.
++	 */
++	swapped.maxcount = nr_free_pagecache_pages() / 3 * 2;
++
++	for_each_zone(zone) {
++		unsigned long present;
++		struct node_stats *ns;
++		int idx;
++
++		present = zone->present_pages;
++		if (!present)
++			continue;
++
++		ns = &sp_stat.node[zone->zone_pgdat->node_id];
++		ns->prefetch_watermark += present / 3 * 2;
++		idx = zone_idx(zone);
++		ns->pointfree[idx] = &ns->highfree[idx];
++	}
++}
++
++static int __init kprefetchd_init(void)
++{
++	kprefetchd_task = kthread_run(kprefetchd, NULL, "kprefetchd");
++
++	return 0;
++}
++
++static void __exit kprefetchd_exit(void)
++{
++	kthread_stop(kprefetchd_task);
++}
++
++module_init(kprefetchd_init);
++module_exit(kprefetchd_exit);
+Index: linux-2.6.21-ck1/mm/swap_state.c
+===================================================================
+--- linux-2.6.21-ck1.orig/mm/swap_state.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/mm/swap_state.c	2007-05-04 12:24:20.000000000 +1000
+@@ -10,6 +10,7 @@
+ #include <linux/mm.h>
+ #include <linux/kernel_stat.h>
+ #include <linux/swap.h>
++#include <linux/swap-prefetch.h>
+ #include <linux/init.h>
+ #include <linux/pagemap.h>
+ #include <linux/buffer_head.h>
+@@ -82,6 +83,7 @@ static int __add_to_swap_cache(struct pa
+ 		error = radix_tree_insert(&swapper_space.page_tree,
+ 						entry.val, page);
+ 		if (!error) {
++			remove_from_swapped_list(entry.val);
+ 			page_cache_get(page);
+ 			SetPageLocked(page);
+ 			SetPageSwapCache(page);
+@@ -95,11 +97,12 @@ static int __add_to_swap_cache(struct pa
+ 	return error;
+ }
+ 
+-static int add_to_swap_cache(struct page *page, swp_entry_t entry)
++int add_to_swap_cache(struct page *page, swp_entry_t entry)
+ {
+ 	int error;
+ 
+ 	if (!swap_duplicate(entry)) {
++		remove_from_swapped_list(entry.val);
+ 		INC_CACHE_INFO(noent_race);
+ 		return -ENOENT;
+ 	}
+@@ -148,6 +151,9 @@ int add_to_swap(struct page * page, gfp_
+ 	swp_entry_t entry;
+ 	int err;
+ 
++	/* Swap prefetching is delayed if we're swapping pages */
++	delay_swap_prefetch();
++
+ 	BUG_ON(!PageLocked(page));
+ 
+ 	for (;;) {
+@@ -320,6 +326,9 @@ struct page *read_swap_cache_async(swp_e
+ 	struct page *found_page, *new_page = NULL;
+ 	int err;
+ 
++	/* Swap prefetching is delayed if we're already reading from swap */
++	delay_swap_prefetch();
++
+ 	do {
+ 		/*
+ 		 * First check the swap cache.  Since this is normally
+Index: linux-2.6.21-ck1/mm/vmscan.c
+===================================================================
+--- linux-2.6.21-ck1.orig/mm/vmscan.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/mm/vmscan.c	2007-05-04 12:24:21.000000000 +1000
+@@ -16,6 +16,7 @@
+ #include <linux/slab.h>
+ #include <linux/kernel_stat.h>
+ #include <linux/swap.h>
++#include <linux/swap-prefetch.h>
+ #include <linux/pagemap.h>
+ #include <linux/init.h>
+ #include <linux/highmem.h>
+@@ -36,6 +37,7 @@
+ #include <linux/rwsem.h>
+ #include <linux/delay.h>
+ #include <linux/kthread.h>
++#include <linux/timer.h>
+ #include <linux/freezer.h>
+ 
+ #include <asm/tlbflush.h>
+@@ -63,7 +65,7 @@ struct scan_control {
+ 	 * whole list at once. */
+ 	int swap_cluster_max;
+ 
+-	int swappiness;
++	int mapped;
+ 
+ 	int all_unreclaimable;
+ };
+@@ -110,9 +112,10 @@ struct shrinker {
+ #endif
+ 
+ /*
+- * From 0 .. 100.  Higher means more swappy.
++ * From 0 .. 100.  Lower means more swappy.
+  */
+-int vm_swappiness = 60;
++int vm_mapped __read_mostly = 66;
++int vm_hardmaplimit __read_mostly = 1;
+ long vm_total_pages;	/* The total number of pages which the VM controls */
+ 
+ static LIST_HEAD(shrinker_list);
+@@ -424,6 +427,7 @@ int remove_mapping(struct address_space 
+ 
+ 	if (PageSwapCache(page)) {
+ 		swp_entry_t swap = { .val = page_private(page) };
++		add_to_swapped_list(page);
+ 		__delete_from_swap_cache(page);
+ 		write_unlock_irq(&mapping->tree_lock);
+ 		swap_free(swap);
+@@ -807,10 +811,14 @@ static void shrink_active_list(unsigned 
+ 		 * The distress ratio is important - we don't want to start
+ 		 * going oom.
+ 		 *
+-		 * A 100% value of vm_swappiness overrides this algorithm
+-		 * altogether.
++		 * This distress value is ignored if we apply a hardmaplimit except
++		 * in extreme distress.
++		 *
++		 * A 0% value of vm_mapped overrides this algorithm altogether.
+ 		 */
+-		swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
++		swap_tendency = mapped_ratio * 100 / (sc->mapped + 1);
++		if (!vm_hardmaplimit || distress == 100)
++			swap_tendency += distress;
+ 
+ 		/*
+ 		 * Now use this metric to decide whether to start moving mapped
+@@ -959,6 +967,41 @@ static unsigned long shrink_zone(int pri
+ }
+ 
+ /*
++ * Helper functions to adjust nice level of kswapd, based on the priority of
++ * the task (p) that called it. If it is already higher priority we do not
++ * demote its nice level since it is still working on behalf of a higher
++ * priority task. With kernel threads we leave it at nice 0.
++ *
++ * We don't ever run kswapd real time, so if a real time task calls kswapd we
++ * set it to highest SCHED_NORMAL priority.
++ */
++static int effective_sc_prio(struct task_struct *p)
++{
++	if (likely(p->mm)) {
++		if (rt_task(p))
++			return -20;
++		if (idleprio_task(p))
++			return 19;
++		return task_nice(p);
++	}
++	return 0;
++}
++
++static void set_kswapd_nice(struct task_struct *kswapd, struct task_struct *p,
++			    int active)
++{
++	long nice = effective_sc_prio(p);
++
++	if (task_nice(kswapd) > nice || !active)
++		set_user_nice(kswapd, nice);
++}
++
++static int sc_priority(struct task_struct *p)
++{
++	return (DEF_PRIORITY + (DEF_PRIORITY * effective_sc_prio(p) / 40));
++}
++
++/*
+  * This is the direct reclaim path, for page-allocating processes.  We only
+  * try to reclaim pages from zones which will satisfy the caller's allocation
+  * request.
+@@ -1015,7 +1058,8 @@ static unsigned long shrink_zones(int pr
+  * holds filesystem locks which prevent writeout this might not work, and the
+  * allocation attempt will fail.
+  */
+-unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask)
++unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask,
++				struct task_struct *p)
+ {
+ 	int priority;
+ 	int ret = 0;
+@@ -1023,15 +1067,20 @@ unsigned long try_to_free_pages(struct z
+ 	unsigned long nr_reclaimed = 0;
+ 	struct reclaim_state *reclaim_state = current->reclaim_state;
+ 	unsigned long lru_pages = 0;
+-	int i;
++	int i, scan_priority = DEF_PRIORITY;
+ 	struct scan_control sc = {
+ 		.gfp_mask = gfp_mask,
+ 		.may_writepage = !laptop_mode,
+ 		.swap_cluster_max = SWAP_CLUSTER_MAX,
+ 		.may_swap = 1,
+-		.swappiness = vm_swappiness,
++		.mapped = vm_mapped,
+ 	};
+ 
++	if (p)
++		scan_priority = sc_priority(p);
++
++	delay_swap_prefetch();
++
+ 	count_vm_event(ALLOCSTALL);
+ 
+ 	for (i = 0; zones[i] != NULL; i++) {
+@@ -1044,7 +1093,7 @@ unsigned long try_to_free_pages(struct z
+ 				+ zone_page_state(zone, NR_INACTIVE);
+ 	}
+ 
+-	for (priority = DEF_PRIORITY; priority >= 0; priority--) {
++	for (priority = scan_priority; priority >= 0; priority--) {
+ 		sc.nr_scanned = 0;
+ 		if (!priority)
+ 			disable_swap_token();
+@@ -1074,7 +1123,7 @@ unsigned long try_to_free_pages(struct z
+ 		}
+ 
+ 		/* Take a nap, wait for some writeback to complete */
+-		if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
++		if (sc.nr_scanned && priority < scan_priority - 2)
+ 			congestion_wait(WRITE, HZ/10);
+ 	}
+ 	/* top priority shrink_caches still had more to do? don't OOM, then */
+@@ -1124,9 +1173,9 @@ out:
+  */
+ static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
+ {
+-	int all_zones_ok;
++	int all_zones_ok = 0;
+ 	int priority;
+-	int i;
++	int i, scan_priority;
+ 	unsigned long total_scanned;
+ 	unsigned long nr_reclaimed;
+ 	struct reclaim_state *reclaim_state = current->reclaim_state;
+@@ -1134,7 +1183,7 @@ static unsigned long balance_pgdat(pg_da
+ 		.gfp_mask = GFP_KERNEL,
+ 		.may_swap = 1,
+ 		.swap_cluster_max = SWAP_CLUSTER_MAX,
+-		.swappiness = vm_swappiness,
++		.mapped = vm_mapped,
+ 	};
+ 	/*
+ 	 * temp_priority is used to remember the scanning priority at which
+@@ -1142,6 +1191,8 @@ static unsigned long balance_pgdat(pg_da
+ 	 */
+ 	int temp_priority[MAX_NR_ZONES];
+ 
++	scan_priority = sc_priority(pgdat->kswapd);
++
+ loop_again:
+ 	total_scanned = 0;
+ 	nr_reclaimed = 0;
+@@ -1149,9 +1200,9 @@ loop_again:
+ 	count_vm_event(PAGEOUTRUN);
+ 
+ 	for (i = 0; i < pgdat->nr_zones; i++)
+-		temp_priority[i] = DEF_PRIORITY;
++		temp_priority[i] = scan_priority;
+ 
+-	for (priority = DEF_PRIORITY; priority >= 0; priority--) {
++	for (priority = scan_priority; priority >= 0; priority--) {
+ 		int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
+ 		unsigned long lru_pages = 0;
+ 
+@@ -1167,15 +1218,22 @@ loop_again:
+ 		 */
+ 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
+ 			struct zone *zone = pgdat->node_zones + i;
++			unsigned long watermark;
+ 
+ 			if (!populated_zone(zone))
+ 				continue;
+ 
+-			if (zone->all_unreclaimable && priority != DEF_PRIORITY)
++			if (zone->all_unreclaimable && priority != scan_priority)
+ 				continue;
+ 
+-			if (!zone_watermark_ok(zone, order, zone->pages_high,
+-					       0, 0)) {
++			/*
++			 * The watermark is relaxed depending on the
++			 * level of "priority" till it drops to
++			 * pages_high.
++			 */
++			watermark = zone->pages_high + (zone->pages_high *
++				    priority / scan_priority);
++			if (!zone_watermark_ok(zone, order, watermark, 0, 0)) {
+ 				end_zone = i;
+ 				break;
+ 			}
+@@ -1202,14 +1260,18 @@ loop_again:
+ 		for (i = 0; i <= end_zone; i++) {
+ 			struct zone *zone = pgdat->node_zones + i;
+ 			int nr_slab;
++			unsigned long watermark;
+ 
+ 			if (!populated_zone(zone))
+ 				continue;
+ 
+-			if (zone->all_unreclaimable && priority != DEF_PRIORITY)
++			if (zone->all_unreclaimable && priority != scan_priority)
+ 				continue;
+ 
+-			if (!zone_watermark_ok(zone, order, zone->pages_high,
++			watermark = zone->pages_high + (zone->pages_high *
++				    priority / scan_priority);
++
++			if (!zone_watermark_ok(zone, order, watermark,
+ 					       end_zone, 0))
+ 				all_zones_ok = 0;
+ 			temp_priority[i] = priority;
+@@ -1242,7 +1304,7 @@ loop_again:
+ 		 * OK, kswapd is getting into trouble.  Take a nap, then take
+ 		 * another pass across the zones.
+ 		 */
+-		if (total_scanned && priority < DEF_PRIORITY - 2)
++		if (total_scanned && priority < scan_priority - 2)
+ 			congestion_wait(WRITE, HZ/10);
+ 
+ 		/*
+@@ -1276,6 +1338,8 @@ out:
+ 	return nr_reclaimed;
+ }
+ 
++#define WT_EXPIRY	(HZ * 5)	/* Time to wakeup watermark_timer */
++
+ /*
+  * The background pageout daemon, started as a kernel thread
+  * from the init process. 
+@@ -1325,6 +1389,8 @@ static int kswapd(void *p)
+ 
+ 		try_to_freeze();
+ 
++		/* kswapd has been busy so delay watermark_timer */
++		mod_timer(&pgdat->watermark_timer, jiffies + WT_EXPIRY);
+ 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
+ 		new_order = pgdat->kswapd_max_order;
+ 		pgdat->kswapd_max_order = 0;
+@@ -1335,6 +1401,7 @@ static int kswapd(void *p)
+ 			 */
+ 			order = new_order;
+ 		} else {
++			set_user_nice(tsk, 0);
+ 			schedule();
+ 			order = pgdat->kswapd_max_order;
+ 		}
+@@ -1348,9 +1415,10 @@ static int kswapd(void *p)
+ /*
+  * A zone is low on free memory, so wake its kswapd task to service it.
+  */
+-void wakeup_kswapd(struct zone *zone, int order)
++void wakeup_kswapd(struct zone *zone, int order, struct task_struct *p)
+ {
+ 	pg_data_t *pgdat;
++	int active;
+ 
+ 	if (!populated_zone(zone))
+ 		return;
+@@ -1362,7 +1430,9 @@ void wakeup_kswapd(struct zone *zone, in
+ 		pgdat->kswapd_max_order = order;
+ 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
+ 		return;
+-	if (!waitqueue_active(&pgdat->kswapd_wait))
++	active = waitqueue_active(&pgdat->kswapd_wait);
++	set_kswapd_nice(pgdat->kswapd, p, active);
++	if (!active)
+ 		return;
+ 	wake_up_interruptible(&pgdat->kswapd_wait);
+ }
+@@ -1381,6 +1451,8 @@ static unsigned long shrink_all_zones(un
+ 	struct zone *zone;
+ 	unsigned long nr_to_scan, ret = 0;
+ 
++	delay_swap_prefetch();
++
+ 	for_each_zone(zone) {
+ 
+ 		if (!populated_zone(zone))
+@@ -1440,7 +1512,7 @@ unsigned long shrink_all_memory(unsigned
+ 		.may_swap = 0,
+ 		.swap_cluster_max = nr_pages,
+ 		.may_writepage = 1,
+-		.swappiness = vm_swappiness,
++		.mapped = vm_mapped,
+ 	};
+ 
+ 	current->reclaim_state = &reclaim_state;
+@@ -1475,7 +1547,7 @@ unsigned long shrink_all_memory(unsigned
+ 		/* Force reclaiming mapped pages in the passes #3 and #4 */
+ 		if (pass > 2) {
+ 			sc.may_swap = 1;
+-			sc.swappiness = 100;
++			sc.mapped = 0;
+ 		}
+ 
+ 		for (prio = DEF_PRIORITY; prio >= 0; prio--) {
+@@ -1539,20 +1611,57 @@ static int __devinit cpu_callback(struct
+ }
+ 
+ /*
++ * We wake up kswapd every WT_EXPIRY till free ram is above pages_lots
++ */
++static void watermark_wakeup(unsigned long data)
++{
++	pg_data_t *pgdat = (pg_data_t *)data;
++	struct timer_list *wt = &pgdat->watermark_timer;
++	int i;
++
++	if (!waitqueue_active(&pgdat->kswapd_wait) || above_background_load())
++		goto out;
++	for (i = pgdat->nr_zones - 1; i >= 0; i--) {
++		struct zone *z = pgdat->node_zones + i;
++
++		if (!populated_zone(z) || is_highmem(z)) {
++			/* We are better off leaving highmem full */
++			continue;
++		}
++		if (!zone_watermark_ok(z, 0, z->pages_lots, 0, 0)) {
++			wake_up_interruptible(&pgdat->kswapd_wait);
++			goto out;
++		}
++	}
++out:
++	mod_timer(wt, jiffies + WT_EXPIRY);
++	return;
++}
++
++/*
+  * This kswapd start function will be called by init and node-hot-add.
+  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
+  */
+ int kswapd_run(int nid)
+ {
+ 	pg_data_t *pgdat = NODE_DATA(nid);
++	struct timer_list *wt;
+ 	int ret = 0;
+ 
+ 	if (pgdat->kswapd)
+ 		return 0;
+ 
++	wt = &pgdat->watermark_timer;
++	init_timer(wt);
++	wt->data = (unsigned long)pgdat;
++	wt->function = watermark_wakeup;
++	wt->expires = jiffies + WT_EXPIRY;
++	add_timer(wt);
++
+ 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
+ 	if (IS_ERR(pgdat->kswapd)) {
+ 		/* failure at boot is fatal */
++		del_timer(wt);
+ 		BUG_ON(system_state == SYSTEM_BOOTING);
+ 		printk("Failed to start kswapd on node %d\n",nid);
+ 		ret = -1;
+@@ -1623,7 +1732,7 @@ static int __zone_reclaim(struct zone *z
+ 		.swap_cluster_max = max_t(unsigned long, nr_pages,
+ 					SWAP_CLUSTER_MAX),
+ 		.gfp_mask = gfp_mask,
+-		.swappiness = vm_swappiness,
++		.mapped = vm_mapped,
+ 	};
+ 	unsigned long slab_reclaimable;
+ 
+Index: linux-2.6.21-ck1/include/linux/mm_inline.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/mm_inline.h	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/mm_inline.h	2007-05-04 12:24:20.000000000 +1000
+@@ -13,6 +13,13 @@ add_page_to_inactive_list(struct zone *z
+ }
+ 
+ static inline void
++add_page_to_inactive_list_tail(struct zone *zone, struct page *page)
++{
++	list_add_tail(&page->lru, &zone->inactive_list);
++	__inc_zone_state(zone, NR_INACTIVE);
++}
++
++static inline void
+ del_page_from_active_list(struct zone *zone, struct page *page)
+ {
+ 	list_del(&page->lru);
+Index: linux-2.6.21-ck1/include/linux/swap-prefetch.h
+===================================================================
+--- /dev/null	1970-01-01 00:00:00.000000000 +0000
++++ linux-2.6.21-ck1/include/linux/swap-prefetch.h	2007-05-04 12:24:20.000000000 +1000
+@@ -0,0 +1,55 @@
++#ifndef SWAP_PREFETCH_H_INCLUDED
++#define SWAP_PREFETCH_H_INCLUDED
++
++#ifdef CONFIG_SWAP_PREFETCH
++/* mm/swap_prefetch.c */
++extern int swap_prefetch;
++struct swapped_entry {
++	swp_entry_t		swp_entry;	/* The actual swap entry */
++	struct list_head	swapped_list;	/* Linked list of entries */
++#if MAX_NUMNODES > 1
++	int			node;		/* Node id */
++#endif
++} __attribute__((packed));
++
++static inline void store_swap_entry_node(struct swapped_entry *entry,
++	struct page *page)
++{
++#if MAX_NUMNODES > 1
++	entry->node = page_to_nid(page);
++#endif
++}
++
++static inline int get_swap_entry_node(struct swapped_entry *entry)
++{
++#if MAX_NUMNODES > 1
++	return entry->node;
++#else
++	return 0;
++#endif
++}
++
++extern void add_to_swapped_list(struct page *page);
++extern void remove_from_swapped_list(const unsigned long index);
++extern void delay_swap_prefetch(void);
++extern void prepare_swap_prefetch(void);
++
++#else	/* CONFIG_SWAP_PREFETCH */
++static inline void add_to_swapped_list(struct page *__unused)
++{
++}
++
++static inline void prepare_swap_prefetch(void)
++{
++}
++
++static inline void remove_from_swapped_list(const unsigned long __unused)
++{
++}
++
++static inline void delay_swap_prefetch(void)
++{
++}
++#endif	/* CONFIG_SWAP_PREFETCH */
++
++#endif		/* SWAP_PREFETCH_H_INCLUDED */
+Index: linux-2.6.21-ck1/include/linux/sysctl.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/sysctl.h	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/sysctl.h	2007-05-04 12:24:20.000000000 +1000
+@@ -190,7 +190,7 @@ enum
+ 	VM_OVERCOMMIT_RATIO=16, /* percent of RAM to allow overcommit in */
+ 	VM_PAGEBUF=17,		/* struct: Control pagebuf parameters */
+ 	VM_HUGETLB_PAGES=18,	/* int: Number of available Huge Pages */
+-	VM_SWAPPINESS=19,	/* Tendency to steal mapped memory */
++	VM_MAPPED=19,		/* percent mapped min while evicting cache */
+ 	VM_LOWMEM_RESERVE_RATIO=20,/* reservation ratio for lower memory zones */
+ 	VM_MIN_FREE_KBYTES=21,	/* Minimum free kilobytes to maintain */
+ 	VM_MAX_MAP_COUNT=22,	/* int: Maximum number of mmaps/address-space */
+Index: linux-2.6.21-ck1/include/linux/mmzone.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/mmzone.h	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/mmzone.h	2007-05-04 12:24:21.000000000 +1000
+@@ -13,6 +13,7 @@
+ #include <linux/init.h>
+ #include <linux/seqlock.h>
+ #include <linux/nodemask.h>
++#include <linux/timer.h>
+ #include <asm/atomic.h>
+ #include <asm/page.h>
+ 
+@@ -178,7 +179,7 @@ enum zone_type {
+ 
+ struct zone {
+ 	/* Fields commonly accessed by the page allocator */
+-	unsigned long		pages_min, pages_low, pages_high;
++	unsigned long		pages_min, pages_low, pages_high, pages_lots;
+ 	/*
+ 	 * We don't know if the memory that we're going to allocate will be freeable
+ 	 * or/and it will be released eventually, so to avoid totally wasting several
+@@ -449,6 +450,7 @@ typedef struct pglist_data {
+ 	wait_queue_head_t kswapd_wait;
+ 	struct task_struct *kswapd;
+ 	int kswapd_max_order;
++	struct timer_list watermark_timer;
+ } pg_data_t;
+ 
+ #define node_present_pages(nid)	(NODE_DATA(nid)->node_present_pages)
+@@ -465,7 +467,7 @@ typedef struct pglist_data {
+ void get_zone_counts(unsigned long *active, unsigned long *inactive,
+ 			unsigned long *free);
+ void build_all_zonelists(void);
+-void wakeup_kswapd(struct zone *zone, int order);
++void wakeup_kswapd(struct zone *zone, int order, struct task_struct *p);
+ int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
+ 		int classzone_idx, int alloc_flags);
+ enum memmap_context {
+Index: linux-2.6.21-ck1/mm/page_alloc.c
+===================================================================
+--- linux-2.6.21-ck1.orig/mm/page_alloc.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/mm/page_alloc.c	2007-05-04 12:24:20.000000000 +1000
+@@ -1277,7 +1277,7 @@ restart:
+ 		goto nopage;
+ 
+ 	for (z = zonelist->zones; *z; z++)
+-		wakeup_kswapd(*z, order);
++		wakeup_kswapd(*z, order, p);
+ 
+ 	/*
+ 	 * OK, we're below the kswapd watermark and have kicked background
+@@ -1341,7 +1341,7 @@ nofail_alloc:
+ 	reclaim_state.reclaimed_slab = 0;
+ 	p->reclaim_state = &reclaim_state;
+ 
+-	did_some_progress = try_to_free_pages(zonelist->zones, gfp_mask);
++	did_some_progress = try_to_free_pages(zonelist->zones, gfp_mask, p);
+ 
+ 	p->reclaim_state = NULL;
+ 	p->flags &= ~PF_MEMALLOC;
+@@ -1597,6 +1597,7 @@ void show_free_areas(void)
+ 			" min:%lukB"
+ 			" low:%lukB"
+ 			" high:%lukB"
++			" lots:%lukB"
+ 			" active:%lukB"
+ 			" inactive:%lukB"
+ 			" present:%lukB"
+@@ -1608,6 +1609,7 @@ void show_free_areas(void)
+ 			K(zone->pages_min),
+ 			K(zone->pages_low),
+ 			K(zone->pages_high),
++			K(zone->pages_lots),
+ 			K(zone_page_state(zone, NR_ACTIVE)),
+ 			K(zone_page_state(zone, NR_INACTIVE)),
+ 			K(zone->present_pages),
+@@ -3146,6 +3148,7 @@ void setup_per_zone_pages_min(void)
+ 
+ 		zone->pages_low   = zone->pages_min + (tmp >> 2);
+ 		zone->pages_high  = zone->pages_min + (tmp >> 1);
++		zone->pages_lots  = zone->pages_min + tmp;
+ 		spin_unlock_irqrestore(&zone->lru_lock, flags);
+ 	}
+ 
+Index: linux-2.6.21-ck1/fs/buffer.c
+===================================================================
+--- linux-2.6.21-ck1.orig/fs/buffer.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/fs/buffer.c	2007-05-04 12:24:20.000000000 +1000
+@@ -363,7 +363,7 @@ static void free_more_memory(void)
+ 	for_each_online_pgdat(pgdat) {
+ 		zones = pgdat->node_zonelists[gfp_zone(GFP_NOFS)].zones;
+ 		if (*zones)
+-			try_to_free_pages(zones, GFP_NOFS);
++			try_to_free_pages(zones, GFP_NOFS, NULL);
+ 	}
+ }
+ 
+Index: linux-2.6.21-ck1/mm/filemap.c
+===================================================================
+--- linux-2.6.21-ck1.orig/mm/filemap.c	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/mm/filemap.c	2007-05-04 12:24:21.000000000 +1000
+@@ -466,6 +466,16 @@ int add_to_page_cache_lru(struct page *p
+ 	return ret;
+ }
+ 
++int add_to_page_cache_lru_tail(struct page *page,
++	struct address_space *mapping, pgoff_t offset, gfp_t gfp_mask)
++{
++	int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
++
++	if (ret == 0)
++		lru_cache_add_tail(page);
++	return ret;
++}
++
+ #ifdef CONFIG_NUMA
+ struct page *__page_cache_alloc(gfp_t gfp)
+ {
+@@ -836,6 +846,34 @@ static void shrink_readahead_size_eio(st
+ 	ra->ra_pages /= 4;
+ }
+ 
++/*
++ * Sysctl which determines whether we should read from large files to the
++ * tail of the inactive lru list.
++ */
++int vm_tail_largefiles __read_mostly = 1;
++
++static inline int nr_mapped(void)
++{
++	return global_page_state(NR_FILE_MAPPED) +
++		global_page_state(NR_ANON_PAGES);
++}
++
++/*
++ * This examines how large in pages a file size is and returns 1 if it is
++ * more than half the unmapped ram. Avoid doing read_page_state which is
++ * expensive unless we already know it is likely to be large enough.
++ */
++static int large_isize(unsigned long nr_pages)
++{
++	if (nr_pages * 6 > vm_total_pages) {
++		 unsigned long unmapped_ram = vm_total_pages - nr_mapped();
++
++		if (nr_pages * 2 > unmapped_ram)
++			return 1;
++	}
++	return 0;
++}
++
+ /**
+  * do_generic_mapping_read - generic file read routine
+  * @mapping:	address_space to be read
+@@ -1044,8 +1082,19 @@ no_cached_page:
+ 				goto out;
+ 			}
+ 		}
+-		error = add_to_page_cache_lru(cached_page, mapping,
+-						index, GFP_KERNEL);
++
++		/*
++		 * If we know the file is large we add the pages read to the
++		 * end of the lru as we're unlikely to be able to cache the
++		 * whole file in ram so make those pages the first to be
++		 * dropped if not referenced soon.
++		 */
++		if (vm_tail_largefiles && large_isize(end_index))
++			error = add_to_page_cache_lru_tail(cached_page,
++						mapping, index, GFP_KERNEL);
++		else
++			error = add_to_page_cache_lru(cached_page, mapping,
++							index, GFP_KERNEL);
+ 		if (error) {
+ 			if (error == -EEXIST)
+ 				goto find_page;
+Index: linux-2.6.21-ck1/Documentation/filesystems/proc.txt
+===================================================================
+--- linux-2.6.21-ck1.orig/Documentation/filesystems/proc.txt	2007-05-04 12:24:01.000000000 +1000
++++ linux-2.6.21-ck1/Documentation/filesystems/proc.txt	2007-05-04 12:24:21.000000000 +1000
+@@ -1325,6 +1325,14 @@ To free pagecache, dentries and inodes:
+ As this is a non-destructive operation and dirty objects are not freeable, the
+ user should run `sync' first.
+ 
++tail_largefiles
++---------------
++
++When enabled reads from large files to the tail end of the inactive lru list.
++This means that any cache from reading large files is dropped very quickly,
++preventing loss of mapped ram and useful pagecache when large files are read.
++This does, however, make caching less effective when working with large files.
++
+ 
+ 2.5 /proc/sys/dev - Device specific parameters
+ ----------------------------------------------
+Index: linux-2.6.21-ck1/arch/i386/Kconfig
+===================================================================
+--- linux-2.6.21-ck1.orig/arch/i386/Kconfig	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/arch/i386/Kconfig	2007-05-04 12:24:21.000000000 +1000
+@@ -546,7 +546,7 @@ endchoice
+ 
+ choice
+ 	depends on EXPERIMENTAL
+-	prompt "Memory split" if EMBEDDED
++	prompt "Memory split"
+ 	default VMSPLIT_3G
+ 	help
+ 	  Select the desired split between kernel and user memory.
+@@ -565,14 +565,14 @@ choice
+ 	  option alone!
+ 
+ 	config VMSPLIT_3G
+-		bool "3G/1G user/kernel split"
++		bool "Default 896MB lowmem (3G/1G user/kernel split)"
+ 	config VMSPLIT_3G_OPT
+ 		depends on !HIGHMEM
+-		bool "3G/1G user/kernel split (for full 1G low memory)"
++		bool "1GB lowmem (3G/1G user/kernel split)"
+ 	config VMSPLIT_2G
+-		bool "2G/2G user/kernel split"
++		bool "2GB lowmem (2G/2G user/kernel split)"
+ 	config VMSPLIT_1G
+-		bool "1G/3G user/kernel split"
++		bool "3GB lowmem (1G/3G user/kernel split)"
+ endchoice
+ 
+ config PAGE_OFFSET
+Index: linux-2.6.21-ck1/kernel/Kconfig.hz
+===================================================================
+--- linux-2.6.21-ck1.orig/kernel/Kconfig.hz	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/kernel/Kconfig.hz	2007-05-04 12:24:21.000000000 +1000
+@@ -4,7 +4,7 @@
+ 
+ choice
+ 	prompt "Timer frequency"
+-	default HZ_250
++	default HZ_1000
+ 	help
+ 	 Allows the configuration of the timer frequency. It is customary
+ 	 to have the timer interrupt run at 1000 Hz but 100 Hz may be more
+@@ -13,8 +13,7 @@ choice
+ 	 contention and cacheline bounces as a result of timer interrupts.
+ 	 Note that the timer interrupt occurs on each processor in an SMP
+ 	 environment leading to NR_CPUS * HZ number of timer interrupts
+-	 per second.
+-
++	 per second.Laptops may also show improved battery life.
+ 
+ 	config HZ_100
+ 		bool "100 HZ"
+@@ -23,13 +22,14 @@ choice
+ 	  with lots of processors that may show reduced performance if
+ 	  too many timer interrupts are occurring.
+ 
+-	config HZ_250
++	config HZ_250_NODEFAULT
+ 		bool "250 HZ"
+ 	help
+-	 250 Hz is a good compromise choice allowing server performance
+-	 while also showing good interactive responsiveness even
+-	 on SMP and NUMA systems. If you are going to be using NTSC video
+-	 or multimedia, selected 300Hz instead.
++	 250 HZ is a lousy compromise choice allowing server interactivity
++	 while also showing desktop throughput and no extra power saving on
++	 laptops. Good for when you can't make up your mind.
++
++	 Recommend 100 or 1000 instead.
+ 
+ 	config HZ_300
+ 		bool "300 HZ"
+@@ -45,12 +45,76 @@ choice
+ 	 1000 Hz is the preferred choice for desktop systems and other
+ 	 systems requiring fast interactive responses to events.
+ 
++	config HZ_1500
++		bool "1500 HZ"
++	help
++	 1500 Hz is an insane value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_2000
++		bool "2000 HZ"
++	help
++	 2000 Hz is an insane value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_3000
++		bool "3000 HZ"
++	help
++	 3000 Hz is an insane value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_4000
++		bool "4000 HZ"
++	help
++	 4000 Hz is an insane value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_5000
++		bool "5000 HZ"
++	help
++	 5000 Hz is an obscene value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_7500
++		bool "7500 HZ"
++	help
++	 7500 Hz is an obscene value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_10000
++		bool "10000 HZ"
++	help
++	 10000 Hz is an obscene value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++
+ endchoice
+ 
+ config HZ
+ 	int
+ 	default 100 if HZ_100
+-	default 250 if HZ_250
++	default 250 if HZ_250_NODEFAULT
+ 	default 300 if HZ_300
+ 	default 1000 if HZ_1000
++	default 1500 if HZ_1500
++	default 2000 if HZ_2000
++	default 3000 if HZ_3000
++	default 4000 if HZ_4000
++	default 5000 if HZ_5000
++	default 7500 if HZ_7500
++	default 10000 if HZ_10000
+ 
+Index: linux-2.6.21-ck1/arch/i386/defconfig
+===================================================================
+--- linux-2.6.21-ck1.orig/arch/i386/defconfig	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/arch/i386/defconfig	2007-05-04 12:24:21.000000000 +1000
+@@ -214,10 +214,10 @@ CONFIG_MTRR=y
+ # CONFIG_IRQBALANCE is not set
+ CONFIG_SECCOMP=y
+ # CONFIG_HZ_100 is not set
+-CONFIG_HZ_250=y
++# CONFIG_HZ_250 is not set
+ # CONFIG_HZ_300 is not set
+-# CONFIG_HZ_1000 is not set
+-CONFIG_HZ=250
++CONFIG_HZ_1000=y
++CONFIG_HZ=1000
+ # CONFIG_KEXEC is not set
+ # CONFIG_CRASH_DUMP is not set
+ CONFIG_PHYSICAL_START=0x100000
+Index: linux-2.6.21-ck1/arch/x86_64/defconfig
+===================================================================
+--- linux-2.6.21-ck1.orig/arch/x86_64/defconfig	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/arch/x86_64/defconfig	2007-05-04 12:24:21.000000000 +1000
+@@ -178,10 +178,10 @@ CONFIG_PHYSICAL_START=0x200000
+ CONFIG_SECCOMP=y
+ # CONFIG_CC_STACKPROTECTOR is not set
+ # CONFIG_HZ_100 is not set
+-CONFIG_HZ_250=y
++# CONFIG_HZ_250 is not set
+ # CONFIG_HZ_300 is not set
+-# CONFIG_HZ_1000 is not set
+-CONFIG_HZ=250
++CONFIG_HZ_1000=y
++CONFIG_HZ=1000
+ # CONFIG_REORDER is not set
+ CONFIG_K8_NB=y
+ CONFIG_GENERIC_HARDIRQS=y
+Index: linux-2.6.21-ck1/include/linux/jiffies.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/jiffies.h	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/jiffies.h	2007-05-04 12:24:21.000000000 +1000
+@@ -29,6 +29,12 @@
+ # define SHIFT_HZ	9
+ #elif HZ >= 768 && HZ < 1536
+ # define SHIFT_HZ	10
++#elif HZ >= 1536 && HZ < 3072
++# define SHIFT_HZ	11
++#elif HZ >= 3072 && HZ < 6144
++# define SHIFT_HZ	12
++#elif HZ >= 6144 && HZ < 12288
++# define SHIFT_HZ	13
+ #else
+ # error You lose.
+ #endif
+Index: linux-2.6.21-ck1/include/net/inet_timewait_sock.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/net/inet_timewait_sock.h	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/include/net/inet_timewait_sock.h	2007-05-04 12:24:21.000000000 +1000
+@@ -38,8 +38,8 @@ struct inet_hashinfo;
+  * If time > 4sec, it is "slow" path, no recycling is required,
+  * so that we select tick to get range about 4 seconds.
+  */
+-#if HZ <= 16 || HZ > 4096
+-# error Unsupported: HZ <= 16 or HZ > 4096
++#if HZ <= 16 || HZ > 16384
++# error Unsupported: HZ <= 16 or HZ > 16384
+ #elif HZ <= 32
+ # define INET_TWDR_RECYCLE_TICK (5 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
+ #elif HZ <= 64
+@@ -54,8 +54,12 @@ struct inet_hashinfo;
+ # define INET_TWDR_RECYCLE_TICK (10 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
+ #elif HZ <= 2048
+ # define INET_TWDR_RECYCLE_TICK (11 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
+-#else
++#elif HZ <= 4096
+ # define INET_TWDR_RECYCLE_TICK (12 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
++#elif HZ <= 8192
++# define INET_TWDR_RECYCLE_TICK (13 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
++#else
++# define INET_TWDR_RECYCLE_TICK (14 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
+ #endif
+ 
+ /* TIME_WAIT reaping mechanism. */
+Index: linux-2.6.21-ck1/include/net/pkt_sched.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/net/pkt_sched.h	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/include/net/pkt_sched.h	2007-05-04 12:24:21.000000000 +1000
+@@ -78,8 +78,14 @@ typedef long	psched_tdiff_t;
+ #define PSCHED_JSCALE 12
+ #elif HZ >= 384 && HZ < 768
+ #define PSCHED_JSCALE 11
+-#elif HZ >= 768
++#elif HZ >= 768 && HZ < 1536
+ #define PSCHED_JSCALE 10
++#elif HZ >= 1536 && HZ < 3072
++#define PSCHED_JSCALE 9
++#elif HZ >= 3072 && HZ < 6144
++#define PSCHED_JSCALE 8
++#else
++#define PSCHED_JSCALE 7
+ #endif
+ 
+ #define PSCHED_GET_TIME(stamp) ((stamp) = (get_jiffies_64()<<PSCHED_JSCALE))
+Index: linux-2.6.21-ck1/init/calibrate.c
+===================================================================
+--- linux-2.6.21-ck1.orig/init/calibrate.c	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/init/calibrate.c	2007-05-04 12:24:21.000000000 +1000
+@@ -122,12 +122,12 @@ void __devinit calibrate_delay(void)
+ 		printk("Calibrating delay loop (skipped)... "
+ 			"%lu.%02lu BogoMIPS preset\n",
+ 			loops_per_jiffy/(500000/HZ),
+-			(loops_per_jiffy/(5000/HZ)) % 100);
++			(loops_per_jiffy * 10/(50000/HZ)) % 100);
+ 	} else if ((loops_per_jiffy = calibrate_delay_direct()) != 0) {
+ 		printk("Calibrating delay using timer specific routine.. ");
+ 		printk("%lu.%02lu BogoMIPS (lpj=%lu)\n",
+ 			loops_per_jiffy/(500000/HZ),
+-			(loops_per_jiffy/(5000/HZ)) % 100,
++			(loops_per_jiffy * 10/(50000/HZ)) % 100,
+ 			loops_per_jiffy);
+ 	} else {
+ 		loops_per_jiffy = (1<<12);
+@@ -166,7 +166,7 @@ void __devinit calibrate_delay(void)
+ 		/* Round the value and print it */
+ 		printk("%lu.%02lu BogoMIPS (lpj=%lu)\n",
+ 			loops_per_jiffy/(500000/HZ),
+-			(loops_per_jiffy/(5000/HZ)) % 100,
++			(loops_per_jiffy * 10/(50000/HZ)) % 100,
+ 			loops_per_jiffy);
+ 	}
+ 
+Index: linux-2.6.21-ck1/arch/i386/kernel/cpu/proc.c
+===================================================================
+--- linux-2.6.21-ck1.orig/arch/i386/kernel/cpu/proc.c	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/arch/i386/kernel/cpu/proc.c	2007-05-04 12:24:21.000000000 +1000
+@@ -158,7 +158,7 @@ static int show_cpuinfo(struct seq_file 
+ 
+ 	seq_printf(m, "\nbogomips\t: %lu.%02lu\n",
+ 		     c->loops_per_jiffy/(500000/HZ),
+-		     (c->loops_per_jiffy/(5000/HZ)) % 100);
++		     (c->loops_per_jiffy * 10/(50000/HZ)) % 100);
+ 	seq_printf(m, "clflush size\t: %u\n\n", c->x86_clflush_size);
+ 
+ 	return 0;
+Index: linux-2.6.21-ck1/arch/i386/kernel/smpboot.c
+===================================================================
+--- linux-2.6.21-ck1.orig/arch/i386/kernel/smpboot.c	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/arch/i386/kernel/smpboot.c	2007-05-04 12:24:21.000000000 +1000
+@@ -1134,7 +1134,7 @@ static void __init smp_boot_cpus(unsigne
+ 		"Total of %d processors activated (%lu.%02lu BogoMIPS).\n",
+ 		cpucount+1,
+ 		bogosum/(500000/HZ),
+-		(bogosum/(5000/HZ))%100);
++		(bogosum * 10/(50000/HZ))%100);
+ 	
+ 	Dprintk("Before bogocount - setting activated=1.\n");
+ 
+Index: linux-2.6.21-ck1/include/linux/nfsd/stats.h
+===================================================================
+--- linux-2.6.21-ck1.orig/include/linux/nfsd/stats.h	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/include/linux/nfsd/stats.h	2007-05-04 12:24:21.000000000 +1000
+@@ -35,8 +35,8 @@ struct nfsd_stats {
+ 
+ };
+ 
+-/* thread usage wraps very million seconds (approx one fortnight) */
+-#define	NFSD_USAGE_WRAP	(HZ*1000000)
++/* thread usage wraps every one hundred thousand seconds (approx one day) */
++#define	NFSD_USAGE_WRAP	(HZ*100000)
+ 
+ #ifdef __KERNEL__
+ 
+Index: linux-2.6.21-ck1/arch/x86_64/kernel/setup.c
+===================================================================
+--- linux-2.6.21-ck1.orig/arch/x86_64/kernel/setup.c	2007-05-04 12:24:00.000000000 +1000
++++ linux-2.6.21-ck1/arch/x86_64/kernel/setup.c	2007-05-04 12:24:22.000000000 +1000
+@@ -1053,7 +1053,7 @@ static int show_cpuinfo(struct seq_file 
+ 		
+ 	seq_printf(m, "\nbogomips\t: %lu.%02lu\n",
+ 		   c->loops_per_jiffy/(500000/HZ),
+-		   (c->loops_per_jiffy/(5000/HZ)) % 100);
++		   (c->loops_per_jiffy * 10/(50000/HZ)) % 100);
+ 
+ 	if (c->x86_tlbsize > 0) 
+ 		seq_printf(m, "TLB size\t: %d 4K pages\n", c->x86_tlbsize);
diff --git a/pkgs/os-specific/linux/kernel/patch-2.6.22-ck1 b/pkgs/os-specific/linux/kernel/patch-2.6.22-ck1
new file mode 100644
index 00000000000..81fa14e2abe
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/patch-2.6.22-ck1
@@ -0,0 +1,5167 @@
+Index: linux-2.6.22-ck1/include/linux/sched.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/sched.h	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/sched.h	2007-07-10 14:55:21.000000000 +1000
+@@ -34,9 +34,14 @@
+ #define SCHED_FIFO		1
+ #define SCHED_RR		2
+ #define SCHED_BATCH		3
++#define SCHED_ISO		4
++#define SCHED_IDLEPRIO		5
+ 
+ #ifdef __KERNEL__
+ 
++#define SCHED_MAX		SCHED_IDLEPRIO
++#define SCHED_RANGE(policy)	((policy) <= SCHED_MAX)
++
+ struct sched_param {
+ 	int sched_priority;
+ };
+@@ -129,7 +134,7 @@
+ extern unsigned long nr_active(void);
+ extern unsigned long nr_iowait(void);
+ extern unsigned long weighted_cpuload(const int cpu);
+-
++extern int above_background_load(void);
+ 
+ /*
+  * Task state bitmask. NOTE! These bits are also
+@@ -150,8 +155,7 @@
+ #define EXIT_ZOMBIE		16
+ #define EXIT_DEAD		32
+ /* in tsk->state again */
+-#define TASK_NONINTERACTIVE	64
+-#define TASK_DEAD		128
++#define TASK_DEAD		64
+ 
+ #define __set_task_state(tsk, state_value)		\
+ 	do { (tsk)->state = (state_value); } while (0)
+@@ -537,14 +541,19 @@
+ 
+ #define MAX_USER_RT_PRIO	100
+ #define MAX_RT_PRIO		MAX_USER_RT_PRIO
++#define PRIO_RANGE		(40)
++#define ISO_PRIO		(MAX_RT_PRIO - 1)
+ 
+-#define MAX_PRIO		(MAX_RT_PRIO + 40)
++#define MAX_PRIO		(MAX_RT_PRIO + PRIO_RANGE)
+ 
+-#define rt_prio(prio)		unlikely((prio) < MAX_RT_PRIO)
++#define rt_prio(prio)		unlikely((prio) < ISO_PRIO)
+ #define rt_task(p)		rt_prio((p)->prio)
+ #define batch_task(p)		(unlikely((p)->policy == SCHED_BATCH))
+-#define is_rt_policy(p)		((p) != SCHED_NORMAL && (p) != SCHED_BATCH)
++#define is_rt_policy(policy)	((policy) == SCHED_FIFO || \
++					(policy) == SCHED_RR)
+ #define has_rt_policy(p)	unlikely(is_rt_policy((p)->policy))
++#define iso_task(p)		unlikely((p)->policy == SCHED_ISO)
++#define idleprio_task(p)	unlikely((p)->policy == SCHED_IDLEPRIO)
+ 
+ /*
+  * Some day this will be a full-fledged user tracking system..
+@@ -809,13 +818,6 @@
+ struct pipe_inode_info;
+ struct uts_namespace;
+ 
+-enum sleep_type {
+-	SLEEP_NORMAL,
+-	SLEEP_NONINTERACTIVE,
+-	SLEEP_INTERACTIVE,
+-	SLEEP_INTERRUPTED,
+-};
+-
+ struct prio_array;
+ 
+ struct task_struct {
+@@ -835,20 +837,33 @@
+ 	int load_weight;	/* for niceness load balancing purposes */
+ 	int prio, static_prio, normal_prio;
+ 	struct list_head run_list;
++	/*
++	 * This bitmap shows what priorities this task has received quota
++	 * from for this major priority rotation on its current runqueue.
++	 */
++	DECLARE_BITMAP(bitmap, PRIO_RANGE + 1);
+ 	struct prio_array *array;
++	/* Which major runqueue rotation did this task run */
++	unsigned long rotation;
+ 
+ 	unsigned short ioprio;
+ #ifdef CONFIG_BLK_DEV_IO_TRACE
+ 	unsigned int btrace_seq;
+ #endif
+-	unsigned long sleep_avg;
+ 	unsigned long long timestamp, last_ran;
+ 	unsigned long long sched_time; /* sched_clock time spent running */
+-	enum sleep_type sleep_type;
+ 
+ 	unsigned int policy;
+ 	cpumask_t cpus_allowed;
+-	unsigned int time_slice, first_time_slice;
++	/*
++	 * How much this task is entitled to run at the current priority
++	 * before being requeued at a lower priority.
++	 */
++	int time_slice;
++	/* Is this the very first time_slice this task has ever run. */
++	unsigned int first_time_slice;
++	/* How much this task receives at each priority level */
++	int quota;
+ 
+ #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
+ 	struct sched_info sched_info;
+@@ -1013,6 +1028,7 @@
+ 	struct held_lock held_locks[MAX_LOCK_DEPTH];
+ 	unsigned int lockdep_recursion;
+ #endif
++	unsigned long mutexes_held;
+ 
+ /* journalling filesystem info */
+ 	void *journal_info;
+@@ -1181,9 +1197,11 @@
+ #define PF_SWAPWRITE	0x00800000	/* Allowed to write to swap */
+ #define PF_SPREAD_PAGE	0x01000000	/* Spread page cache over cpuset */
+ #define PF_SPREAD_SLAB	0x02000000	/* Spread some slab caches over cpuset */
++#define PF_ISOREF	0x04000000	/* SCHED_ISO task has used up quota */
+ #define PF_MEMPOLICY	0x10000000	/* Non-default NUMA mempolicy */
+ #define PF_MUTEX_TESTER	0x20000000	/* Thread belongs to the rt mutex tester */
+ #define PF_FREEZER_SKIP	0x40000000	/* Freezer should not count it as freezeable */
++#define PF_NONSLEEP	0x80000000	/* Waiting on in-kernel activity */
+ 
+ /*
+  * Only the _current_ task can read/write to tsk->flags, but other
+@@ -1253,7 +1271,7 @@
+ #endif
+ 
+ extern void set_user_nice(struct task_struct *p, long nice);
+-extern int task_prio(const struct task_struct *p);
++extern int task_prio(struct task_struct *p);
+ extern int task_nice(const struct task_struct *p);
+ extern int can_nice(const struct task_struct *p, const int nice);
+ extern int task_curr(const struct task_struct *p);
+Index: linux-2.6.22-ck1/kernel/sched.c
+===================================================================
+--- linux-2.6.22-ck1.orig/kernel/sched.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/kernel/sched.c	2007-07-10 14:55:24.000000000 +1000
+@@ -16,6 +16,7 @@
+  *		by Davide Libenzi, preemptible kernel bits by Robert Love.
+  *  2003-09-03	Interactivity tuning by Con Kolivas.
+  *  2004-04-02	Scheduler domains code by Nick Piggin
++ *  2007-03-02	Staircase deadline scheduling policy by Con Kolivas
+  */
+ 
+ #include <linux/mm.h>
+@@ -53,8 +54,9 @@
+ #include <linux/kprobes.h>
+ #include <linux/delayacct.h>
+ #include <linux/reciprocal_div.h>
+-
++#include <linux/log2.h>
+ #include <asm/tlb.h>
++
+ #include <asm/unistd.h>
+ 
+ /*
+@@ -84,147 +86,85 @@
+ #define USER_PRIO(p)		((p)-MAX_RT_PRIO)
+ #define TASK_USER_PRIO(p)	USER_PRIO((p)->static_prio)
+ #define MAX_USER_PRIO		(USER_PRIO(MAX_PRIO))
++#define SCHED_PRIO(p)		((p)+MAX_RT_PRIO)
+ 
+-/*
+- * Some helpers for converting nanosecond timing to jiffy resolution
+- */
+-#define NS_TO_JIFFIES(TIME)	((TIME) / (1000000000 / HZ))
++/* Some helpers for converting to/from various scales.*/
+ #define JIFFIES_TO_NS(TIME)	((TIME) * (1000000000 / HZ))
+-
+-/*
+- * These are the 'tuning knobs' of the scheduler:
+- *
+- * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
+- * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
+- * Timeslices get refilled after they expire.
+- */
+-#define MIN_TIMESLICE		max(5 * HZ / 1000, 1)
+-#define DEF_TIMESLICE		(100 * HZ / 1000)
+-#define ON_RUNQUEUE_WEIGHT	 30
+-#define CHILD_PENALTY		 95
+-#define PARENT_PENALTY		100
+-#define EXIT_WEIGHT		  3
+-#define PRIO_BONUS_RATIO	 25
+-#define MAX_BONUS		(MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
+-#define INTERACTIVE_DELTA	  2
+-#define MAX_SLEEP_AVG		(DEF_TIMESLICE * MAX_BONUS)
+-#define STARVATION_LIMIT	(MAX_SLEEP_AVG)
+-#define NS_MAX_SLEEP_AVG	(JIFFIES_TO_NS(MAX_SLEEP_AVG))
+-
+-/*
+- * If a task is 'interactive' then we reinsert it in the active
+- * array after it has expired its current timeslice. (it will not
+- * continue to run immediately, it will still roundrobin with
+- * other interactive tasks.)
+- *
+- * This part scales the interactivity limit depending on niceness.
+- *
+- * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
+- * Here are a few examples of different nice levels:
+- *
+- *  TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
+- *  TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
+- *  TASK_INTERACTIVE(  0): [1,1,1,1,0,0,0,0,0,0,0]
+- *  TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
+- *  TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
+- *
+- * (the X axis represents the possible -5 ... 0 ... +5 dynamic
+- *  priority range a task can explore, a value of '1' means the
+- *  task is rated interactive.)
+- *
+- * Ie. nice +19 tasks can never get 'interactive' enough to be
+- * reinserted into the active array. And only heavily CPU-hog nice -20
+- * tasks will be expired. Default nice 0 tasks are somewhere between,
+- * it takes some effort for them to get interactive, but it's not
+- * too hard.
+- */
+-
+-#define CURRENT_BONUS(p) \
+-	(NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
+-		MAX_SLEEP_AVG)
+-
+-#define GRANULARITY	(10 * HZ / 1000 ? : 1)
+-
+-#ifdef CONFIG_SMP
+-#define TIMESLICE_GRANULARITY(p)	(GRANULARITY * \
+-		(1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
+-			num_online_cpus())
+-#else
+-#define TIMESLICE_GRANULARITY(p)	(GRANULARITY * \
+-		(1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
+-#endif
+-
+-#define SCALE(v1,v1_max,v2_max) \
+-	(v1) * (v2_max) / (v1_max)
+-
+-#define DELTA(p) \
+-	(SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
+-		INTERACTIVE_DELTA)
+-
+-#define TASK_INTERACTIVE(p) \
+-	((p)->prio <= (p)->static_prio - DELTA(p))
+-
+-#define INTERACTIVE_SLEEP(p) \
+-	(JIFFIES_TO_NS(MAX_SLEEP_AVG * \
+-		(MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
+-
+-#define TASK_PREEMPTS_CURR(p, rq) \
+-	((p)->prio < (rq)->curr->prio)
+-
+-#define SCALE_PRIO(x, prio) \
+-	max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
+-
+-static unsigned int static_prio_timeslice(int static_prio)
+-{
+-	if (static_prio < NICE_TO_PRIO(0))
+-		return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
+-	else
+-		return SCALE_PRIO(DEF_TIMESLICE, static_prio);
+-}
+-
+-#ifdef CONFIG_SMP
+-/*
+- * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
+- * Since cpu_power is a 'constant', we can use a reciprocal divide.
++#define MS_TO_NS(TIME)		((TIME) * 1000000)
++#define MS_TO_US(TIME)		((TIME) * 1000)
++#define US_TO_MS(TIME)		((TIME) / 1000)
++
++#define TASK_PREEMPTS_CURR(p, curr)	((p)->prio < (curr)->prio)
++
++/*
++ * This is the time all tasks within the same priority round robin.
++ * Value is in ms and set to a minimum of 10ms. Scales with number of cpus.
++ * Tunable via /proc interface.
++ */
++int rr_interval __read_mostly = 6;
++int sched_interactive __read_mostly = 1;
++
++/*
++ * sched_iso_cpu - sysctl which determines the cpu percentage SCHED_ISO tasks
++ * are allowed to run (over ISO_PERIOD seconds) as real time tasks.
++ * sched_iso_period - sysctl which determines the number of seconds over
++ * which cpu usage of SCHED_ISO tasks is averaged to determine if they are
++ * exceeding their allowable bandwidth.
++*/
++int sched_iso_cpu __read_mostly = 80;
++int sched_iso_period __read_mostly = 5;
++
++#define ISO_PERIOD	((sched_iso_period * HZ) + 1)
++
++/*
++ * This contains a bitmap for each dynamic priority level with empty slots
++ * for the valid priorities each different nice level can have. It allows
++ * us to stagger the slots where differing priorities run in a way that
++ * keeps latency differences between different nice levels at a minimum.
++ * The purpose of a pre-generated matrix is for rapid lookup of next slot in
++ * O(1) time without having to recalculate every time priority gets demoted.
++ * All nice levels use priority slot 39 as this allows less niced tasks to
++ * get all priority slots better than that before expiration is forced.
++ * ie, where 0 means a slot for that priority, priority running from left to
++ * right is from prio 0 to prio 39:
++ * nice -20 0000000000000000000000000000000000000000
++ * nice -10 1000100010001000100010001000100010010000
++ * nice   0 1010101010101010101010101010101010101010
++ * nice   5 1011010110110101101101011011010110110110
++ * nice  10 1110111011101110111011101110111011101110
++ * nice  15 1111111011111110111111101111111011111110
++ * nice  19 1111111111111111111111111111111111111110
+  */
+-static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
+-{
+-	return reciprocal_divide(load, sg->reciprocal_cpu_power);
+-}
++static unsigned long prio_matrix[PRIO_RANGE][BITS_TO_LONGS(PRIO_RANGE)]
++				 __read_mostly;
+ 
+-/*
+- * Each time a sched group cpu_power is changed,
+- * we must compute its reciprocal value
+- */
+-static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
+-{
+-	sg->__cpu_power += val;
+-	sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
+-}
+-#endif
++struct rq;
+ 
+ /*
+- * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
+- * to time slice values: [800ms ... 100ms ... 5ms]
+- *
+- * The higher a thread's priority, the bigger timeslices
+- * it gets during one round of execution. But even the lowest
+- * priority thread gets MIN_TIMESLICE worth of execution time.
++ * These are the runqueue data structures:
+  */
++struct prio_array {
++	/* Tasks queued at each priority */
++	struct list_head queue[MAX_PRIO + 1];
+ 
+-static inline unsigned int task_timeslice(struct task_struct *p)
+-{
+-	return static_prio_timeslice(p->static_prio);
+-}
++	/*
++	 * The bitmap of priorities queued for this array. While the expired
++	 * array will never have realtime tasks on it, it is simpler to have
++	 * equal sized bitmaps for a cheap array swap. Include 1 bit for
++	 * delimiter.
++	 */
++	DECLARE_BITMAP(prio_bitmap, MAX_PRIO + 1);
+ 
+-/*
+- * These are the runqueue data structures:
+- */
++	/*
++	 * The best static priority (of the dynamic priority tasks) queued
++	 * this array.
++	 */
++	int best_static_prio;
+ 
+-struct prio_array {
+-	unsigned int nr_active;
+-	DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
+-	struct list_head queue[MAX_PRIO];
++#ifdef CONFIG_SMP
++	/* For convenience looks back at rq */
++	struct rq *rq;
++#endif
+ };
+ 
+ /*
+@@ -260,14 +200,28 @@
+ 	 */
+ 	unsigned long nr_uninterruptible;
+ 
+-	unsigned long expired_timestamp;
+ 	/* Cached timestamp set by update_cpu_clock() */
+ 	unsigned long long most_recent_timestamp;
+ 	struct task_struct *curr, *idle;
+ 	unsigned long next_balance;
+ 	struct mm_struct *prev_mm;
+-	struct prio_array *active, *expired, arrays[2];
+-	int best_expired_prio;
++
++	struct prio_array *active, *expired, *idleprio, arrays[2];
++	unsigned long *dyn_bitmap, *exp_bitmap;
++
++	/*
++	 * The current dynamic priority level this runqueue is at per static
++	 * priority level.
++	 */
++	int prio_level[PRIO_RANGE];
++
++	/* How many times we have rotated the priority queue */
++	unsigned long prio_rotation;
++	unsigned long iso_ticks;
++	unsigned short iso_refractory;
++
++	/* Number of idleprio tasks running */
++	unsigned long nr_idleprio;
+ 	atomic_t nr_iowait;
+ 
+ #ifdef CONFIG_SMP
+@@ -606,12 +560,9 @@
+ #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
+ /*
+  * Called when a process is dequeued from the active array and given
+- * the cpu.  We should note that with the exception of interactive
+- * tasks, the expired queue will become the active queue after the active
+- * queue is empty, without explicitly dequeuing and requeuing tasks in the
+- * expired queue.  (Interactive tasks may be requeued directly to the
+- * active queue, thus delaying tasks in the expired queue from running;
+- * see scheduler_tick()).
++ * the cpu.  We should note that the expired queue will become the active
++ * queue after the active queue is empty, without explicitly dequeuing and
++ * requeuing tasks in the expired queue.
+  *
+  * This function is only called from sched_info_arrive(), rather than
+  * dequeue_task(). Even though a task may be queued and dequeued multiple
+@@ -709,71 +660,304 @@
+ #define sched_info_switch(t, next)	do { } while (0)
+ #endif /* CONFIG_SCHEDSTATS || CONFIG_TASK_DELAY_ACCT */
+ 
++static int idleprio_suitable(struct task_struct *p)
++{
++	return (!p->mutexes_held && !freezing(p) && !signal_pending(p) &&
++		!(p->flags & (PF_NONSLEEP | PF_EXITING)));
++}
++
++static int idleprio(const struct task_struct *p)
++{
++	return (p->prio == MAX_PRIO);
++}
++
++static inline int task_queued(struct task_struct *task)
++{
++	return !list_empty(&task->run_list);
++}
++
++static inline void set_dynamic_bit(struct task_struct *p, struct rq *rq)
++{
++	__set_bit(p->prio, p->array->prio_bitmap);
++}
++
+ /*
+- * Adding/removing a task to/from a priority array:
++ * Removing from a runqueue.
+  */
+-static void dequeue_task(struct task_struct *p, struct prio_array *array)
++static void dequeue_task(struct task_struct *p, struct rq *rq)
+ {
+-	array->nr_active--;
+-	list_del(&p->run_list);
+-	if (list_empty(array->queue + p->prio))
+-		__clear_bit(p->prio, array->bitmap);
++	list_del_init(&p->run_list);
++	if (idleprio_task(p) && idleprio(p))
++		rq->nr_idleprio--;
++	else if (list_empty(p->array->queue + p->prio))
++		__clear_bit(p->prio, p->array->prio_bitmap);
+ }
+ 
+-static void enqueue_task(struct task_struct *p, struct prio_array *array)
++static void reset_first_time_slice(struct task_struct *p)
+ {
+-	sched_info_queued(p);
+-	list_add_tail(&p->run_list, array->queue + p->prio);
+-	__set_bit(p->prio, array->bitmap);
+-	array->nr_active++;
++	if (unlikely(p->first_time_slice))
++		p->first_time_slice = 0;
++}
++
++/*
++ * The task is being queued on a fresh array so it has its entitlement
++ * bitmap cleared.
++ */
++static void task_new_array(struct task_struct *p, struct rq *rq,
++			   struct prio_array *array)
++{
++	bitmap_zero(p->bitmap, PRIO_RANGE);
++	p->rotation = rq->prio_rotation;
++	p->time_slice = p->quota;
+ 	p->array = array;
++	reset_first_time_slice(p);
++}
++
++/* Find the first slot from the relevant prio_matrix entry */
++static int first_prio_slot(struct task_struct *p)
++{
++	if (unlikely(p->policy == SCHED_BATCH))
++		return p->static_prio;
++	return SCHED_PRIO(find_first_zero_bit(
++		prio_matrix[USER_PRIO(p->static_prio)], PRIO_RANGE));
+ }
+ 
+ /*
+- * Put task to the end of the run list without the overhead of dequeue
+- * followed by enqueue.
++ * In sched_interactive mode priority allocation occurs per process per rq
++ * array swap. In !sched_interactive mode all waking tasks must obey the
++ * current prio level of all other tasks running per array swap.
+  */
+-static void requeue_task(struct task_struct *p, struct prio_array *array)
++static int minprio(struct rq *rq, int uprio)
+ {
+-	list_move_tail(&p->run_list, array->queue + p->prio);
++	if (sched_interactive)
++		return MAX_RT_PRIO;
++	return rq->prio_level[uprio];
+ }
+ 
+-static inline void
+-enqueue_task_head(struct task_struct *p, struct prio_array *array)
++/*
++ * Find the first unused slot by this task that is also in its prio_matrix
++ * level. SCHED_BATCH tasks do not use the priority matrix. They only take
++ * priority slots from their static_prio and above.
++ */
++static int next_entitled_slot(struct task_struct *p, struct rq *rq)
+ {
+-	list_add(&p->run_list, array->queue + p->prio);
+-	__set_bit(p->prio, array->bitmap);
+-	array->nr_active++;
+-	p->array = array;
++	int search_prio = MAX_RT_PRIO, uprio = USER_PRIO(p->static_prio);
++	struct prio_array *array = rq->active;
++	DECLARE_BITMAP(tmp, PRIO_RANGE);
++
++	/*
++	 * Go straight to expiration if there are higher priority tasks
++	 * already expired.
++	 */
++	if (p->static_prio > rq->expired->best_static_prio)
++		return MAX_PRIO;
++	if (!rq->prio_level[uprio])
++		rq->prio_level[uprio] = MAX_RT_PRIO;
++	/*
++	 * Only priorities equal to the prio_level and above for their
++	 * static_prio are acceptable, and only if it's not better than
++	 * a queued better static_prio's prio_level.
++	 */
++	if (p->static_prio < array->best_static_prio) {
++		if (likely(p->policy != SCHED_BATCH))
++			array->best_static_prio = p->static_prio;
++	} else if (p->static_prio == array->best_static_prio) {
++		search_prio = minprio(rq, uprio);
++	} else {
++		int i;
++
++		search_prio = minprio(rq, uprio);
++		/* A bound O(n) function, worst case n is 40 */
++		for (i = array->best_static_prio; i <= p->static_prio ; i++) {
++			if (!rq->prio_level[USER_PRIO(i)])
++				rq->prio_level[USER_PRIO(i)] = MAX_RT_PRIO;
++			search_prio = max(search_prio,
++				      rq->prio_level[USER_PRIO(i)]);
++		}
++	}
++	if (unlikely(p->policy == SCHED_BATCH)) {
++		search_prio = max(search_prio, p->static_prio);
++		return SCHED_PRIO(find_next_zero_bit(p->bitmap, PRIO_RANGE,
++				  USER_PRIO(search_prio)));
++	}
++	bitmap_or(tmp, p->bitmap, prio_matrix[uprio], PRIO_RANGE);
++	return SCHED_PRIO(find_next_zero_bit(tmp, PRIO_RANGE,
++		USER_PRIO(search_prio)));
++}
++
++static void queue_expired(struct task_struct *p, struct rq *rq)
++{
++	task_new_array(p, rq, rq->expired);
++	p->prio = p->normal_prio = first_prio_slot(p);
++	if (p->static_prio < rq->expired->best_static_prio)
++		rq->expired->best_static_prio = p->static_prio;
++	reset_first_time_slice(p);
+ }
+ 
++#ifdef CONFIG_SMP
+ /*
+- * __normal_prio - return the priority that is based on the static
+- * priority but is modified by bonuses/penalties.
+- *
+- * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
+- * into the -5 ... 0 ... +5 bonus/penalty range.
+- *
+- * We use 25% of the full 0...39 priority range so that:
+- *
+- * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
+- * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
+- *
+- * Both properties are important to certain workloads.
++ * If we're waking up a task that was previously on a different runqueue,
++ * update its data appropriately. Note we may be reading data from src_rq->
++ * outside of lock, but the occasional inaccurate result should be harmless.
+  */
++ static void update_if_moved(struct task_struct *p, struct rq *rq)
++{
++	struct rq *src_rq = p->array->rq;
++
++	if (src_rq == rq)
++		return;
++	/*
++	 * Only need to set p->array when p->rotation == rq->prio_rotation as
++	 * they will be set in recalc_task_prio when != rq->prio_rotation.
++	 */
++	if (p->rotation == src_rq->prio_rotation) {
++		p->rotation = rq->prio_rotation;
++		if (p->array == src_rq->expired)
++			p->array = rq->expired;
++		else
++			p->array = rq->active;
++	} else
++		p->rotation = 0;
++}
++#else
++static inline void update_if_moved(struct task_struct *p, struct rq *rq)
++{
++}
++#endif
+ 
+-static inline int __normal_prio(struct task_struct *p)
++static inline int isoprio_suitable(struct task_struct *p)
+ {
+-	int bonus, prio;
++	return !(p->flags & PF_ISOREF);
++}
+ 
+-	bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
++static int task_timeslice(struct task_struct *p);
+ 
+-	prio = p->static_prio - bonus;
+-	if (prio < MAX_RT_PRIO)
+-		prio = MAX_RT_PRIO;
+-	if (prio > MAX_PRIO-1)
+-		prio = MAX_PRIO-1;
+-	return prio;
++/*
++ * recalc_task_prio determines what priority a non rt_task will be
++ * queued at. If the task has already been running during this runqueue's
++ * major rotation (rq->prio_rotation) then it continues at the same
++ * priority if it has tick entitlement left. If it does not have entitlement
++ * left, it finds the next priority slot according to its nice value that it
++ * has not extracted quota from. If it has not run during this major
++ * rotation, it starts at the next_entitled_slot and has its bitmap quota
++ * cleared. If it does not have any slots left it has all its slots reset and
++ * is queued on the expired at its first_prio_slot.
++ */
++static void recalc_task_prio(struct task_struct *p, struct rq *rq)
++{
++	struct prio_array *array = rq->active;
++	int queue_prio;
++
++	if (iso_task(p)) {
++		if (isoprio_suitable(p)) {
++			/*
++			 * If SCHED_ISO tasks have not used up their real time
++			 * quota they have run just better than highest
++			 * SCHED_NORMAL priority. Otherwise they run as
++			 * SCHED_NORMAL.
++			 */
++			p->prio = p->normal_prio = ISO_PRIO;
++			p->array = rq->active;
++			if (p->time_slice <= 0)
++				p->time_slice = p->quota;
++			return;
++		} else if (p->prio == ISO_PRIO) {
++			/* Just about to be demoted to SCHED_NORMAL */
++			p->time_slice = 0;
++		}
++	} else if (idleprio_task(p)) {
++		if (idleprio_suitable(p)) {
++			/*
++			 * If suitable idleprio_tasks are queued at MAX_PRIO
++			 * only on the idleprio array. Their time_slice is
++			 * their full task_timeslice as they cooperatively
++			 * multitask.
++			 */
++			p->prio = p->normal_prio = MAX_PRIO;
++			p->array = rq->idleprio;
++			if (p->time_slice <= 0)
++				p->time_slice = task_timeslice(p);
++			return;
++		}
++		/*
++		 * If unsuitable idleprio_tasks are queued equivalent to
++		 * nice 19 tasks on the expired array.
++		 */
++		p->flags &= ~PF_NONSLEEP;
++		p->prio = p->normal_prio = MAX_PRIO - 1;
++		p->array = rq->expired;
++		if (p->time_slice <= 0 || p->time_slice > p->quota)
++			p->time_slice = p->quota;
++		return;
++	}
++
++	update_if_moved(p, rq);
++	if (p->rotation == rq->prio_rotation) {
++		if (p->array == array) {
++			if (p->time_slice > 0)
++				return;
++			p->time_slice = p->quota;
++		} else if (p->array == rq->expired) {
++			queue_expired(p, rq);
++			return;
++		} else
++			task_new_array(p, rq, array);
++	} else
++		task_new_array(p, rq, array);
++
++	queue_prio = next_entitled_slot(p, rq);
++	if (queue_prio >= MAX_PRIO) {
++		queue_expired(p, rq);
++		return;
++	}
++	p->prio = p->normal_prio = queue_prio;
++	__set_bit(USER_PRIO(p->prio), p->bitmap);
++}
++
++/*
++ * Adding to a runqueue. The dynamic priority queue that it is added to is
++ * determined by recalc_task_prio() above.
++ */
++static inline void __enqueue_task(struct task_struct *p, struct rq *rq)
++{
++	if (rt_task(p))
++		p->array = rq->active;
++	else
++		recalc_task_prio(p, rq);
++
++	if (idleprio_task(p) && idleprio(p))
++		rq->nr_idleprio++;
++	sched_info_queued(p);
++	set_dynamic_bit(p, rq);
++}
++
++static void enqueue_task(struct task_struct *p, struct rq *rq)
++{
++	__enqueue_task(p, rq);
++	list_add_tail(&p->run_list, p->array->queue + p->prio);
++}
++
++static inline void enqueue_task_head(struct task_struct *p, struct rq *rq)
++{
++	__enqueue_task(p, rq);
++	list_add(&p->run_list, p->array->queue + p->prio);
++}
++
++/*
++ * requeue_task is only called when p->static_prio does not change. p->prio
++ * can change with dynamic tasks.
++ */
++static void requeue_task(struct task_struct *p, struct rq *rq,
++			 struct prio_array *old_array, int old_prio)
++{
++	if (p->array == rq->expired)
++		queue_expired(p, rq);
++	list_move_tail(&p->run_list, p->array->queue + p->prio);
++	if (!rt_task(p)) {
++		if (list_empty(old_array->queue + old_prio))
++			__clear_bit(old_prio, old_array->prio_bitmap);
++		set_dynamic_bit(p, rq);
++	}
+ }
+ 
+ /*
+@@ -786,20 +970,29 @@
+  */
+ 
+ /*
+- * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
+- * If static_prio_timeslice() is ever changed to break this assumption then
+- * this code will need modification
+- */
+-#define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
+-#define LOAD_WEIGHT(lp) \
+-	(((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
+-#define PRIO_TO_LOAD_WEIGHT(prio) \
+-	LOAD_WEIGHT(static_prio_timeslice(prio))
+-#define RTPRIO_TO_LOAD_WEIGHT(rp) \
+-	(PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
++ * task_timeslice - the total duration a task can run during one major
++ * rotation. Returns value in milliseconds as the smallest value can be 1.
++ */
++static int task_timeslice(struct task_struct *p)
++{
++	int slice = p->quota;	/* quota is in us */
++
++	if (!rt_task(p))
++		slice += (PRIO_RANGE - 1 - TASK_USER_PRIO(p)) * slice;
++	return US_TO_MS(slice);
++}
++
++/*
++ * The load weight is basically the task_timeslice in ms. Realtime tasks are
++ * special cased to be proportionately larger than nice -20 by their
++ * rt_priority. The weight for rt tasks can only be arbitrary at best.
++ */
++#define RTPRIO_TO_LOAD_WEIGHT(rp)	(rr_interval * 20 * (40 + rp))
+ 
+ static void set_load_weight(struct task_struct *p)
+ {
++	int load_weight;
++
+ 	if (has_rt_policy(p)) {
+ #ifdef CONFIG_SMP
+ 		if (p == task_rq(p)->migration_thread)
+@@ -808,12 +1001,19 @@
+ 			 * Giving its load any weight will skew balancing
+ 			 * adversely.
+ 			 */
+-			p->load_weight = 0;
++			load_weight = 0;
+ 		else
+ #endif
+-			p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
++			load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
+ 	} else
+-		p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
++		load_weight = task_timeslice(p);
++	/*
++	 * idleprio tasks have much lower weight than SCHED_NORMAL tasks but
++	 * still need to be weighted to allow balancing to occur.
++	 */
++	if (likely(!idleprio_task(p)))
++		load_weight *= PRIO_RANGE;
++	p->load_weight = load_weight;
+ }
+ 
+ static inline void
+@@ -841,28 +1041,38 @@
+ }
+ 
+ /*
+- * Calculate the expected normal priority: i.e. priority
+- * without taking RT-inheritance into account. Might be
+- * boosted by interactivity modifiers. Changes upon fork,
+- * setprio syscalls, and whenever the interactivity
+- * estimator recalculates.
++ * __activate_task - move a task to the runqueue.
+  */
+-static inline int normal_prio(struct task_struct *p)
++static inline void __activate_task(struct task_struct *p, struct rq *rq)
+ {
+-	int prio;
++	enqueue_task(p, rq);
++	inc_nr_running(p, rq);
++}
+ 
++/*
++ * __activate_idle_task - move idle task to the _front_ of runqueue.
++ */
++static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
++{
++	enqueue_task_head(p, rq);
++	inc_nr_running(p, rq);
++}
++
++static inline int normal_prio(struct task_struct *p)
++{
+ 	if (has_rt_policy(p))
+-		prio = MAX_RT_PRIO-1 - p->rt_priority;
++		return MAX_RT_PRIO-1 - p->rt_priority;
++	/* Other tasks all have normal_prio set in recalc_task_prio */
++	if (likely(p->prio >= MAX_RT_PRIO && p->prio < MAX_PRIO))
++		return p->prio;
+ 	else
+-		prio = __normal_prio(p);
+-	return prio;
++		return p->static_prio;
+ }
+ 
+ /*
+  * Calculate the current priority, i.e. the priority
+  * taken into account by the scheduler. This value might
+- * be boosted by RT tasks, or might be boosted by
+- * interactivity modifiers. Will be RT if the task got
++ * be boosted by RT tasks as it will be RT if the task got
+  * RT-boosted. If not then it returns p->normal_prio.
+  */
+ static int effective_prio(struct task_struct *p)
+@@ -878,112 +1088,70 @@
+ 	return p->prio;
+ }
+ 
+-/*
+- * __activate_task - move a task to the runqueue.
+- */
+-static void __activate_task(struct task_struct *p, struct rq *rq)
++static inline unsigned int nice_quota_ms(int nice)
+ {
+-	struct prio_array *target = rq->active;
++	unsigned int rr = rr_interval;
+ 
+-	if (batch_task(p))
+-		target = rq->expired;
+-	enqueue_task(p, target);
+-	inc_nr_running(p, rq);
++	if (nice < -6) {
++		rr *= nice * nice;
++		rr /= 40;
++	} else if (nice > 0)
++		rr = rr / 2 ? : 1;
++	return rr;
+ }
+ 
++#define DEFAULT_WEIGHT	(nice_quota_ms(0) * 20 * PRIO_RANGE)
++
+ /*
+- * __activate_idle_task - move idle task to the _front_ of runqueue.
++ * A runqueue laden with a single nice 0 task scores a weighted_cpuload of
++ * SCHED_LOAD_SCALE. This function returns 1 if any cpu is laden with a
++ * task of nice 0 or enough lower priority tasks to bring up the
++ * weighted_cpuload
+  */
+-static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
++int above_background_load(void)
+ {
+-	enqueue_task_head(p, rq->active);
+-	inc_nr_running(p, rq);
++	unsigned long cpu;
++
++	for_each_online_cpu(cpu) {
++		if (weighted_cpuload(cpu) >= DEFAULT_WEIGHT)
++			return 1;
++	}
++	return 0;
+ }
+ 
+ /*
+- * Recalculate p->normal_prio and p->prio after having slept,
+- * updating the sleep-average too:
++ * All tasks have quotas based on rr_interval. RT tasks all get rr_interval.
++ * From nice 1 to 19 they are smaller than it only if they are at least one
++ * tick still. Below nice 0 they get progressively larger.
++ * ie nice -6..0 = rr_interval. nice -10 = 2.5 * rr_interval
++ * nice -20 = 10 * rr_interval. nice 1-19 = rr_interval / 2.
++ * Value returned is in microseconds.
+  */
+-static int recalc_task_prio(struct task_struct *p, unsigned long long now)
++static inline unsigned int rr_quota(struct task_struct *p)
+ {
+-	/* Caller must always ensure 'now >= p->timestamp' */
+-	unsigned long sleep_time = now - p->timestamp;
++	unsigned int quota;
+ 
+-	if (batch_task(p))
+-		sleep_time = 0;
+-
+-	if (likely(sleep_time > 0)) {
+-		/*
+-		 * This ceiling is set to the lowest priority that would allow
+-		 * a task to be reinserted into the active array on timeslice
+-		 * completion.
+-		 */
+-		unsigned long ceiling = INTERACTIVE_SLEEP(p);
+-
+-		if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
+-			/*
+-			 * Prevents user tasks from achieving best priority
+-			 * with one single large enough sleep.
+-			 */
+-			p->sleep_avg = ceiling;
+-			/*
+-			 * Using INTERACTIVE_SLEEP() as a ceiling places a
+-			 * nice(0) task 1ms sleep away from promotion, and
+-			 * gives it 700ms to round-robin with no chance of
+-			 * being demoted.  This is more than generous, so
+-			 * mark this sleep as non-interactive to prevent the
+-			 * on-runqueue bonus logic from intervening should
+-			 * this task not receive cpu immediately.
+-			 */
+-			p->sleep_type = SLEEP_NONINTERACTIVE;
+-		} else {
+-			/*
+-			 * Tasks waking from uninterruptible sleep are
+-			 * limited in their sleep_avg rise as they
+-			 * are likely to be waiting on I/O
+-			 */
+-			if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
+-				if (p->sleep_avg >= ceiling)
+-					sleep_time = 0;
+-				else if (p->sleep_avg + sleep_time >=
+-					 ceiling) {
+-						p->sleep_avg = ceiling;
+-						sleep_time = 0;
+-				}
+-			}
+-
+-			/*
+-			 * This code gives a bonus to interactive tasks.
+-			 *
+-			 * The boost works by updating the 'average sleep time'
+-			 * value here, based on ->timestamp. The more time a
+-			 * task spends sleeping, the higher the average gets -
+-			 * and the higher the priority boost gets as well.
+-			 */
+-			p->sleep_avg += sleep_time;
+-
+-		}
+-		if (p->sleep_avg > NS_MAX_SLEEP_AVG)
+-			p->sleep_avg = NS_MAX_SLEEP_AVG;
+-	}
++	if (rt_task(p))
++		quota = rr_interval;
++	else
++		quota = nice_quota_ms(TASK_NICE(p));
++	return MS_TO_US(quota);
++}
+ 
+-	return effective_prio(p);
++/* Every time we set the quota we need to set the load weight */
++static void set_quota(struct task_struct *p)
++{
++	p->quota = rr_quota(p);
++	set_load_weight(p);
+ }
+ 
+ /*
+  * activate_task - move a task to the runqueue and do priority recalculation
+- *
+- * Update all the scheduling statistics stuff. (sleep average
+- * calculation, priority modifiers, etc.)
+  */
+ static void activate_task(struct task_struct *p, struct rq *rq, int local)
+ {
+-	unsigned long long now;
+-
+-	if (rt_task(p))
+-		goto out;
++	unsigned long long now = sched_clock();
+ 
+-	now = sched_clock();
+ #ifdef CONFIG_SMP
+ 	if (!local) {
+ 		/* Compensate for drifting sched_clock */
+@@ -1004,32 +1172,9 @@
+ 				     (now - p->timestamp) >> 20);
+ 	}
+ 
+-	p->prio = recalc_task_prio(p, now);
+-
+-	/*
+-	 * This checks to make sure it's not an uninterruptible task
+-	 * that is now waking up.
+-	 */
+-	if (p->sleep_type == SLEEP_NORMAL) {
+-		/*
+-		 * Tasks which were woken up by interrupts (ie. hw events)
+-		 * are most likely of interactive nature. So we give them
+-		 * the credit of extending their sleep time to the period
+-		 * of time they spend on the runqueue, waiting for execution
+-		 * on a CPU, first time around:
+-		 */
+-		if (in_interrupt())
+-			p->sleep_type = SLEEP_INTERRUPTED;
+-		else {
+-			/*
+-			 * Normal first-time wakeups get a credit too for
+-			 * on-runqueue time, but it will be weighted down:
+-			 */
+-			p->sleep_type = SLEEP_INTERACTIVE;
+-		}
+-	}
++	set_quota(p);
++	p->prio = effective_prio(p);
+ 	p->timestamp = now;
+-out:
+ 	__activate_task(p, rq);
+ }
+ 
+@@ -1039,8 +1184,7 @@
+ static void deactivate_task(struct task_struct *p, struct rq *rq)
+ {
+ 	dec_nr_running(p, rq);
+-	dequeue_task(p, p->array);
+-	p->array = NULL;
++	dequeue_task(p, rq);
+ }
+ 
+ /*
+@@ -1133,7 +1277,7 @@
+ 	 * If the task is not on a runqueue (and not running), then
+ 	 * it is sufficient to simply update the task's cpu field.
+ 	 */
+-	if (!p->array && !task_running(rq, p)) {
++	if (!task_queued(p) && !task_running(rq, p)) {
+ 		set_task_cpu(p, dest_cpu);
+ 		return 0;
+ 	}
+@@ -1159,7 +1303,6 @@
+ {
+ 	unsigned long flags;
+ 	struct rq *rq;
+-	struct prio_array *array;
+ 	int running;
+ 
+ repeat:
+@@ -1192,7 +1335,6 @@
+ 	 */
+ 	rq = task_rq_lock(p, &flags);
+ 	running = task_running(rq, p);
+-	array = p->array;
+ 	task_rq_unlock(rq, &flags);
+ 
+ 	/*
+@@ -1215,7 +1357,7 @@
+ 	 * running right now), it's preempted, and we should
+ 	 * yield - it could be a while.
+ 	 */
+-	if (unlikely(array)) {
++	if (unlikely(task_queued(p))) {
+ 		yield();
+ 		goto repeat;
+ 	}
+@@ -1294,6 +1436,25 @@
+ }
+ 
+ /*
++ * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
++ * Since cpu_power is a 'constant', we can use a reciprocal divide.
++ */
++static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
++{
++	return reciprocal_divide(load, sg->reciprocal_cpu_power);
++}
++
++/*
++ * Each time a sched group cpu_power is changed,
++ * we must compute its reciprocal value
++ */
++static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
++{
++	sg->__cpu_power += val;
++	sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
++}
++
++/*
+  * find_idlest_group finds and returns the least busy CPU group within the
+  * domain.
+  */
+@@ -1490,6 +1651,31 @@
+ }
+ #endif
+ 
++/*
++ * We need to have a special definition for an idle runqueue when testing
++ * for preemption on CONFIG_HOTPLUG_CPU as the idle task may be scheduled as
++ * a realtime task in sched_idle_next.
++ */
++#ifdef CONFIG_HOTPLUG_CPU
++#define rq_idle(rq)	((rq)->curr == (rq)->idle && !rt_task((rq)->curr))
++#else
++#define rq_idle(rq)	((rq)->curr == (rq)->idle)
++#endif
++
++static inline int task_preempts_curr(struct task_struct *p, struct rq *rq)
++{
++	struct task_struct *curr = rq->curr;
++
++	return ((p->array == task_rq(p)->active &&
++		TASK_PREEMPTS_CURR(p, curr)) || rq_idle(rq));
++}
++
++static inline void try_preempt(struct task_struct *p, struct rq *rq)
++{
++	if (task_preempts_curr(p, rq))
++		resched_task(rq->curr);
++}
++
+ /***
+  * try_to_wake_up - wake up a thread
+  * @p: the to-be-woken-up thread
+@@ -1521,7 +1707,7 @@
+ 	if (!(old_state & state))
+ 		goto out;
+ 
+-	if (p->array)
++	if (task_queued(p))
+ 		goto out_running;
+ 
+ 	cpu = task_cpu(p);
+@@ -1614,7 +1800,7 @@
+ 		old_state = p->state;
+ 		if (!(old_state & state))
+ 			goto out;
+-		if (p->array)
++		if (task_queued(p))
+ 			goto out_running;
+ 
+ 		this_cpu = smp_processor_id();
+@@ -1623,25 +1809,9 @@
+ 
+ out_activate:
+ #endif /* CONFIG_SMP */
+-	if (old_state == TASK_UNINTERRUPTIBLE) {
++	if (old_state == TASK_UNINTERRUPTIBLE)
+ 		rq->nr_uninterruptible--;
+-		/*
+-		 * Tasks on involuntary sleep don't earn
+-		 * sleep_avg beyond just interactive state.
+-		 */
+-		p->sleep_type = SLEEP_NONINTERACTIVE;
+-	} else
+-
+-	/*
+-	 * Tasks that have marked their sleep as noninteractive get
+-	 * woken up with their sleep average not weighted in an
+-	 * interactive way.
+-	 */
+-		if (old_state & TASK_NONINTERACTIVE)
+-			p->sleep_type = SLEEP_NONINTERACTIVE;
+-
+ 
+-	activate_task(p, rq, cpu == this_cpu);
+ 	/*
+ 	 * Sync wakeups (i.e. those types of wakeups where the waker
+ 	 * has indicated that it will leave the CPU in short order)
+@@ -1650,15 +1820,22 @@
+ 	 * the waker guarantees that the freshly woken up task is going
+ 	 * to be considered on this CPU.)
+ 	 */
+-	if (!sync || cpu != this_cpu) {
+-		if (TASK_PREEMPTS_CURR(p, rq))
+-			resched_task(rq->curr);
+-	}
++	activate_task(p, rq, cpu == this_cpu);
++	if (!sync || cpu != this_cpu)
++		try_preempt(p, rq);
+ 	success = 1;
+ 
+ out_running:
+ 	p->state = TASK_RUNNING;
+ out:
++	/*
++	 * Special case when freezing we need to reschedule idleprio tasks
++	 * as SCHED_NORMAL or else they'll never freeze
++	 */
++	if (idleprio_task(p) && freezing(p) && idleprio(p)) {
++		dequeue_task(p, rq);
++		enqueue_task(p, rq);
++	}
+ 	task_rq_unlock(rq, &flags);
+ 
+ 	return success;
+@@ -1676,7 +1853,6 @@
+ 	return try_to_wake_up(p, state, 0);
+ }
+ 
+-static void task_running_tick(struct rq *rq, struct task_struct *p);
+ /*
+  * Perform scheduler related setup for a newly forked process p.
+  * p is forked by current.
+@@ -1704,7 +1880,6 @@
+ 	p->prio = current->normal_prio;
+ 
+ 	INIT_LIST_HEAD(&p->run_list);
+-	p->array = NULL;
+ #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
+ 	if (unlikely(sched_info_on()))
+ 		memset(&p->sched_info, 0, sizeof(p->sched_info));
+@@ -1716,30 +1891,31 @@
+ 	/* Want to start with kernel preemption disabled. */
+ 	task_thread_info(p)->preempt_count = 1;
+ #endif
++	if (unlikely(p->policy == SCHED_FIFO))
++		goto out;
+ 	/*
+ 	 * Share the timeslice between parent and child, thus the
+ 	 * total amount of pending timeslices in the system doesn't change,
+ 	 * resulting in more scheduling fairness.
+ 	 */
+ 	local_irq_disable();
+-	p->time_slice = (current->time_slice + 1) >> 1;
+-	/*
+-	 * The remainder of the first timeslice might be recovered by
+-	 * the parent if the child exits early enough.
+-	 */
+-	p->first_time_slice = 1;
+-	current->time_slice >>= 1;
+-	p->timestamp = sched_clock();
+-	if (unlikely(!current->time_slice)) {
++	if (current->time_slice > 0) {
++		current->time_slice /= 2;
++		if (current->time_slice)
++			p->time_slice = current->time_slice;
++		else
++			p->time_slice = 1;
+ 		/*
+-		 * This case is rare, it happens when the parent has only
+-		 * a single jiffy left from its timeslice. Taking the
+-		 * runqueue lock is not a problem.
++		 * The remainder of the first timeslice might be recovered by
++		 * the parent if the child exits early enough.
+ 		 */
+-		current->time_slice = 1;
+-		task_running_tick(cpu_rq(cpu), current);
+-	}
++		p->first_time_slice = 1;
++	} else
++		p->time_slice = 0;
++
++	p->timestamp = sched_clock();
+ 	local_irq_enable();
++out:
+ 	put_cpu();
+ }
+ 
+@@ -1761,38 +1937,16 @@
+ 	this_cpu = smp_processor_id();
+ 	cpu = task_cpu(p);
+ 
+-	/*
+-	 * We decrease the sleep average of forking parents
+-	 * and children as well, to keep max-interactive tasks
+-	 * from forking tasks that are max-interactive. The parent
+-	 * (current) is done further down, under its lock.
+-	 */
+-	p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
+-		CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
+-
+-	p->prio = effective_prio(p);
+-
+ 	if (likely(cpu == this_cpu)) {
++		activate_task(p, rq, 1);
+ 		if (!(clone_flags & CLONE_VM)) {
+ 			/*
+ 			 * The VM isn't cloned, so we're in a good position to
+ 			 * do child-runs-first in anticipation of an exec. This
+ 			 * usually avoids a lot of COW overhead.
+ 			 */
+-			if (unlikely(!current->array))
+-				__activate_task(p, rq);
+-			else {
+-				p->prio = current->prio;
+-				p->normal_prio = current->normal_prio;
+-				list_add_tail(&p->run_list, &current->run_list);
+-				p->array = current->array;
+-				p->array->nr_active++;
+-				inc_nr_running(p, rq);
+-			}
+ 			set_need_resched();
+-		} else
+-			/* Run child last */
+-			__activate_task(p, rq);
++		}
+ 		/*
+ 		 * We skip the following code due to cpu == this_cpu
+ 	 	 *
+@@ -1809,19 +1963,16 @@
+ 		 */
+ 		p->timestamp = (p->timestamp - this_rq->most_recent_timestamp)
+ 					+ rq->most_recent_timestamp;
+-		__activate_task(p, rq);
+-		if (TASK_PREEMPTS_CURR(p, rq))
+-			resched_task(rq->curr);
++		activate_task(p, rq, 0);
++		try_preempt(p, rq);
+ 
+ 		/*
+ 		 * Parent and child are on different CPUs, now get the
+-		 * parent runqueue to update the parent's ->sleep_avg:
++		 * parent runqueue to update the parent's ->flags:
+ 		 */
+ 		task_rq_unlock(rq, &flags);
+ 		this_rq = task_rq_lock(current, &flags);
+ 	}
+-	current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
+-		PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
+ 	task_rq_unlock(this_rq, &flags);
+ }
+ 
+@@ -1836,23 +1987,17 @@
+  */
+ void fastcall sched_exit(struct task_struct *p)
+ {
++	struct task_struct *parent;
+ 	unsigned long flags;
+ 	struct rq *rq;
+ 
+-	/*
+-	 * If the child was a (relative-) CPU hog then decrease
+-	 * the sleep_avg of the parent as well.
+-	 */
+-	rq = task_rq_lock(p->parent, &flags);
+-	if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
+-		p->parent->time_slice += p->time_slice;
+-		if (unlikely(p->parent->time_slice > task_timeslice(p)))
+-			p->parent->time_slice = task_timeslice(p);
+-	}
+-	if (p->sleep_avg < p->parent->sleep_avg)
+-		p->parent->sleep_avg = p->parent->sleep_avg /
+-		(EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
+-		(EXIT_WEIGHT + 1);
++	parent = p->parent;
++	rq = task_rq_lock(parent, &flags);
++	if (p->first_time_slice > 0 && task_cpu(p) == task_cpu(parent)) {
++		parent->time_slice += p->time_slice;
++		if (unlikely(parent->time_slice > parent->quota))
++			parent->time_slice = parent->quota;
++	}
+ 	task_rq_unlock(rq, &flags);
+ }
+ 
+@@ -2184,23 +2329,17 @@
+  * pull_task - move a task from a remote runqueue to the local runqueue.
+  * Both runqueues must be locked.
+  */
+-static void pull_task(struct rq *src_rq, struct prio_array *src_array,
+-		      struct task_struct *p, struct rq *this_rq,
+-		      struct prio_array *this_array, int this_cpu)
++static void pull_task(struct rq *src_rq, struct task_struct *p,
++		      struct rq *this_rq, int this_cpu)
+ {
+-	dequeue_task(p, src_array);
++	dequeue_task(p, src_rq);
+ 	dec_nr_running(p, src_rq);
+ 	set_task_cpu(p, this_cpu);
+ 	inc_nr_running(p, this_rq);
+-	enqueue_task(p, this_array);
++	enqueue_task(p, this_rq);
+ 	p->timestamp = (p->timestamp - src_rq->most_recent_timestamp)
+ 				+ this_rq->most_recent_timestamp;
+-	/*
+-	 * Note that idle threads have a prio of MAX_PRIO, for this test
+-	 * to be always true for them.
+-	 */
+-	if (TASK_PREEMPTS_CURR(p, this_rq))
+-		resched_task(this_rq->curr);
++	try_preempt(p, this_rq);
+ }
+ 
+ /*
+@@ -2243,7 +2382,16 @@
+ 	return 1;
+ }
+ 
+-#define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
++static inline int rq_best_prio(struct rq *rq)
++{
++	int best_prio, exp_prio;
++
++	best_prio = sched_find_first_bit(rq->dyn_bitmap);
++	exp_prio = find_next_bit(rq->exp_bitmap, MAX_PRIO, MAX_RT_PRIO);
++	if (unlikely(best_prio > exp_prio))
++		best_prio = exp_prio;
++	return best_prio;
++}
+ 
+ /*
+  * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
+@@ -2259,7 +2407,7 @@
+ {
+ 	int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
+ 	    best_prio_seen, skip_for_load;
+-	struct prio_array *array, *dst_array;
++	struct prio_array *array;
+ 	struct list_head *head, *curr;
+ 	struct task_struct *tmp;
+ 	long rem_load_move;
+@@ -2286,31 +2434,29 @@
+ 	 * be cache-cold, thus switching CPUs has the least effect
+ 	 * on them.
+ 	 */
+-	if (busiest->expired->nr_active) {
+-		array = busiest->expired;
+-		dst_array = this_rq->expired;
+-	} else {
+-		array = busiest->active;
+-		dst_array = this_rq->active;
+-	}
+-
++	array = busiest->expired;
+ new_array:
+-	/* Start searching at priority 0: */
+-	idx = 0;
++	/* Expired arrays don't have RT tasks so they're always MAX_RT_PRIO+ */
++	if (array == busiest->expired)
++		idx = MAX_RT_PRIO;
++	else
++		idx = 0;
+ skip_bitmap:
+ 	if (!idx)
+-		idx = sched_find_first_bit(array->bitmap);
++		idx = sched_find_first_bit(array->prio_bitmap);
+ 	else
+-		idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
+-	if (idx >= MAX_PRIO) {
+-		if (array == busiest->expired && busiest->active->nr_active) {
++		idx = find_next_bit(array->prio_bitmap, MAX_PRIO, idx);
++	if (idx == MAX_PRIO) {
++		if (array == busiest->idleprio && busiest->nr_idleprio)
++			goto found_idleprio;
++		if (array == busiest->expired) {
+ 			array = busiest->active;
+-			dst_array = this_rq->active;
+ 			goto new_array;
+ 		}
+ 		goto out;
+ 	}
+ 
++found_idleprio:
+ 	head = array->queue + idx;
+ 	curr = head->prev;
+ skip_queue:
+@@ -2332,11 +2478,22 @@
+ 		best_prio_seen |= idx == best_prio;
+ 		if (curr != head)
+ 			goto skip_queue;
++		if (idx == MAX_PRIO) {
++			/*
++			 * Occurs either when balancing idleprio tasks or
++			 * there really are no more tasks to find.
++			 */
++			if (array == busiest->expired) {
++				array = busiest->active;
++				goto new_array;
++			}
++			goto out;
++		}
+ 		idx++;
+ 		goto skip_bitmap;
+ 	}
+ 
+-	pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
++	pull_task(busiest, tmp, this_rq, this_cpu);
+ 	pulled++;
+ 	rem_load_move -= tmp->load_weight;
+ 
+@@ -2349,6 +2506,13 @@
+ 			this_best_prio = idx;
+ 		if (curr != head)
+ 			goto skip_queue;
++		if (idx == MAX_PRIO) {
++			if (array == busiest->expired) {
++				array = busiest->active;
++				goto new_array;
++			}
++			goto out;
++		}
+ 		idx++;
+ 		goto skip_bitmap;
+ 	}
+@@ -3297,11 +3461,36 @@
+ /*
+  * This is called on clock ticks and on context switches.
+  * Bank in p->sched_time the ns elapsed since the last tick or switch.
++ * CPU scheduler quota accounting is also performed here in microseconds.
++ * The value returned from sched_clock() occasionally gives bogus values so
++ * some sanity checking is required.
+  */
+-static inline void
+-update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
++static void
++update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now,
++		 int tick)
+ {
+-	p->sched_time += now - p->last_ran;
++	long time_diff = now - p->last_ran;
++
++	if (tick) {
++		/*
++		 * Called from scheduler_tick() there should be less than two
++		 * jiffies worth, and not negative/overflow.
++		 */
++		if (time_diff > JIFFIES_TO_NS(2) || time_diff < 0)
++			time_diff = JIFFIES_TO_NS(1);
++	} else {
++		/*
++		 * Called from context_switch there should be less than one
++		 * jiffy worth, and not negative/overflow. There should be
++		 * some time banked here so use a nominal 1us.
++		 */
++		if (time_diff > JIFFIES_TO_NS(1) || time_diff < 1)
++			time_diff = 1000;
++	}
++	/* time_slice accounting is done in usecs to avoid overflow on 32bit */
++	if (p != rq->idle && p->policy != SCHED_FIFO)
++		p->time_slice -= time_diff / 1000;
++	p->sched_time += time_diff;
+ 	p->last_ran = rq->most_recent_timestamp = now;
+ }
+ 
+@@ -3322,27 +3511,6 @@
+ }
+ 
+ /*
+- * We place interactive tasks back into the active array, if possible.
+- *
+- * To guarantee that this does not starve expired tasks we ignore the
+- * interactivity of a task if the first expired task had to wait more
+- * than a 'reasonable' amount of time. This deadline timeout is
+- * load-dependent, as the frequency of array switched decreases with
+- * increasing number of running tasks. We also ignore the interactivity
+- * if a better static_prio task has expired:
+- */
+-static inline int expired_starving(struct rq *rq)
+-{
+-	if (rq->curr->static_prio > rq->best_expired_prio)
+-		return 1;
+-	if (!STARVATION_LIMIT || !rq->expired_timestamp)
+-		return 0;
+-	if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
+-		return 1;
+-	return 0;
+-}
+-
+-/*
+  * Account user cpu time to a process.
+  * @p: the process that the cpu time gets accounted to
+  * @hardirq_offset: the offset to subtract from hardirq_count()
+@@ -3357,7 +3525,7 @@
+ 
+ 	/* Add user time to cpustat. */
+ 	tmp = cputime_to_cputime64(cputime);
+-	if (TASK_NICE(p) > 0)
++	if (TASK_NICE(p) > 0 || idleprio_task(p))
+ 		cpustat->nice = cputime64_add(cpustat->nice, tmp);
+ 	else
+ 		cpustat->user = cputime64_add(cpustat->user, tmp);
+@@ -3415,87 +3583,94 @@
+ 		cpustat->steal = cputime64_add(cpustat->steal, tmp);
+ }
+ 
+-static void task_running_tick(struct rq *rq, struct task_struct *p)
++/*
++ * The task has used up its quota of running in this prio_level so it must be
++ * dropped a priority level, all managed by recalc_task_prio().
++ */
++static void task_expired_entitlement(struct rq *rq, struct task_struct *p)
+ {
+-	if (p->array != rq->active) {
+-		/* Task has expired but was not scheduled yet */
+-		set_tsk_need_resched(p);
++	int overrun;
++
++	reset_first_time_slice(p);
++	if (rt_task(p)) {
++		p->time_slice += p->quota;
++		list_move_tail(&p->run_list, p->array->queue + p->prio);
+ 		return;
+ 	}
+-	spin_lock(&rq->lock);
++	overrun = p->time_slice;
++	dequeue_task(p, rq);
++	enqueue_task(p, rq);
+ 	/*
+-	 * The task was running during this tick - update the
+-	 * time slice counter. Note: we do not update a thread's
+-	 * priority until it either goes to sleep or uses up its
+-	 * timeslice. This makes it possible for interactive tasks
+-	 * to use up their timeslices at their highest priority levels.
++	 * Subtract any extra time this task ran over its time_slice; ie
++	 * overrun will either be 0 or negative.
+ 	 */
+-	if (rt_task(p)) {
+-		/*
+-		 * RR tasks need a special form of timeslice management.
+-		 * FIFO tasks have no timeslices.
+-		 */
+-		if ((p->policy == SCHED_RR) && !--p->time_slice) {
+-			p->time_slice = task_timeslice(p);
+-			p->first_time_slice = 0;
+-			set_tsk_need_resched(p);
++	p->time_slice += overrun;
++}
+ 
+-			/* put it at the end of the queue: */
+-			requeue_task(p, rq->active);
+-		}
+-		goto out_unlock;
++/*
++ * Test if SCHED_ISO tasks have run longer than their alloted period as RT
++ * tasks and set the refractory flag if necessary. There is 10% hysteresis
++ * for unsetting the flag.
++ */
++static unsigned int test_ret_isorefractory(struct rq *rq)
++{
++	if (likely(!rq->iso_refractory)) {
++		if (rq->iso_ticks / ISO_PERIOD > sched_iso_cpu)
++			rq->iso_refractory = 1;
++	} else {
++		if (rq->iso_ticks / ISO_PERIOD < (sched_iso_cpu * 90 / 100))
++			rq->iso_refractory = 0;
+ 	}
+-	if (!--p->time_slice) {
+-		dequeue_task(p, rq->active);
+-		set_tsk_need_resched(p);
+-		p->prio = effective_prio(p);
+-		p->time_slice = task_timeslice(p);
+-		p->first_time_slice = 0;
++	return rq->iso_refractory;
++}
+ 
+-		if (!rq->expired_timestamp)
+-			rq->expired_timestamp = jiffies;
+-		if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
+-			enqueue_task(p, rq->expired);
+-			if (p->static_prio < rq->best_expired_prio)
+-				rq->best_expired_prio = p->static_prio;
+-		} else
+-			enqueue_task(p, rq->active);
+-	} else {
+-		/*
+-		 * Prevent a too long timeslice allowing a task to monopolize
+-		 * the CPU. We do this by splitting up the timeslice into
+-		 * smaller pieces.
+-		 *
+-		 * Note: this does not mean the task's timeslices expire or
+-		 * get lost in any way, they just might be preempted by
+-		 * another task of equal priority. (one with higher
+-		 * priority would have preempted this task already.) We
+-		 * requeue this task to the end of the list on this priority
+-		 * level, which is in essence a round-robin of tasks with
+-		 * equal priority.
+-		 *
+-		 * This only applies to tasks in the interactive
+-		 * delta range with at least TIMESLICE_GRANULARITY to requeue.
+-		 */
+-		if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
+-			p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
+-			(p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
+-			(p->array == rq->active)) {
++/* No SCHED_ISO task was running so decrease rq->iso_ticks */
++static inline void no_iso_tick(struct rq *rq)
++{
++	rq->iso_ticks = rq->iso_ticks * (ISO_PERIOD - 1) / ISO_PERIOD;
++}
+ 
+-			requeue_task(p, rq->active);
+-			set_tsk_need_resched(p);
+-		}
++/* This manages tasks that have run out of timeslice during a scheduler_tick */
++static void task_running_tick(struct rq *rq, struct task_struct *p)
++{
++	/*
++	 * If a SCHED_ISO task is running we increment the iso_ticks. In
++	 * order to prevent SCHED_ISO tasks from causing starvation in the
++	 * presence of true RT tasks we account those as iso_ticks as well.
++	 */
++	if ((rt_task(p) || (iso_task(p) && !rq->iso_refractory))) {
++		if (rq->iso_ticks <= (ISO_PERIOD * 100) - 100)
++			rq->iso_ticks += 100;
++	} else
++		no_iso_tick(rq);
++
++	if (iso_task(p)) {
++		if (unlikely(test_ret_isorefractory(rq))) {
++			if (isoprio_suitable(p)) {
++				/*
++				 * SCHED_ISO task is running as RT and limit
++				 * has been hit. Set the PF_ISOREF flag and
++				 * force it to reschedule as SCHED_NORMAL
++				 * by zeroing its time_slice
++				 */
++				p->flags |= PF_ISOREF;
++				p->time_slice = 0;
++			}
++		} else
++			p->flags &= ~PF_ISOREF;
+ 	}
+-out_unlock:
+-	spin_unlock(&rq->lock);
++	/* SCHED_FIFO tasks never run out of timeslice. */
++	if (p->time_slice > 0 || p->policy == SCHED_FIFO)
++		return;
++	/* p->time_slice <= 0 */
++	set_tsk_need_resched(p);
++	if (likely(task_queued(p)))
++		task_expired_entitlement(rq, p);
+ }
+ 
+ /*
+  * This function gets called by the timer code, with HZ frequency.
+  * We call it with interrupts disabled.
+- *
+- * It also gets called by the fork code, when changing the parent's
+- * timeslices.
+  */
+ void scheduler_tick(void)
+ {
+@@ -3505,10 +3680,14 @@
+ 	int idle_at_tick = idle_cpu(cpu);
+ 	struct rq *rq = cpu_rq(cpu);
+ 
+-	update_cpu_clock(p, rq, now);
++	update_cpu_clock(p, rq, now, 1);
+ 
++	spin_lock(&rq->lock);
+ 	if (!idle_at_tick)
+ 		task_running_tick(rq, p);
++	else
++		no_iso_tick(rq);
++	spin_unlock(&rq->lock);
+ #ifdef CONFIG_SMP
+ 	update_load(rq);
+ 	rq->idle_at_tick = idle_at_tick;
+@@ -3554,10 +3733,80 @@
+ 
+ #endif
+ 
+-static inline int interactive_sleep(enum sleep_type sleep_type)
++static void reset_prio_levels(struct rq *rq)
+ {
+-	return (sleep_type == SLEEP_INTERACTIVE ||
+-		sleep_type == SLEEP_INTERRUPTED);
++	rq->active->best_static_prio = MAX_PRIO - 1;
++	rq->expired->best_static_prio = MAX_PRIO - 1;
++	memset(rq->prio_level, 0, sizeof(int) * PRIO_RANGE);
++}
++
++/*
++ * Only tasks running are SCHED_IDLEPRIO. Set the active array to the
++ * idleprio array and if it isn't already active
++ */
++static struct task_struct *next_idleprio_task(struct rq *rq)
++{
++	struct prio_array *array = rq->active;
++	struct list_head *queue;
++
++	if (array != rq->idleprio) {
++		rq->active = rq->idleprio;
++		rq->expired = array;
++		array = rq->active;
++		rq->exp_bitmap = rq->expired->prio_bitmap;
++		rq->dyn_bitmap = rq->active->prio_bitmap;
++	}
++	rq->prio_rotation++;
++	reset_prio_levels(rq);
++	queue = array->queue + MAX_PRIO;
++	return list_entry(queue->next, struct task_struct, run_list);
++}
++
++/*
++ * next_dynamic_task finds the next suitable dynamic task.
++ */
++static inline struct task_struct *next_dynamic_task(struct rq *rq, int idx)
++{
++	struct prio_array *array = rq->active;
++	struct task_struct *next;
++	struct list_head *queue;
++	int nstatic;
++
++retry:
++	if (unlikely(rq->nr_running == rq->nr_idleprio))
++		return next_idleprio_task(rq);
++	if (idx >= MAX_PRIO) {
++		/* There are no more tasks in the active array. Swap arrays */
++		array = rq->expired;
++		rq->expired = rq->active;
++		rq->active = array;
++		rq->exp_bitmap = rq->expired->prio_bitmap;
++		rq->dyn_bitmap = rq->active->prio_bitmap;
++		rq->prio_rotation++;
++		idx = find_next_bit(rq->dyn_bitmap, MAX_PRIO, MAX_RT_PRIO);
++		reset_prio_levels(rq);
++	}
++	queue = array->queue + idx;
++	next = list_entry(queue->next, struct task_struct, run_list);
++	if (unlikely(next->time_slice <= 0 && !(iso_task(next) &&
++	    isoprio_suitable(next)))) {
++		/*
++		 * Unlucky enough that this task ran out of time_slice
++		 * before it hit a scheduler_tick so it should have its
++		 * priority reassessed and choose another task (possibly
++		 * the same one)
++		 */
++		task_expired_entitlement(rq, next);
++		idx = find_next_bit(rq->dyn_bitmap, MAX_PRIO, MAX_RT_PRIO);
++		goto retry;
++	}
++	next->rotation = rq->prio_rotation;
++	nstatic = next->static_prio;
++	if (nstatic < array->best_static_prio)
++		array->best_static_prio = nstatic;
++	if (idx > rq->prio_level[USER_PRIO(nstatic)])
++		rq->prio_level[USER_PRIO(nstatic)] = idx;
++	return next;
+ }
+ 
+ /*
+@@ -3566,13 +3815,11 @@
+ asmlinkage void __sched schedule(void)
+ {
+ 	struct task_struct *prev, *next;
+-	struct prio_array *array;
+ 	struct list_head *queue;
+ 	unsigned long long now;
+-	unsigned long run_time;
+-	int cpu, idx, new_prio;
+ 	long *switch_count;
+ 	struct rq *rq;
++	int cpu, idx;
+ 
+ 	/*
+ 	 * Test if we are atomic.  Since do_exit() needs to call into
+@@ -3608,18 +3855,6 @@
+ 
+ 	schedstat_inc(rq, sched_cnt);
+ 	now = sched_clock();
+-	if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
+-		run_time = now - prev->timestamp;
+-		if (unlikely((long long)(now - prev->timestamp) < 0))
+-			run_time = 0;
+-	} else
+-		run_time = NS_MAX_SLEEP_AVG;
+-
+-	/*
+-	 * Tasks charged proportionately less run_time at high sleep_avg to
+-	 * delay them losing their interactive status
+-	 */
+-	run_time /= (CURRENT_BONUS(prev) ? : 1);
+ 
+ 	spin_lock_irq(&rq->lock);
+ 
+@@ -3630,8 +3865,10 @@
+ 				unlikely(signal_pending(prev))))
+ 			prev->state = TASK_RUNNING;
+ 		else {
+-			if (prev->state == TASK_UNINTERRUPTIBLE)
++			if (prev->state == TASK_UNINTERRUPTIBLE) {
++				prev->flags |= PF_NONSLEEP;
+ 				rq->nr_uninterruptible++;
++			}
+ 			deactivate_task(prev, rq);
+ 		}
+ 	}
+@@ -3641,59 +3878,29 @@
+ 		idle_balance(cpu, rq);
+ 		if (!rq->nr_running) {
+ 			next = rq->idle;
+-			rq->expired_timestamp = 0;
+ 			goto switch_tasks;
+ 		}
+ 	}
+ 
+-	array = rq->active;
+-	if (unlikely(!array->nr_active)) {
+-		/*
+-		 * Switch the active and expired arrays.
+-		 */
+-		schedstat_inc(rq, sched_switch);
+-		rq->active = rq->expired;
+-		rq->expired = array;
+-		array = rq->active;
+-		rq->expired_timestamp = 0;
+-		rq->best_expired_prio = MAX_PRIO;
+-	}
+-
+-	idx = sched_find_first_bit(array->bitmap);
+-	queue = array->queue + idx;
+-	next = list_entry(queue->next, struct task_struct, run_list);
+-
+-	if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
+-		unsigned long long delta = now - next->timestamp;
+-		if (unlikely((long long)(now - next->timestamp) < 0))
+-			delta = 0;
+-
+-		if (next->sleep_type == SLEEP_INTERACTIVE)
+-			delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
+-
+-		array = next->array;
+-		new_prio = recalc_task_prio(next, next->timestamp + delta);
+-
+-		if (unlikely(next->prio != new_prio)) {
+-			dequeue_task(next, array);
+-			next->prio = new_prio;
+-			enqueue_task(next, array);
+-		}
++	idx = sched_find_first_bit(rq->dyn_bitmap);
++	if (likely(idx > ISO_PRIO))
++		next = next_dynamic_task(rq, idx);
++	else {
++		queue = rq->active->queue + idx;
++		next = list_entry(queue->next, struct task_struct, run_list);
+ 	}
+-	next->sleep_type = SLEEP_NORMAL;
+ switch_tasks:
+-	if (next == rq->idle)
++	if (next == rq->idle) {
++		reset_prio_levels(rq);
++		rq->prio_rotation++;
+ 		schedstat_inc(rq, sched_goidle);
++	}
+ 	prefetch(next);
+ 	prefetch_stack(next);
+ 	clear_tsk_need_resched(prev);
+ 	rcu_qsctr_inc(task_cpu(prev));
+ 
+-	update_cpu_clock(prev, rq, now);
+-
+-	prev->sleep_avg -= run_time;
+-	if ((long)prev->sleep_avg <= 0)
+-		prev->sleep_avg = 0;
++	update_cpu_clock(prev, rq, now, 0);
+ 	prev->timestamp = prev->last_ran = now;
+ 
+ 	sched_info_switch(prev, next);
+@@ -4129,29 +4336,22 @@
+  */
+ void rt_mutex_setprio(struct task_struct *p, int prio)
+ {
+-	struct prio_array *array;
+ 	unsigned long flags;
++	int queued, oldprio;
+ 	struct rq *rq;
+-	int oldprio;
+ 
+ 	BUG_ON(prio < 0 || prio > MAX_PRIO);
+ 
+ 	rq = task_rq_lock(p, &flags);
+ 
+ 	oldprio = p->prio;
+-	array = p->array;
+-	if (array)
+-		dequeue_task(p, array);
++	queued = task_queued(p);
++	if (queued)
++		dequeue_task(p, rq);
+ 	p->prio = prio;
+ 
+-	if (array) {
+-		/*
+-		 * If changing to an RT priority then queue it
+-		 * in the active array!
+-		 */
+-		if (rt_task(p))
+-			array = rq->active;
+-		enqueue_task(p, array);
++	if (queued) {
++		enqueue_task(p, rq);
+ 		/*
+ 		 * Reschedule if we are currently running on this runqueue and
+ 		 * our priority decreased, or if we are not currently running on
+@@ -4160,8 +4360,8 @@
+ 		if (task_running(rq, p)) {
+ 			if (p->prio > oldprio)
+ 				resched_task(rq->curr);
+-		} else if (TASK_PREEMPTS_CURR(p, rq))
+-			resched_task(rq->curr);
++		} else
++			try_preempt(p, rq);
+ 	}
+ 	task_rq_unlock(rq, &flags);
+ }
+@@ -4170,8 +4370,7 @@
+ 
+ void set_user_nice(struct task_struct *p, long nice)
+ {
+-	struct prio_array *array;
+-	int old_prio, delta;
++	int queued, old_prio,delta;
+ 	unsigned long flags;
+ 	struct rq *rq;
+ 
+@@ -4192,26 +4391,27 @@
+ 		p->static_prio = NICE_TO_PRIO(nice);
+ 		goto out_unlock;
+ 	}
+-	array = p->array;
+-	if (array) {
+-		dequeue_task(p, array);
++	queued = task_queued(p);
++	if (queued) {
++		dequeue_task(p, rq);
+ 		dec_raw_weighted_load(rq, p);
+ 	}
+ 
+ 	p->static_prio = NICE_TO_PRIO(nice);
+-	set_load_weight(p);
+ 	old_prio = p->prio;
+ 	p->prio = effective_prio(p);
++	set_quota(p);
+ 	delta = p->prio - old_prio;
+ 
+-	if (array) {
+-		enqueue_task(p, array);
++	if (queued) {
++		enqueue_task(p, rq);
+ 		inc_raw_weighted_load(rq, p);
+ 		/*
+ 		 * If the task increased its priority or is running and
+ 		 * lowered its priority, then reschedule its CPU:
+ 		 */
+-		if (delta < 0 || (delta > 0 && task_running(rq, p)))
++		if (delta < 0 || ((delta > 0 || idleprio_task(p)) &&
++		    task_running(rq, p)))
+ 			resched_task(rq->curr);
+ 	}
+ out_unlock:
+@@ -4281,11 +4481,23 @@
+  *
+  * This is the priority value as seen by users in /proc.
+  * RT tasks are offset by -200. Normal tasks are centered
+- * around 0, value goes from -16 to +15.
++ * around 1, value goes from 0 to +79. Values higher than
++ * 39 indicate task is on the expired array. This is done
++ * lockless and may rarely return an active instead of
++ * expired value.
+  */
+-int task_prio(const struct task_struct *p)
++int task_prio(struct task_struct *p)
+ {
+-	return p->prio - MAX_RT_PRIO;
++	int prio = p->prio - MAX_RT_PRIO;
++
++	if (task_queued(p)) {
++		struct rq *rq = task_rq(p);
++		struct prio_array *array = p->array;
++
++		if (rq && rq->expired == array)
++			prio += PRIO_RANGE;
++	}
++	return prio;
+ }
+ 
+ /**
+@@ -4328,19 +4540,14 @@
+ /* Actually do priority change: must hold rq lock. */
+ static void __setscheduler(struct task_struct *p, int policy, int prio)
+ {
+-	BUG_ON(p->array);
++	BUG_ON(task_queued(p));
+ 
+ 	p->policy = policy;
+ 	p->rt_priority = prio;
+ 	p->normal_prio = normal_prio(p);
+ 	/* we are holding p->pi_lock already */
+ 	p->prio = rt_mutex_getprio(p);
+-	/*
+-	 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
+-	 */
+-	if (policy == SCHED_BATCH)
+-		p->sleep_avg = 0;
+-	set_load_weight(p);
++	set_quota(p);
+ }
+ 
+ /**
+@@ -4354,19 +4561,36 @@
+ int sched_setscheduler(struct task_struct *p, int policy,
+ 		       struct sched_param *param)
+ {
+-	int retval, oldprio, oldpolicy = -1;
+-	struct prio_array *array;
++	struct sched_param zero_param = { .sched_priority = 0 };
++	int queued, retval, oldprio, oldpolicy = -1;
++	unsigned long rlim_rtprio = 0;
+ 	unsigned long flags;
+ 	struct rq *rq;
+ 
+ 	/* may grab non-irq protected spin_locks */
+ 	BUG_ON(in_interrupt());
++	if (is_rt_policy(policy) && !capable(CAP_SYS_NICE)) {
++		unsigned long lflags;
++
++		if (!lock_task_sighand(p, &lflags))
++			return -ESRCH;
++		rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
++		unlock_task_sighand(p, &lflags);
++		if (rlim_rtprio)
++			goto recheck;
++		/*
++		 * If the caller requested an RT policy without having the
++		 * necessary rights, we downgrade the policy to SCHED_ISO.
++		 * We also set the parameter to zero to pass the checks.
++		 */
++		policy = SCHED_ISO;
++		param = &zero_param;
++	}
+ recheck:
+ 	/* double check policy once rq lock held */
+ 	if (policy < 0)
+ 		policy = oldpolicy = p->policy;
+-	else if (policy != SCHED_FIFO && policy != SCHED_RR &&
+-			policy != SCHED_NORMAL && policy != SCHED_BATCH)
++	else if (!SCHED_RANGE(policy))
+ 		return -EINVAL;
+ 	/*
+ 	 * Valid priorities for SCHED_FIFO and SCHED_RR are
+@@ -4385,14 +4609,6 @@
+ 	 */
+ 	if (!capable(CAP_SYS_NICE)) {
+ 		if (is_rt_policy(policy)) {
+-			unsigned long rlim_rtprio;
+-			unsigned long flags;
+-
+-			if (!lock_task_sighand(p, &flags))
+-				return -ESRCH;
+-			rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
+-			unlock_task_sighand(p, &flags);
+-
+ 			/* can't set/change the rt policy */
+ 			if (policy != p->policy && !rlim_rtprio)
+ 				return -EPERM;
+@@ -4401,6 +4617,31 @@
+ 			if (param->sched_priority > p->rt_priority &&
+ 			    param->sched_priority > rlim_rtprio)
+ 				return -EPERM;
++		} else {
++			switch (p->policy) {
++				/*
++				 * Can only downgrade policies but not back to
++				 * SCHED_NORMAL
++				 */
++				case SCHED_ISO:
++					if (policy == SCHED_ISO)
++						goto out;
++					if (policy == SCHED_NORMAL)
++						return -EPERM;
++					break;
++				case SCHED_BATCH:
++					if (policy == SCHED_BATCH)
++						goto out;
++					if (policy != SCHED_IDLEPRIO)
++					    	return -EPERM;
++					break;
++				case SCHED_IDLEPRIO:
++					if (policy == SCHED_IDLEPRIO)
++						goto out;
++					return -EPERM;
++				default:
++					break;
++			}
+ 		}
+ 
+ 		/* can't change other user's priorities */
+@@ -4409,6 +4650,11 @@
+ 			return -EPERM;
+ 	}
+ 
++	if (!(p->mm) && policy == SCHED_IDLEPRIO) {
++		/* Don't allow kernel threads to be SCHED_IDLEPRIO. */
++		return -EINVAL;
++	}
++
+ 	retval = security_task_setscheduler(p, policy, param);
+ 	if (retval)
+ 		return retval;
+@@ -4429,12 +4675,12 @@
+ 		spin_unlock_irqrestore(&p->pi_lock, flags);
+ 		goto recheck;
+ 	}
+-	array = p->array;
+-	if (array)
++	queued = task_queued(p);
++	if (queued)
+ 		deactivate_task(p, rq);
+ 	oldprio = p->prio;
+ 	__setscheduler(p, policy, param->sched_priority);
+-	if (array) {
++	if (queued) {
+ 		__activate_task(p, rq);
+ 		/*
+ 		 * Reschedule if we are currently running on this runqueue and
+@@ -4444,14 +4690,15 @@
+ 		if (task_running(rq, p)) {
+ 			if (p->prio > oldprio)
+ 				resched_task(rq->curr);
+-		} else if (TASK_PREEMPTS_CURR(p, rq))
+-			resched_task(rq->curr);
++		} else
++			try_preempt(p, rq);
+ 	}
+ 	__task_rq_unlock(rq);
+ 	spin_unlock_irqrestore(&p->pi_lock, flags);
+ 
+ 	rt_mutex_adjust_pi(p);
+ 
++out:
+ 	return 0;
+ }
+ EXPORT_SYMBOL_GPL(sched_setscheduler);
+@@ -4718,41 +4965,34 @@
+  * sys_sched_yield - yield the current processor to other threads.
+  *
+  * This function yields the current CPU by moving the calling thread
+- * to the expired array. If there are no other threads running on this
+- * CPU then this function will return.
++ * to the expired array if SCHED_NORMAL or the end of its current priority
++ * queue if a realtime task. If there are no other threads running on this
++ * cpu this function will return.
+  */
+ asmlinkage long sys_sched_yield(void)
+ {
+ 	struct rq *rq = this_rq_lock();
+-	struct prio_array *array = current->array, *target = rq->expired;
++	struct task_struct *p = current;
+ 
+ 	schedstat_inc(rq, yld_cnt);
+-	/*
+-	 * We implement yielding by moving the task into the expired
+-	 * queue.
+-	 *
+-	 * (special rule: RT tasks will just roundrobin in the active
+-	 *  array.)
+-	 */
+-	if (rt_task(current))
+-		target = rq->active;
+-
+-	if (array->nr_active == 1) {
+-		schedstat_inc(rq, yld_act_empty);
+-		if (!rq->expired->nr_active)
+-			schedstat_inc(rq, yld_both_empty);
+-	} else if (!rq->expired->nr_active)
+-		schedstat_inc(rq, yld_exp_empty);
+-
+-	if (array != target) {
+-		dequeue_task(current, array);
+-		enqueue_task(current, target);
+-	} else
+-		/*
+-		 * requeue_task is cheaper so perform that if possible.
+-		 */
+-		requeue_task(current, array);
++	if (rq->nr_running == 1)
++		schedstat_inc(rq, yld_both_empty);
++	else {
++		struct prio_array *old_array = p->array;
++		int old_prio = p->prio;
++
++		if (idleprio_task(p)) {
++			dequeue_task(p, rq);
++			enqueue_task(p, rq);
++			goto out_release;
++		}
++		/* p->prio will be updated in requeue_task via queue_expired */
++		if (!rt_task(p))
++			p->array = rq->expired;
++		requeue_task(p, rq, old_array, old_prio);
++	}
+ 
++out_release:
+ 	/*
+ 	 * Since we are going to call schedule() anyway, there's
+ 	 * no need to preempt or enable interrupts:
+@@ -4902,6 +5142,8 @@
+ 		break;
+ 	case SCHED_NORMAL:
+ 	case SCHED_BATCH:
++	case SCHED_ISO:
++	case SCHED_IDLEPRIO:
+ 		ret = 0;
+ 		break;
+ 	}
+@@ -4926,6 +5168,8 @@
+ 		break;
+ 	case SCHED_NORMAL:
+ 	case SCHED_BATCH:
++	case SCHED_ISO:
++	case SCHED_IDLEPRIO:
+ 		ret = 0;
+ 	}
+ 	return ret;
+@@ -4959,8 +5203,8 @@
+ 	if (retval)
+ 		goto out_unlock;
+ 
+-	jiffies_to_timespec(p->policy == SCHED_FIFO ?
+-				0 : task_timeslice(p), &t);
++	t = ns_to_timespec(p->policy == SCHED_FIFO ? 0 :
++			   MS_TO_NS(task_timeslice(p)));
+ 	read_unlock(&tasklist_lock);
+ 	retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
+ out_nounlock:
+@@ -5056,10 +5300,10 @@
+ 	struct rq *rq = cpu_rq(cpu);
+ 	unsigned long flags;
+ 
+-	idle->timestamp = sched_clock();
+-	idle->sleep_avg = 0;
+-	idle->array = NULL;
+-	idle->prio = idle->normal_prio = MAX_PRIO;
++	bitmap_zero(idle->bitmap, PRIO_RANGE);
++	idle->timestamp = idle->last_ran = sched_clock();
++	idle->array = rq->active;
++	idle->prio = idle->normal_prio = NICE_TO_PRIO(0);
+ 	idle->state = TASK_RUNNING;
+ 	idle->cpus_allowed = cpumask_of_cpu(cpu);
+ 	set_task_cpu(idle, cpu);
+@@ -5178,7 +5422,7 @@
+ 		goto out;
+ 
+ 	set_task_cpu(p, dest_cpu);
+-	if (p->array) {
++	if (task_queued(p)) {
+ 		/*
+ 		 * Sync timestamp with rq_dest's before activating.
+ 		 * The same thing could be achieved by doing this step
+@@ -5189,8 +5433,7 @@
+ 				+ rq_dest->most_recent_timestamp;
+ 		deactivate_task(p, rq_src);
+ 		__activate_task(p, rq_dest);
+-		if (TASK_PREEMPTS_CURR(p, rq_dest))
+-			resched_task(rq_dest->curr);
++		try_preempt(p, rq_dest);
+ 	}
+ 	ret = 1;
+ out:
+@@ -5487,7 +5730,7 @@
+ 		/* Idle task back to normal (off runqueue, low prio) */
+ 		rq = task_rq_lock(rq->idle, &flags);
+ 		deactivate_task(rq->idle, rq);
+-		rq->idle->static_prio = MAX_PRIO;
++		rq->idle->static_prio = NICE_TO_PRIO(0);
+ 		__setscheduler(rq->idle, SCHED_NORMAL, 0);
+ 		migrate_dead_tasks(cpu);
+ 		task_rq_unlock(rq, &flags);
+@@ -7013,6 +7256,13 @@
+ 	/* Move init over to a non-isolated CPU */
+ 	if (set_cpus_allowed(current, non_isolated_cpus) < 0)
+ 		BUG();
++
++	/*
++	 * Assume that every added cpu gives us slightly less overall latency
++	 * allowing us to increase the base rr_interval, but in a non linear
++	 * fashion.
++	 */
++	rr_interval *= 1 + ilog2(num_online_cpus());
+ }
+ #else
+ void __init sched_init_smp(void)
+@@ -7035,6 +7285,16 @@
+ 	int i, j, k;
+ 	int highest_cpu = 0;
+ 
++	/* Generate the priority matrix */
++	for (i = 0; i < PRIO_RANGE; i++) {
++		bitmap_fill(prio_matrix[i], PRIO_RANGE);
++		j = PRIO_RANGE * PRIO_RANGE / (PRIO_RANGE - i);
++		for (k = 0; k <= PRIO_RANGE * (PRIO_RANGE - 1); k += j) {
++			__clear_bit(PRIO_RANGE - 1 - (k / PRIO_RANGE),
++				    prio_matrix[i]);
++		}
++	}
++
+ 	for_each_possible_cpu(i) {
+ 		struct prio_array *array;
+ 		struct rq *rq;
+@@ -7042,12 +7302,20 @@
+ 		rq = cpu_rq(i);
+ 		spin_lock_init(&rq->lock);
+ 		lockdep_set_class(&rq->lock, &rq->rq_lock_key);
++		rq->iso_ticks = 0;
+ 		rq->nr_running = 0;
++		rq->nr_idleprio = 0;
++		rq->prio_rotation = 0;
+ 		rq->active = rq->arrays;
++		rq->idleprio = rq->active;
+ 		rq->expired = rq->arrays + 1;
+-		rq->best_expired_prio = MAX_PRIO;
++		reset_prio_levels(rq);
++		rq->dyn_bitmap = rq->active->prio_bitmap;
++		rq->exp_bitmap = rq->expired->prio_bitmap;
+ 
+ #ifdef CONFIG_SMP
++		rq->active->rq = rq;
++		rq->expired->rq = rq;
+ 		rq->sd = NULL;
+ 		for (j = 1; j < 3; j++)
+ 			rq->cpu_load[j] = 0;
+@@ -7060,17 +7328,16 @@
+ 		atomic_set(&rq->nr_iowait, 0);
+ 
+ 		for (j = 0; j < 2; j++) {
++
+ 			array = rq->arrays + j;
+-			for (k = 0; k < MAX_PRIO; k++) {
++			for (k = 0; k <= MAX_PRIO; k++)
+ 				INIT_LIST_HEAD(array->queue + k);
+-				__clear_bit(k, array->bitmap);
+-			}
+-			// delimiter for bitsearch
+-			__set_bit(MAX_PRIO, array->bitmap);
++			bitmap_zero(array->prio_bitmap, MAX_PRIO);
++			/* delimiter for bitsearch */
++			__set_bit(MAX_PRIO, array->prio_bitmap);
+ 		}
+ 		highest_cpu = i;
+ 	}
+-
+ 	set_load_weight(&init_task);
+ 
+ #ifdef CONFIG_SMP
+@@ -7125,25 +7392,25 @@
+ #ifdef CONFIG_MAGIC_SYSRQ
+ void normalize_rt_tasks(void)
+ {
+-	struct prio_array *array;
+ 	struct task_struct *g, *p;
+ 	unsigned long flags;
+ 	struct rq *rq;
++	int queued;
+ 
+ 	read_lock_irq(&tasklist_lock);
+ 
+ 	do_each_thread(g, p) {
+-		if (!rt_task(p))
++		if (!rt_task(p) && !iso_task(p))
+ 			continue;
+ 
+ 		spin_lock_irqsave(&p->pi_lock, flags);
+ 		rq = __task_rq_lock(p);
+ 
+-		array = p->array;
+-		if (array)
++		queued = task_queued(p);
++		if (queued)
+ 			deactivate_task(p, task_rq(p));
+ 		__setscheduler(p, SCHED_NORMAL, 0);
+-		if (array) {
++		if (queued) {
+ 			__activate_task(p, task_rq(p));
+ 			resched_task(rq->curr);
+ 		}
+Index: linux-2.6.22-ck1/kernel/sysctl.c
+===================================================================
+--- linux-2.6.22-ck1.orig/kernel/sysctl.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/kernel/sysctl.c	2007-07-10 14:55:23.000000000 +1000
+@@ -22,6 +22,7 @@
+ #include <linux/mm.h>
+ #include <linux/swap.h>
+ #include <linux/slab.h>
++#include <linux/swap-prefetch.h>
+ #include <linux/sysctl.h>
+ #include <linux/proc_fs.h>
+ #include <linux/capability.h>
+@@ -70,6 +71,7 @@
+ extern char core_pattern[];
+ extern int pid_max;
+ extern int min_free_kbytes;
++extern int vm_tail_largefiles;
+ extern int printk_ratelimit_jiffies;
+ extern int printk_ratelimit_burst;
+ extern int pid_max_min, pid_max_max;
+@@ -78,6 +80,10 @@
+ extern int compat_log;
+ extern int maps_protect;
+ extern int sysctl_stat_interval;
++extern int rr_interval;
++extern int sched_interactive;
++extern int sched_iso_cpu;
++extern int sched_iso_period;
+ 
+ /* this is needed for the proc_dointvec_minmax for [fs_]overflow UID and GID */
+ static int maxolduid = 65535;
+@@ -161,6 +167,14 @@
+ #endif
+ 
+ 
++/* Constants for minimum and maximum testing.
++   We use these as one-element integer vectors. */
++static int __read_mostly zero;
++static int __read_mostly one = 1;
++static int __read_mostly one_hundred = 100;
++static int __read_mostly five_thousand = 5000;
++
++
+ /* The default sysctl tables: */
+ 
+ static ctl_table root_table[] = {
+@@ -501,6 +515,47 @@
+ 		.mode		= 0444,
+ 		.proc_handler	= &proc_dointvec,
+ 	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "rr_interval",
++		.data		= &rr_interval,
++		.maxlen		= sizeof (int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec_minmax,
++		.strategy	= &sysctl_intvec,
++		.extra1		= &one,
++		.extra2		= &five_thousand,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "interactive",
++		.data		= &sched_interactive,
++		.maxlen		= sizeof(int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "iso_cpu",
++		.data		= &sched_iso_cpu,
++		.maxlen		= sizeof (int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec_minmax,
++		.strategy	= &sysctl_intvec,
++		.extra1		= &zero,
++		.extra2		= &one_hundred,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "iso_period",
++		.data		= &sched_iso_period,
++		.maxlen		= sizeof (int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec_minmax,
++		.strategy	= &sysctl_intvec,
++		.extra1		= &one,
++		.extra2		= &one_hundred,
++	},
+ #if defined(CONFIG_X86_LOCAL_APIC) && defined(CONFIG_X86)
+ 	{
+ 		.ctl_name       = KERN_UNKNOWN_NMI_PANIC,
+@@ -619,14 +674,16 @@
+ 	{ .ctl_name = 0 }
+ };
+ 
+-/* Constants for minimum and maximum testing in vm_table.
+-   We use these as one-element integer vectors. */
+-static int zero;
+-static int one_hundred = 100;
+-
+-
+ static ctl_table vm_table[] = {
+ 	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "tail_largefiles",
++		.data		= &vm_tail_largefiles,
++		.maxlen		= sizeof(int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
++	{
+ 		.ctl_name	= VM_OVERCOMMIT_MEMORY,
+ 		.procname	= "overcommit_memory",
+ 		.data		= &sysctl_overcommit_memory,
+@@ -705,16 +762,24 @@
+ 		.proc_handler	= &proc_dointvec,
+ 	},
+ 	{
+-		.ctl_name	= VM_SWAPPINESS,
+-		.procname	= "swappiness",
+-		.data		= &vm_swappiness,
+-		.maxlen		= sizeof(vm_swappiness),
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "mapped",
++		.data		= &vm_mapped,
++		.maxlen		= sizeof(vm_mapped),
+ 		.mode		= 0644,
+ 		.proc_handler	= &proc_dointvec_minmax,
+ 		.strategy	= &sysctl_intvec,
+ 		.extra1		= &zero,
+ 		.extra2		= &one_hundred,
+ 	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "hardmaplimit",
++		.data		= &vm_hardmaplimit,
++		.maxlen		= sizeof(int),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
+ #ifdef CONFIG_HUGETLB_PAGE
+ 	 {
+ 		.ctl_name	= VM_HUGETLB_PAGES,
+@@ -882,6 +947,32 @@
+ 		.extra1		= &zero,
+ 	},
+ #endif
++#ifdef CONFIG_SWAP_PREFETCH
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "swap_prefetch",
++		.data		= &swap_prefetch,
++		.maxlen		= sizeof(swap_prefetch),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "swap_prefetch_delay",
++		.data		= &swap_prefetch_delay,
++		.maxlen		= sizeof(swap_prefetch_delay),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
++	{
++		.ctl_name	= CTL_UNNUMBERED,
++		.procname	= "swap_prefetch_sleep",
++		.data		= &swap_prefetch_sleep,
++		.maxlen		= sizeof(swap_prefetch_sleep),
++		.mode		= 0644,
++		.proc_handler	= &proc_dointvec,
++	},
++#endif
+ 	{ .ctl_name = 0 }
+ };
+ 
+Index: linux-2.6.22-ck1/Documentation/sched-design.txt
+===================================================================
+--- linux-2.6.22-ck1.orig/Documentation/sched-design.txt	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/Documentation/sched-design.txt	2007-07-10 14:55:02.000000000 +1000
+@@ -1,11 +1,14 @@
+-		   Goals, Design and Implementation of the
+-		      new ultra-scalable O(1) scheduler
++ Goals, Design and Implementation of the ultra-scalable O(1) scheduler by
++ Ingo Molnar and theStaircase Deadline cpu scheduler policy designed by
++ Con Kolivas.
+ 
+ 
+-  This is an edited version of an email Ingo Molnar sent to
+-  lkml on 4 Jan 2002.  It describes the goals, design, and
+-  implementation of Ingo's new ultra-scalable O(1) scheduler.
+-  Last Updated: 18 April 2002.
++  This was originally an edited version of an email Ingo Molnar sent to
++  lkml on 4 Jan 2002.  It describes the goals, design, and implementation
++  of Ingo's ultra-scalable O(1) scheduler. It now contains a description
++  of the Staircase Deadline priority scheduler that was built on this
++  design.
++  Last Updated: Fri, 4 May 2007
+ 
+ 
+ Goal
+@@ -163,3 +166,222 @@
+ code is smaller than the old one.
+ 
+ 	Ingo
++
++
++Staircase Deadline cpu scheduler policy
++================================================
++
++Design summary
++==============
++
++A novel design which incorporates a foreground-background descending priority
++system (the staircase) via a bandwidth allocation matrix according to nice
++level.
++
++
++Features
++========
++
++A starvation free, strict fairness O(1) scalable design with interactivity
++as good as the above restrictions can provide. There is no interactivity
++estimator, no sleep/run measurements and only simple fixed accounting.
++The design has strict enough a design and accounting that task behaviour
++can be modelled and maximum scheduling latencies can be predicted by
++the virtual deadline mechanism that manages runqueues. The prime concern
++in this design is to maintain fairness at all costs determined by nice level,
++yet to maintain as good interactivity as can be allowed within the
++constraints of strict fairness.
++
++
++Design description
++==================
++
++SD works off the principle of providing each task a quota of runtime that it is
++allowed to run at a number of priority levels determined by its static priority
++(ie. its nice level). If the task uses up its quota it has its priority
++decremented to the next level determined by a priority matrix. Once every
++runtime quota has been consumed of every priority level, a task is queued on the
++"expired" array. When no other tasks exist with quota, the expired array is
++activated and fresh quotas are handed out. This is all done in O(1).
++
++Design details
++==============
++
++Each task keeps a record of its own entitlement of cpu time. Most of the rest of
++these details apply to non-realtime tasks as rt task management is straight
++forward.
++
++Each runqueue keeps a record of what major epoch it is up to in the
++rq->prio_rotation field which is incremented on each major epoch. It also
++keeps a record of the current prio_level for each static priority task.
++
++Each task keeps a record of what major runqueue epoch it was last running
++on in p->rotation. It also keeps a record of what priority levels it has
++already been allocated quota from during this epoch in a bitmap p->bitmap.
++
++The only tunable that determines all other details is the RR_INTERVAL. This
++is set to 8ms, and is scaled gently upwards with more cpus. This value is
++tunable via a /proc interface.
++
++All tasks are initially given a quota based on RR_INTERVAL. This is equal to
++RR_INTERVAL between nice values of -6 and 0, half that size above nice 0, and
++progressively larger for nice values from -1 to -20. This is assigned to
++p->quota and only changes with changes in nice level.
++
++As a task is first queued, it checks in recalc_task_prio to see if it has run at
++this runqueue's current priority rotation. If it has not, it will have its
++p->prio level set according to the first slot in a "priority matrix" and will be
++given a p->time_slice equal to the p->quota, and has its allocation bitmap bit
++set in p->bitmap for this prio level. It is then queued on the current active
++priority array.
++
++If a task has already been running during this major epoch, and it has
++p->time_slice left and the rq->prio_quota for the task's p->prio still
++has quota, it will be placed back on the active array, but no more quota
++will be added.
++
++If a task has been running during this major epoch, but does not have
++p->time_slice left, it will find the next lowest priority in its bitmap that it
++has not been allocated quota from. It then gets the a full quota in
++p->time_slice. It is then queued on the current active priority array at the
++newly determined lower priority.
++
++If a task has been running during this major epoch, and does not have
++any entitlement left in p->bitmap and no time_slice left, it will have its
++bitmap cleared, and be queued at its best prio again, but on the expired
++priority array.
++
++When a task is queued, it has its relevant bit set in the array->prio_bitmap.
++
++p->time_slice is stored in nanosconds and is updated via update_cpu_clock on
++schedule() and scheduler_tick. If p->time_slice is below zero then the
++recalc_task_prio is readjusted and the task rescheduled.
++
++
++Priority Matrix
++===============
++
++In order to minimise the latencies between tasks of different nice levels
++running concurrently, the dynamic priority slots where different nice levels
++are queued are dithered instead of being sequential. What this means is that
++there are 40 priority slots where a task may run during one major rotation,
++and the allocation of slots is dependant on nice level. In the
++following table, a zero represents a slot where the task may run.
++
++PRIORITY:0..................20.................39
++nice -20 0000000000000000000000000000000000000000
++nice -10 1000100010001000100010001000100010010000
++nice   0 1010101010101010101010101010101010101010
++nice   5 1011010110110101101101011011010110110110
++nice  10 1110111011101110111011101110111011101110
++nice  15 1111111011111110111111101111111011111110
++nice  19 1111111111111111111111111111111111111110
++
++As can be seen, a nice -20 task runs in every priority slot whereas a nice 19
++task only runs one slot per major rotation. This dithered table allows for the
++smallest possible maximum latencies between tasks of varying nice levels, thus
++allowing vastly different nice levels to be used.
++
++SCHED_BATCH tasks are managed slightly differently, receiving only the top
++slots from its priority bitmap giving it equal cpu as SCHED_NORMAL, but
++slightly higher latencies.
++
++
++Modelling deadline behaviour
++============================
++
++As the accounting in this design is hard and not modified by sleep average
++calculations or interactivity modifiers, it is possible to accurately
++predict the maximum latency that a task may experience under different
++conditions. This is a virtual deadline mechanism enforced by mandatory
++timeslice expiration and not outside bandwidth measurement.
++
++The maximum duration a task can run during one major epoch is determined by its
++nice value. Nice 0 tasks can run at 19 different priority levels for RR_INTERVAL
++duration during each epoch. Nice 10 tasks can run at 9 priority levels for each
++epoch, and so on. The table in the priority matrix above demonstrates how this
++is enforced.
++
++Therefore the maximum duration a runqueue epoch can take is determined by
++the number of tasks running, and their nice level. After that, the maximum
++duration it can take before a task can wait before it get scheduled is
++determined by the position of its first slot on the matrix.
++
++In the following examples, these are _worst case scenarios_ and would rarely
++occur, but can be modelled nonetheless to determine the maximum possible
++latency.
++
++So for example, if two nice 0 tasks are running, and one has just expired as
++another is activated for the first time receiving a full quota for this
++runqueue rotation, the first task will wait:
++
++nr_tasks * max_duration + nice_difference * rr_interval
++1 * 19 * RR_INTERVAL + 0 = 152ms
++
++In the presence of a nice 10 task, a nice 0 task would wait a maximum of
++1 * 10 * RR_INTERVAL + 0 = 80ms
++
++In the presence of a nice 0 task, a nice 10 task would wait a maximum of
++1 * 19 * RR_INTERVAL + 1 * RR_INTERVAL = 160ms
++
++More useful than these values, though, are the average latencies which are
++a matter of determining the average distance between priority slots of
++different nice values and multiplying them by the tasks' quota. For example
++in the presence of a nice -10 task, a nice 0 task will wait either one or
++two slots. Given that nice -10 tasks have a quota 2.5 times the RR_INTERVAL,
++this means the latencies will alternate between 2.5 and 5 RR_INTERVALs or
++20 and 40ms respectively (on uniprocessor at 1000HZ).
++
++
++Achieving interactivity
++=======================
++
++A requirement of this scheduler design was to achieve good interactivity
++despite being a completely fair deadline based design. The disadvantage of
++designs that try to achieve interactivity is that they usually do so at
++the expense of maintaining fairness. As cpu speeds increase, the requirement
++for some sort of metered unfairness towards interactive tasks becomes a less
++desirable phenomenon, but low latency and fairness remains mandatory to
++good interactive performance.
++
++This design relies on the fact that interactive tasks, by their nature,
++sleep often. Most fair scheduling designs end up penalising such tasks
++indirectly giving them less than their fair possible share because of the
++sleep, and have to use a mechanism of bonusing their priority to offset
++this based on the duration they sleep. This becomes increasingly inaccurate
++as the number of running tasks rises and more tasks spend time waiting on
++runqueues rather than sleeping, and it is impossible to tell whether the
++task that's waiting on a runqueue only intends to run for a short period and
++then sleep again after than runqueue wait. Furthermore, all such designs rely
++on a period of time to pass to accumulate some form of statistic on the task
++before deciding on how much to give them preference. The shorter this period,
++the more rapidly bursts of cpu ruin the interactive tasks behaviour. The
++longer this period, the longer it takes for interactive tasks to get low
++scheduling latencies and fair cpu.
++
++This design does not measure sleep time at all. Interactive tasks that sleep
++often will wake up having consumed very little if any of their quota for
++the current major priority rotation. The longer they have slept, the less
++likely they are to even be on the current major priority rotation. Once
++woken up, though, they get to use up a their full quota for that epoch,
++whether part of a quota remains or a full quota. Overall, however, they
++can still only run as much cpu time for that epoch as any other task of the
++same nice level. This means that two tasks behaving completely differently
++from fully cpu bound to waking/sleeping extremely frequently will still
++get the same quota of cpu, but the latter will be using its quota for that
++epoch in bursts rather than continuously. This guarantees that interactive
++tasks get the same amount of cpu as cpu bound ones.
++
++The other requirement of interactive tasks is also to obtain low latencies
++for when they are scheduled. Unlike fully cpu bound tasks and the maximum
++latencies possible described in the modelling deadline behaviour section
++above, tasks that sleep will wake up with quota available usually at the
++current runqueue's priority_level or better. This means that the most latency
++they are likely to see is one RR_INTERVAL, and often they will preempt the
++current task if it is not of a sleeping nature. This then guarantees very
++low latency for interactive tasks, and the lowest latencies for the least
++cpu bound tasks.
++
++
++Fri, 4 May 2007
++Con Kolivas <kernel@kolivas.org>
+Index: linux-2.6.22-ck1/Documentation/sysctl/kernel.txt
+===================================================================
+--- linux-2.6.22-ck1.orig/Documentation/sysctl/kernel.txt	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/Documentation/sysctl/kernel.txt	2007-07-10 14:55:20.000000000 +1000
+@@ -25,6 +25,9 @@
+ - domainname
+ - hostname
+ - hotplug
++- interactive
++- iso_cpu
++- iso_period
+ - java-appletviewer           [ binfmt_java, obsolete ]
+ - java-interpreter            [ binfmt_java, obsolete ]
+ - kstack_depth_to_print       [ X86 only ]
+@@ -43,6 +46,7 @@
+ - printk
+ - real-root-dev               ==> Documentation/initrd.txt
+ - reboot-cmd                  [ SPARC only ]
++- rr_interval
+ - rtsig-max
+ - rtsig-nr
+ - sem
+@@ -164,6 +168,40 @@
+ 
+ ==============================================================
+ 
++interactive:
++
++The staircase-deadline cpu scheduler can be set in either purely
++forward-looking mode for absolutely rigid fairness and cpu distribution
++according to nice level, or it can allow a small per-process history
++to smooth out cpu usage perturbations common in interactive tasks by
++enabling this sysctl. While small fairness issues can arise with this
++enabled, overall fairness is usually still strongly maintained and
++starvation is never possible. Enabling this can significantly smooth
++out 3d graphics and games.
++
++Default value is 1 (enabled).
++
++==============================================================
++
++iso_cpu:
++
++This sets the percentage cpu that the unprivileged SCHED_ISO tasks can
++run effectively at realtime priority, averaged over a rolling iso_period
++seconds.
++
++Set to 80 (percent) by default.
++
++==============================================================
++
++iso_period:
++
++This sets the number of seconds over which SCHED_ISO cpu usage is averaged
++to see if it exceeds its allocated cpu bandwidth.
++
++Set to 5 (seconds) by default.
++
++==============================================================
++
+ l2cr: (PPC only)
+ 
+ This flag controls the L2 cache of G3 processor boards. If
+@@ -288,6 +326,19 @@
+ 
+ ==============================================================
+ 
++rr_interval:
++
++This is the smallest duration that any cpu process scheduling unit
++will run for. Increasing this value can increase throughput of cpu
++bound tasks substantially but at the expense of increased latencies
++overall. This value is in milliseconds and the default value chosen
++depends on the number of cpus available at scheduler initialisation
++with a minimum of 8.
++
++Valid values are from 1-5000.
++
++==============================================================
++
+ rtsig-max & rtsig-nr:
+ 
+ The file rtsig-max can be used to tune the maximum number
+Index: linux-2.6.22-ck1/fs/pipe.c
+===================================================================
+--- linux-2.6.22-ck1.orig/fs/pipe.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/fs/pipe.c	2007-07-10 14:55:02.000000000 +1000
+@@ -41,12 +41,7 @@
+ {
+ 	DEFINE_WAIT(wait);
+ 
+-	/*
+-	 * Pipes are system-local resources, so sleeping on them
+-	 * is considered a noninteractive wait:
+-	 */
+-	prepare_to_wait(&pipe->wait, &wait,
+-			TASK_INTERRUPTIBLE | TASK_NONINTERACTIVE);
++	prepare_to_wait(&pipe->wait, &wait, TASK_INTERRUPTIBLE);
+ 	if (pipe->inode)
+ 		mutex_unlock(&pipe->inode->i_mutex);
+ 	schedule();
+Index: linux-2.6.22-ck1/fs/proc/array.c
+===================================================================
+--- linux-2.6.22-ck1.orig/fs/proc/array.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/fs/proc/array.c	2007-07-10 14:55:02.000000000 +1000
+@@ -165,7 +165,6 @@
+ 	rcu_read_lock();
+ 	buffer += sprintf(buffer,
+ 		"State:\t%s\n"
+-		"SleepAVG:\t%lu%%\n"
+ 		"Tgid:\t%d\n"
+ 		"Pid:\t%d\n"
+ 		"PPid:\t%d\n"
+@@ -173,7 +172,6 @@
+ 		"Uid:\t%d\t%d\t%d\t%d\n"
+ 		"Gid:\t%d\t%d\t%d\t%d\n",
+ 		get_task_state(p),
+-		(p->sleep_avg/1024)*100/(1020000000/1024),
+ 	       	p->tgid, p->pid,
+ 	       	pid_alive(p) ? rcu_dereference(p->real_parent)->tgid : 0,
+ 		pid_alive(p) && p->ptrace ? rcu_dereference(p->parent)->pid : 0,
+Index: linux-2.6.22-ck1/include/linux/init_task.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/init_task.h	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/init_task.h	2007-07-10 14:55:20.000000000 +1000
+@@ -125,13 +125,15 @@
+ 	.prio		= MAX_PRIO-20,					\
+ 	.static_prio	= MAX_PRIO-20,					\
+ 	.normal_prio	= MAX_PRIO-20,					\
++	.rotation	= 0,						\
+ 	.policy		= SCHED_NORMAL,					\
+ 	.cpus_allowed	= CPU_MASK_ALL,					\
+ 	.mm		= NULL,						\
+ 	.active_mm	= &init_mm,					\
+ 	.run_list	= LIST_HEAD_INIT(tsk.run_list),			\
+ 	.ioprio		= 0,						\
+-	.time_slice	= HZ,						\
++	.time_slice	= 1000000000,						\
++	.quota		= 1000000000,						\
+ 	.tasks		= LIST_HEAD_INIT(tsk.tasks),			\
+ 	.ptrace_children= LIST_HEAD_INIT(tsk.ptrace_children),		\
+ 	.ptrace_list	= LIST_HEAD_INIT(tsk.ptrace_list),		\
+@@ -158,6 +160,7 @@
+ 		.signal = {{0}}},					\
+ 	.blocked	= {{0}},					\
+ 	.alloc_lock	= __SPIN_LOCK_UNLOCKED(tsk.alloc_lock),		\
++	.mutexes_held	= 0,						\
+ 	.journal_info	= NULL,						\
+ 	.cpu_timers	= INIT_CPU_TIMERS(tsk.cpu_timers),		\
+ 	.fs_excl	= ATOMIC_INIT(0),				\
+Index: linux-2.6.22-ck1/kernel/softirq.c
+===================================================================
+--- linux-2.6.22-ck1.orig/kernel/softirq.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/kernel/softirq.c	2007-07-10 14:55:02.000000000 +1000
+@@ -488,7 +488,7 @@
+ 
+ static int ksoftirqd(void * __bind_cpu)
+ {
+-	set_user_nice(current, 19);
++	set_user_nice(current, 15);
+ 	current->flags |= PF_NOFREEZE;
+ 
+ 	set_current_state(TASK_INTERRUPTIBLE);
+Index: linux-2.6.22-ck1/kernel/workqueue.c
+===================================================================
+--- linux-2.6.22-ck1.orig/kernel/workqueue.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/kernel/workqueue.c	2007-07-10 14:55:02.000000000 +1000
+@@ -285,8 +285,6 @@
+ 	if (!cwq->wq->freezeable)
+ 		current->flags |= PF_NOFREEZE;
+ 
+-	set_user_nice(current, -5);
+-
+ 	for (;;) {
+ 		prepare_to_wait(&cwq->more_work, &wait, TASK_INTERRUPTIBLE);
+ 		if (!freezing(current) &&
+Index: linux-2.6.22-ck1/kernel/kthread.c
+===================================================================
+--- linux-2.6.22-ck1.orig/kernel/kthread.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/kernel/kthread.c	2007-07-10 14:55:02.000000000 +1000
+@@ -223,7 +223,6 @@
+ 
+ 	ignore_signals(tsk);
+ 
+-	set_user_nice(tsk, -5);
+ 	set_cpus_allowed(tsk, CPU_MASK_ALL);
+ }
+ 
+Index: linux-2.6.22-ck1/kernel/fork.c
+===================================================================
+--- linux-2.6.22-ck1.orig/kernel/fork.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/kernel/fork.c	2007-07-10 14:55:20.000000000 +1000
+@@ -1063,6 +1063,7 @@
+ 	p->io_context = NULL;
+ 	p->io_wait = NULL;
+ 	p->audit_context = NULL;
++	p->mutexes_held = 0;
+ 	cpuset_fork(p);
+ #ifdef CONFIG_NUMA
+  	p->mempolicy = mpol_copy(p->mempolicy);
+Index: linux-2.6.22-ck1/kernel/mutex.c
+===================================================================
+--- linux-2.6.22-ck1.orig/kernel/mutex.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/kernel/mutex.c	2007-07-10 14:55:20.000000000 +1000
+@@ -60,6 +60,16 @@
+ static void fastcall noinline __sched
+ __mutex_lock_slowpath(atomic_t *lock_count);
+ 
++static inline void inc_mutex_count(void)
++{
++	current->mutexes_held++;
++}
++
++static inline void dec_mutex_count(void)
++{
++	current->mutexes_held--;
++}
++
+ /***
+  * mutex_lock - acquire the mutex
+  * @lock: the mutex to be acquired
+@@ -89,6 +99,7 @@
+ 	 * 'unlocked' into 'locked' state.
+ 	 */
+ 	__mutex_fastpath_lock(&lock->count, __mutex_lock_slowpath);
++	inc_mutex_count();
+ }
+ 
+ EXPORT_SYMBOL(mutex_lock);
+@@ -114,6 +125,7 @@
+ 	 * into 'unlocked' state:
+ 	 */
+ 	__mutex_fastpath_unlock(&lock->count, __mutex_unlock_slowpath);
++	dec_mutex_count();
+ }
+ 
+ EXPORT_SYMBOL(mutex_unlock);
+@@ -283,9 +295,14 @@
+  */
+ int fastcall __sched mutex_lock_interruptible(struct mutex *lock)
+ {
++	int ret;
++
+ 	might_sleep();
+-	return __mutex_fastpath_lock_retval
++	ret = __mutex_fastpath_lock_retval
+ 			(&lock->count, __mutex_lock_interruptible_slowpath);
++	if (likely(!ret))
++		inc_mutex_count();
++	return ret;
+ }
+ 
+ EXPORT_SYMBOL(mutex_lock_interruptible);
+@@ -340,8 +357,12 @@
+  */
+ int fastcall __sched mutex_trylock(struct mutex *lock)
+ {
+-	return __mutex_fastpath_trylock(&lock->count,
++	int ret = __mutex_fastpath_trylock(&lock->count,
+ 					__mutex_trylock_slowpath);
++
++	if (likely(ret))
++		inc_mutex_count();
++	return ret;
+ }
+ 
+ EXPORT_SYMBOL(mutex_trylock);
+Index: linux-2.6.22-ck1/block/cfq-iosched.c
+===================================================================
+--- linux-2.6.22-ck1.orig/block/cfq-iosched.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/block/cfq-iosched.c	2007-07-10 14:55:21.000000000 +1000
+@@ -1276,10 +1276,12 @@
+ 			printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
+ 		case IOPRIO_CLASS_NONE:
+ 			/*
+-			 * no prio set, place us in the middle of the BE classes
++			 * Select class and ioprio according to policy and nice
+ 			 */
++			cfqq->ioprio_class = task_policy_ioprio_class(tsk);
+ 			cfqq->ioprio = task_nice_ioprio(tsk);
+-			cfqq->ioprio_class = IOPRIO_CLASS_BE;
++			if (cfqq->ioprio_class == IOPRIO_CLASS_IDLE)
++				cfq_clear_cfqq_idle_window(cfqq);
+ 			break;
+ 		case IOPRIO_CLASS_RT:
+ 			cfqq->ioprio = task_ioprio(tsk);
+Index: linux-2.6.22-ck1/include/linux/ioprio.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/ioprio.h	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/ioprio.h	2007-07-10 14:55:21.000000000 +1000
+@@ -22,7 +22,7 @@
+  * class, the default for any process. IDLE is the idle scheduling class, it
+  * is only served when no one else is using the disk.
+  */
+-enum {
++enum ioprio_class {
+ 	IOPRIO_CLASS_NONE,
+ 	IOPRIO_CLASS_RT,
+ 	IOPRIO_CLASS_BE,
+@@ -51,8 +51,25 @@
+ 	return IOPRIO_PRIO_DATA(task->ioprio);
+ }
+ 
++static inline enum ioprio_class
++	task_policy_ioprio_class(struct task_struct *task)
++{
++	if (rt_task(task))
++		return IOPRIO_CLASS_RT;
++	if (idleprio_task(task))
++		return IOPRIO_CLASS_IDLE;
++	return IOPRIO_CLASS_BE;
++}
++
+ static inline int task_nice_ioprio(struct task_struct *task)
+ {
++	if (rt_task(task))
++		return (MAX_RT_PRIO - task->rt_priority) * IOPRIO_BE_NR /
++			(MAX_RT_PRIO + 1);
++	if (iso_task(task))
++		return 0;
++	if (idleprio_task(task))
++		return IOPRIO_BE_NR - 1;
+ 	return (task_nice(task) + 20) / 5;
+ }
+ 
+Index: linux-2.6.22-ck1/Documentation/sysctl/vm.txt
+===================================================================
+--- linux-2.6.22-ck1.orig/Documentation/sysctl/vm.txt	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/Documentation/sysctl/vm.txt	2007-07-10 14:55:23.000000000 +1000
+@@ -22,6 +22,8 @@
+ - dirty_background_ratio
+ - dirty_expire_centisecs
+ - dirty_writeback_centisecs
++- hardmaplimit
++- mapped
+ - max_map_count
+ - min_free_kbytes
+ - laptop_mode
+@@ -31,12 +33,15 @@
+ - min_unmapped_ratio
+ - min_slab_ratio
+ - panic_on_oom
++- swap_prefetch
++- swap_prefetch_delay
++- swap_prefetch_sleep
+ 
+ ==============================================================
+ 
+ dirty_ratio, dirty_background_ratio, dirty_expire_centisecs,
+ dirty_writeback_centisecs, vfs_cache_pressure, laptop_mode,
+-block_dump, swap_token_timeout, drop-caches:
++block_dump, swap_token_timeout, drop-caches, tail_largefiles:
+ 
+ See Documentation/filesystems/proc.txt
+ 
+@@ -86,6 +91,27 @@
+ 
+ ==============================================================
+ 
++hardmaplimit:
++
++This flag makes the vm adhere to the mapped value as closely as possible
++except in the most extreme vm stress where doing so would provoke an out
++of memory condition (see mapped below).
++
++Enabled by default.
++
++==============================================================
++
++mapped:
++
++This is the percentage ram that is filled with mapped pages (applications)
++before the vm will start reclaiming mapped pages by moving them to swap.
++It is altered by the relative stress of the vm at the time so is not
++strictly adhered to to prevent provoking out of memory kills.
++
++Set to 66 by default.
++
++==============================================================
++
+ max_map_count:
+ 
+ This file contains the maximum number of memory map areas a process
+@@ -216,3 +242,37 @@
+ The default value is 0.
+ 1 and 2 are for failover of clustering. Please select either
+ according to your policy of failover.
++
++==============================================================
++
++swap_prefetch
++
++This enables or disables the swap prefetching feature. When the virtual
++memory subsystem has been extremely idle for at least swap_prefetch_sleep
++seconds it will start copying back pages from swap into the swapcache and keep
++a copy in swap. Valid values are 0 - 3. A value of 0 disables swap
++prefetching, 1 enables it unless laptop_mode is enabled, 2 enables it in the
++presence of laptop_mode, and 3 enables it unconditionally, ignoring whether
++the system is idle or not. If set to 0, swap prefetch wil not even try to keep
++record of ram swapped out to have the most minimal impact on performance.
++
++The default value is 1.
++
++==============================================================
++
++swap_prefetch_delay
++
++This is the time in seconds that swap prefetching is delayed upon finding
++the system is not idle (ie the vm is busy or non-niced cpu load is present).
++
++The default value is 1.
++
++==============================================================
++
++swap_prefetch_sleep
++
++This is the time in seconds that the swap prefetch kernel thread is put to
++sleep for when the ram is found to be full and it is unable to prefetch
++further.
++
++The default value is 5.
+Index: linux-2.6.22-ck1/include/linux/swap.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/swap.h	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/swap.h	2007-07-10 14:55:22.000000000 +1000
+@@ -180,6 +180,7 @@
+ /* linux/mm/swap.c */
+ extern void FASTCALL(lru_cache_add(struct page *));
+ extern void FASTCALL(lru_cache_add_active(struct page *));
++extern void FASTCALL(lru_cache_add_tail(struct page *));
+ extern void FASTCALL(activate_page(struct page *));
+ extern void FASTCALL(mark_page_accessed(struct page *));
+ extern void lru_add_drain(void);
+@@ -188,9 +189,11 @@
+ extern void swap_setup(void);
+ 
+ /* linux/mm/vmscan.c */
+-extern unsigned long try_to_free_pages(struct zone **, gfp_t);
++extern unsigned long try_to_free_pages(struct zone **, gfp_t,
++				       struct task_struct *p);
+ extern unsigned long shrink_all_memory(unsigned long nr_pages);
+-extern int vm_swappiness;
++extern int vm_mapped;
++extern int vm_hardmaplimit;
+ extern int remove_mapping(struct address_space *mapping, struct page *page);
+ extern long vm_total_pages;
+ 
+@@ -237,6 +240,7 @@
+ extern struct page * lookup_swap_cache(swp_entry_t);
+ extern struct page * read_swap_cache_async(swp_entry_t, struct vm_area_struct *vma,
+ 					   unsigned long addr);
++extern int add_to_swap_cache(struct page *page, swp_entry_t entry);
+ /* linux/mm/swapfile.c */
+ extern long total_swap_pages;
+ extern unsigned int nr_swapfiles;
+Index: linux-2.6.22-ck1/init/Kconfig
+===================================================================
+--- linux-2.6.22-ck1.orig/init/Kconfig	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/init/Kconfig	2007-07-10 14:55:22.000000000 +1000
+@@ -105,6 +105,28 @@
+ 	  used to provide more virtual memory than the actual RAM present
+ 	  in your computer.  If unsure say Y.
+ 
++config SWAP_PREFETCH
++	bool "Support for prefetching swapped memory"
++	depends on SWAP
++	default y
++	---help---
++	  This option will allow the kernel to prefetch swapped memory pages
++	  when idle. The pages will be kept on both swap and in swap_cache
++	  thus avoiding the need for further I/O if either ram or swap space
++	  is required.
++
++	  What this will do on workstations is slowly bring back applications
++	  that have swapped out after memory intensive workloads back into
++	  physical ram if you have free ram at a later stage and the machine
++	  is relatively idle. This means that when you come back to your
++	  computer after leaving it idle for a while, applications will come
++	  to life faster. Note that your swap usage will appear to increase
++	  but these are cached pages, can be dropped freely by the vm, and it
++	  should stabilise around 50% swap usage maximum.
++
++	  Workstations and multiuser workstation servers will most likely want
++	  to say Y.
++
+ config SYSVIPC
+ 	bool "System V IPC"
+ 	---help---
+Index: linux-2.6.22-ck1/mm/Makefile
+===================================================================
+--- linux-2.6.22-ck1.orig/mm/Makefile	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/mm/Makefile	2007-07-10 14:55:22.000000000 +1000
+@@ -17,6 +17,7 @@
+ obj-y			+= bounce.o
+ endif
+ obj-$(CONFIG_SWAP)	+= page_io.o swap_state.o swapfile.o thrash.o
++obj-$(CONFIG_SWAP_PREFETCH) += swap_prefetch.o
+ obj-$(CONFIG_HUGETLBFS)	+= hugetlb.o
+ obj-$(CONFIG_NUMA) 	+= mempolicy.o
+ obj-$(CONFIG_SPARSEMEM)	+= sparse.o
+Index: linux-2.6.22-ck1/mm/swap.c
+===================================================================
+--- linux-2.6.22-ck1.orig/mm/swap.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/mm/swap.c	2007-07-10 14:55:23.000000000 +1000
+@@ -17,6 +17,7 @@
+ #include <linux/sched.h>
+ #include <linux/kernel_stat.h>
+ #include <linux/swap.h>
++#include <linux/swap-prefetch.h>
+ #include <linux/mman.h>
+ #include <linux/pagemap.h>
+ #include <linux/pagevec.h>
+@@ -176,6 +177,7 @@
+  */
+ static DEFINE_PER_CPU(struct pagevec, lru_add_pvecs) = { 0, };
+ static DEFINE_PER_CPU(struct pagevec, lru_add_active_pvecs) = { 0, };
++static DEFINE_PER_CPU(struct pagevec, lru_add_tail_pvecs) = { 0, };
+ 
+ void fastcall lru_cache_add(struct page *page)
+ {
+@@ -197,6 +199,31 @@
+ 	put_cpu_var(lru_add_active_pvecs);
+ }
+ 
++static void __pagevec_lru_add_tail(struct pagevec *pvec)
++{
++	int i;
++	struct zone *zone = NULL;
++
++	for (i = 0; i < pagevec_count(pvec); i++) {
++		struct page *page = pvec->pages[i];
++		struct zone *pagezone = page_zone(page);
++
++		if (pagezone != zone) {
++			if (zone)
++				spin_unlock_irq(&zone->lru_lock);
++			zone = pagezone;
++			spin_lock_irq(&zone->lru_lock);
++		}
++		BUG_ON(PageLRU(page));
++		SetPageLRU(page);
++		add_page_to_inactive_list_tail(zone, page);
++	}
++	if (zone)
++		spin_unlock_irq(&zone->lru_lock);
++	release_pages(pvec->pages, pvec->nr, pvec->cold);
++	pagevec_reinit(pvec);
++}
++
+ static void __lru_add_drain(int cpu)
+ {
+ 	struct pagevec *pvec = &per_cpu(lru_add_pvecs, cpu);
+@@ -207,6 +234,9 @@
+ 	pvec = &per_cpu(lru_add_active_pvecs, cpu);
+ 	if (pagevec_count(pvec))
+ 		__pagevec_lru_add_active(pvec);
++	pvec = &per_cpu(lru_add_tail_pvecs, cpu);
++	if (pagevec_count(pvec))
++		__pagevec_lru_add_tail(pvec);
+ }
+ 
+ void lru_add_drain(void)
+@@ -403,6 +433,20 @@
+ }
+ 
+ /*
++ * Function used uniquely to put pages back to the lru at the end of the
++ * inactive list to preserve the lru order.
++ */
++void fastcall lru_cache_add_tail(struct page *page)
++{
++	struct pagevec *pvec = &get_cpu_var(lru_add_tail_pvecs);
++
++	page_cache_get(page);
++	if (!pagevec_add(pvec, page))
++		__pagevec_lru_add_tail(pvec);
++	put_cpu_var(lru_add_pvecs);
++}
++
++/*
+  * Try to drop buffers from the pages in a pagevec
+  */
+ void pagevec_strip(struct pagevec *pvec)
+@@ -514,6 +558,9 @@
+ 	 * Right now other parts of the system means that we
+ 	 * _really_ don't want to cluster much more
+ 	 */
++
++	prepare_swap_prefetch();
++
+ #ifdef CONFIG_HOTPLUG_CPU
+ 	hotcpu_notifier(cpu_swap_callback, 0);
+ #endif
+Index: linux-2.6.22-ck1/mm/swap_prefetch.c
+===================================================================
+--- /dev/null	1970-01-01 00:00:00.000000000 +0000
++++ linux-2.6.22-ck1/mm/swap_prefetch.c	2007-07-10 14:55:22.000000000 +1000
+@@ -0,0 +1,542 @@
++/*
++ * linux/mm/swap_prefetch.c
++ *
++ * Copyright (C) 2005-2007 Con Kolivas
++ *
++ * Written by Con Kolivas <kernel@kolivas.org>
++ *
++ * This program is free software; you can redistribute it and/or modify
++ * it under the terms of the GNU General Public License version 2 as
++ * published by the Free Software Foundation.
++ */
++
++#include <linux/fs.h>
++#include <linux/mm.h>
++#include <linux/swap.h>
++#include <linux/swap-prefetch.h>
++#include <linux/ioprio.h>
++#include <linux/kthread.h>
++#include <linux/pagemap.h>
++#include <linux/syscalls.h>
++#include <linux/writeback.h>
++#include <linux/vmstat.h>
++#include <linux/freezer.h>
++
++/*
++ * sysctls:
++ * swap_prefetch:	0. Disable swap prefetching
++ *			1. Prefetch only when idle and not with laptop_mode
++ *			2. Prefetch when idle and with laptop_mode
++ *			3. Prefetch at all times.
++ * swap_prefetch_delay:	Number of seconds to delay prefetching when system
++ *			is not idle.
++ * swap_prefetch_sleep:	Number of seconds to put kprefetchd to sleep when
++ *			unable to prefetch.
++ */
++int swap_prefetch __read_mostly = 1;
++int swap_prefetch_delay __read_mostly = 1;
++int swap_prefetch_sleep __read_mostly = 5;
++
++#define PREFETCH_DELAY		(HZ * swap_prefetch_delay)
++#define PREFETCH_SLEEP		((HZ * swap_prefetch_sleep) ? : 1)
++
++struct swapped_root {
++	unsigned long		busy;		/* vm busy */
++	spinlock_t		lock;		/* protects all data */
++	struct list_head	list;		/* MRU list of swapped pages */
++	struct radix_tree_root	swap_tree;	/* Lookup tree of pages */
++	unsigned int		count;		/* Number of entries */
++	unsigned int		maxcount;	/* Maximum entries allowed */
++	struct kmem_cache	*cache;		/* Of struct swapped_entry */
++};
++
++static struct swapped_root swapped = {
++	.lock		= SPIN_LOCK_UNLOCKED,
++	.list  		= LIST_HEAD_INIT(swapped.list),
++	.swap_tree	= RADIX_TREE_INIT(GFP_ATOMIC),
++};
++
++static struct task_struct *kprefetchd_task;
++
++/*
++ * We check to see no part of the vm is busy. If it is this will interrupt
++ * trickle_swap and wait another PREFETCH_DELAY. Purposefully racy.
++ */
++inline void delay_swap_prefetch(void)
++{
++	if (!test_bit(0, &swapped.busy))
++		__set_bit(0, &swapped.busy);
++}
++
++/*
++ * If laptop_mode is enabled don't prefetch to avoid hard drives
++ * doing unnecessary spin-ups unless swap_prefetch is explicitly
++ * set to a higher value.
++ */
++static inline int prefetch_enabled(void)
++{
++	if (swap_prefetch <= laptop_mode)
++		return 0;
++	return 1;
++}
++
++static int kprefetchd_awake;
++
++/*
++ * Drop behind accounting which keeps a list of the most recently used swap
++ * entries. Entries are removed lazily by kprefetchd.
++ */
++void add_to_swapped_list(struct page *page)
++{
++	struct swapped_entry *entry;
++	unsigned long index, flags;
++
++	if (!prefetch_enabled())
++		goto out;
++
++	spin_lock_irqsave(&swapped.lock, flags);
++	if (swapped.count >= swapped.maxcount) {
++		/*
++		 * Once the number of entries exceeds maxcount we start
++		 * removing the least recently used entries.
++		 */
++		entry = list_entry(swapped.list.next,
++			struct swapped_entry, swapped_list);
++		radix_tree_delete(&swapped.swap_tree, entry->swp_entry.val);
++		list_del(&entry->swapped_list);
++		swapped.count--;
++	} else {
++		entry = kmem_cache_alloc(swapped.cache, GFP_ATOMIC);
++		if (unlikely(!entry))
++			/* bad, can't allocate more mem */
++			goto out_locked;
++	}
++
++	index = page_private(page);
++	entry->swp_entry.val = index;
++	/*
++	 * On numa we need to store the node id to ensure that we prefetch to
++	 * the same node it came from.
++	 */
++	store_swap_entry_node(entry, page);
++
++	if (likely(!radix_tree_insert(&swapped.swap_tree, index, entry))) {
++		list_add(&entry->swapped_list, &swapped.list);
++		swapped.count++;
++	} else
++		kmem_cache_free(swapped.cache, entry);
++
++out_locked:
++	spin_unlock_irqrestore(&swapped.lock, flags);
++out:
++	if (!kprefetchd_awake)
++		wake_up_process(kprefetchd_task);
++	return;
++}
++
++/*
++ * Removes entries from the swapped_list. The radix tree allows us to quickly
++ * look up the entry from the index without having to iterate over the whole
++ * list.
++ */
++static void remove_from_swapped_list(const unsigned long index)
++{
++	struct swapped_entry *entry;
++	unsigned long flags;
++
++	spin_lock_irqsave(&swapped.lock, flags);
++	entry = radix_tree_delete(&swapped.swap_tree, index);
++	if (likely(entry)) {
++		list_del(&entry->swapped_list);
++		swapped.count--;
++		kmem_cache_free(swapped.cache, entry);
++	}
++	spin_unlock_irqrestore(&swapped.lock, flags);
++}
++
++enum trickle_return {
++	TRICKLE_SUCCESS,
++	TRICKLE_FAILED,
++	TRICKLE_DELAY,
++};
++
++struct node_stats {
++	/* Free ram after a cycle of prefetching */
++	unsigned long	last_free;
++	/* Free ram on this cycle of checking prefetch_suitable */
++	unsigned long	current_free;
++	/* The amount of free ram before we start prefetching */
++	unsigned long	highfree[MAX_NR_ZONES];
++	/* The amount of free ram where we will stop prefetching */
++	unsigned long	lowfree[MAX_NR_ZONES];
++	/* highfree or lowfree depending on whether we've hit a watermark */
++	unsigned long	*pointfree[MAX_NR_ZONES];
++};
++
++/*
++ * prefetch_stats stores the free ram data of each node and this is used to
++ * determine if a node is suitable for prefetching into.
++ */
++struct prefetch_stats {
++	/* Which nodes are currently suited to prefetching */
++	nodemask_t	prefetch_nodes;
++	/* Total pages we've prefetched on this wakeup of kprefetchd */
++	unsigned long	prefetched_pages;
++	struct node_stats node[MAX_NUMNODES];
++};
++
++static struct prefetch_stats sp_stat;
++
++/*
++ * This tries to read a swp_entry_t into swap cache for swap prefetching.
++ * If it returns TRICKLE_DELAY we should delay further prefetching.
++ */
++static enum trickle_return trickle_swap_cache_async(const swp_entry_t entry,
++	const int node)
++{
++	enum trickle_return ret = TRICKLE_FAILED;
++	unsigned long flags;
++	struct page *page;
++
++	read_lock_irqsave(&swapper_space.tree_lock, flags);
++	/* Entry may already exist */
++	page = radix_tree_lookup(&swapper_space.page_tree, entry.val);
++	read_unlock_irqrestore(&swapper_space.tree_lock, flags);
++	if (page)
++		goto out;
++
++	/*
++	 * Get a new page to read from swap. We have already checked the
++	 * watermarks so __alloc_pages will not call on reclaim.
++	 */
++	page = alloc_pages_node(node, GFP_HIGHUSER & ~__GFP_WAIT, 0);
++	if (unlikely(!page)) {
++		ret = TRICKLE_DELAY;
++		goto out;
++	}
++
++	if (add_to_swap_cache(page, entry)) {
++		/* Failed to add to swap cache */
++		goto out_release;
++	}
++
++	/* Add them to the tail of the inactive list to preserve LRU order */
++	lru_cache_add_tail(page);
++	if (unlikely(swap_readpage(NULL, page)))
++		goto out_release;
++
++	sp_stat.prefetched_pages++;
++	sp_stat.node[node].last_free--;
++
++	ret = TRICKLE_SUCCESS;
++out_release:
++	page_cache_release(page);
++out:
++	/*
++	 * All entries are removed here lazily. This avoids the cost of
++	 * remove_from_swapped_list during normal swapin. Thus there are
++	 * usually many stale entries.
++	 */
++	remove_from_swapped_list(entry.val);
++	return ret;
++}
++
++static void clear_last_prefetch_free(void)
++{
++	int node;
++
++	/*
++	 * Reset the nodes suitable for prefetching to all nodes. We could
++	 * update the data to take into account memory hotplug if desired..
++	 */
++	sp_stat.prefetch_nodes = node_online_map;
++	for_each_node_mask(node, sp_stat.prefetch_nodes) {
++		struct node_stats *ns = &sp_stat.node[node];
++
++		ns->last_free = 0;
++	}
++}
++
++static void clear_current_prefetch_free(void)
++{
++	int node;
++
++	sp_stat.prefetch_nodes = node_online_map;
++	for_each_node_mask(node, sp_stat.prefetch_nodes) {
++		struct node_stats *ns = &sp_stat.node[node];
++
++		ns->current_free = 0;
++	}
++}
++
++/*
++ * This updates the high and low watermarks of amount of free ram in each
++ * node used to start and stop prefetching. We prefetch from pages_high * 4
++ * down to pages_high * 3.
++ */
++static void examine_free_limits(void)
++{
++	struct zone *z;
++
++	for_each_zone(z) {
++		struct node_stats *ns;
++		int idx;
++
++		if (!populated_zone(z))
++			continue;
++
++		ns = &sp_stat.node[zone_to_nid(z)];
++		idx = zone_idx(z);
++		ns->lowfree[idx] = z->pages_high * 3;
++		ns->highfree[idx] = ns->lowfree[idx] + z->pages_high;
++
++		if (zone_page_state(z, NR_FREE_PAGES) > ns->highfree[idx]) {
++			/*
++			 * We've gotten above the high watermark of free pages
++			 * so we can start prefetching till we get to the low
++			 * watermark.
++			 */
++			ns->pointfree[idx] = &ns->lowfree[idx];
++		}
++	}
++}
++
++/*
++ * We want to be absolutely certain it's ok to start prefetching.
++ */
++static enum trickle_return prefetch_suitable(void)
++{
++	enum trickle_return ret = TRICKLE_DELAY;
++	struct zone *z;
++	int node;
++
++	/*
++	 * If swap_prefetch is set to a high value we can ignore load
++	 * and prefetch whenever we can. Otherwise we test for vm and
++	 * cpu activity.
++	 */
++	if (swap_prefetch < 3) {
++		/* Purposefully racy, may return false positive */
++		if (test_bit(0, &swapped.busy)) {
++			__clear_bit(0, &swapped.busy);
++			goto out;
++		}
++
++		/*
++		 * above_background_load is expensive so we only perform it
++		 * every SWAP_CLUSTER_MAX prefetched_pages.
++		 * We test to see if we're above_background_load as disk
++		 * activity even at low priority can cause interrupt induced
++		 * scheduling latencies.
++		 */
++		if (!(sp_stat.prefetched_pages % SWAP_CLUSTER_MAX) &&
++		    above_background_load())
++			goto out;
++	}
++	clear_current_prefetch_free();
++
++	/*
++	 * Have some hysteresis between where page reclaiming and prefetching
++	 * will occur to prevent ping-ponging between them.
++	 */
++	for_each_zone(z) {
++		struct node_stats *ns;
++		unsigned long free;
++		int idx;
++
++		if (!populated_zone(z))
++			continue;
++
++		node = zone_to_nid(z);
++		ns = &sp_stat.node[node];
++		idx = zone_idx(z);
++
++		free = zone_page_state(z, NR_FREE_PAGES);
++		if (free < *ns->pointfree[idx]) {
++			/*
++			 * Free pages have dropped below the low watermark so
++			 * we won't start prefetching again till we hit the
++			 * high watermark of free pages.
++			 */
++			ns->pointfree[idx] = &ns->highfree[idx];
++			node_clear(node, sp_stat.prefetch_nodes);
++			continue;
++		}
++		ns->current_free += free;
++	}
++
++	/*
++	 * We iterate over each node testing to see if it is suitable for
++	 * prefetching and clear the nodemask if it is not.
++	 */
++	for_each_node_mask(node, sp_stat.prefetch_nodes) {
++		struct node_stats *ns = &sp_stat.node[node];
++
++		/*
++		 * We check to see that pages are not being allocated
++		 * elsewhere at any significant rate implying any
++		 * degree of memory pressure (eg during file reads)
++		 */
++		if (ns->last_free) {
++			if (ns->current_free + SWAP_CLUSTER_MAX <
++			    ns->last_free) {
++				ns->last_free = ns->current_free;
++				node_clear(node,
++					sp_stat.prefetch_nodes);
++				continue;
++			}
++		} else
++			ns->last_free = ns->current_free;
++
++		/* We shouldn't prefetch when we are doing writeback */
++		if (node_page_state(node, NR_WRITEBACK))
++			node_clear(node, sp_stat.prefetch_nodes);
++	}
++
++	/* Nothing suitable, put kprefetchd back to sleep */
++	if (nodes_empty(sp_stat.prefetch_nodes))
++		return TRICKLE_FAILED;
++
++	/* Survived all that? Hooray we can prefetch! */
++	ret = TRICKLE_SUCCESS;
++out:
++	return ret;
++}
++
++/*
++ * trickle_swap is the main function that initiates the swap prefetching. It
++ * first checks to see if the busy flag is set, and does not prefetch if it
++ * is, as the flag implied we are low on memory or swapping in currently.
++ * Otherwise it runs until prefetch_suitable fails which occurs when the
++ * vm is busy, we prefetch to the watermark, the list is empty or we have
++ * iterated over all entries once.
++ */
++static enum trickle_return trickle_swap(void)
++{
++	enum trickle_return suitable, ret = TRICKLE_DELAY;
++	struct swapped_entry *pos, *n;
++	unsigned long flags;
++
++	if (!prefetch_enabled())
++		return ret;
++
++	examine_free_limits();
++	suitable = prefetch_suitable();
++	if (suitable != TRICKLE_SUCCESS)
++		return suitable;
++	if (list_empty(&swapped.list)) {
++		kprefetchd_awake = 0;
++		return TRICKLE_FAILED;
++	}
++
++	spin_lock_irqsave(&swapped.lock, flags);
++	list_for_each_entry_safe_reverse(pos, n, &swapped.list, swapped_list) {
++		swp_entry_t swp_entry;
++		int node;
++
++		spin_unlock_irqrestore(&swapped.lock, flags);
++		cond_resched();
++		suitable = prefetch_suitable();
++		if (suitable != TRICKLE_SUCCESS) {
++			ret = suitable;
++			goto out_unlocked;
++		}
++
++		spin_lock_irqsave(&swapped.lock, flags);
++		if (unlikely(!pos))
++			continue;
++		node = get_swap_entry_node(pos);
++		if (!node_isset(node, sp_stat.prefetch_nodes)) {
++			/*
++			 * We found an entry that belongs to a node that is
++			 * not suitable for prefetching so skip it.
++			 */
++			continue;
++		}
++		swp_entry = pos->swp_entry;
++		spin_unlock_irqrestore(&swapped.lock, flags);
++
++		if (trickle_swap_cache_async(swp_entry, node) == TRICKLE_DELAY)
++			goto out_unlocked;
++		spin_lock_irqsave(&swapped.lock, flags);
++	}
++	spin_unlock_irqrestore(&swapped.lock, flags);
++
++out_unlocked:
++	if (sp_stat.prefetched_pages) {
++		lru_add_drain();
++		sp_stat.prefetched_pages = 0;
++	}
++	return ret;
++}
++
++static int kprefetchd(void *__unused)
++{
++	struct sched_param param = { .sched_priority = 0 };
++
++	sched_setscheduler(current, SCHED_BATCH, &param);
++	set_user_nice(current, 19);
++	/* Set ioprio to lowest if supported by i/o scheduler */
++	sys_ioprio_set(IOPRIO_WHO_PROCESS, IOPRIO_BE_NR - 1, IOPRIO_CLASS_BE);
++
++	while (!kthread_should_stop()) {
++		try_to_freeze();
++
++		if (!kprefetchd_awake) {
++			set_current_state(TASK_INTERRUPTIBLE);
++			schedule();
++			kprefetchd_awake = 1;
++		}
++
++		if (trickle_swap() == TRICKLE_FAILED)
++			schedule_timeout_interruptible(PREFETCH_SLEEP);
++		else
++			schedule_timeout_interruptible(PREFETCH_DELAY);
++		clear_last_prefetch_free();
++	}
++	return 0;
++}
++
++/*
++ * Create kmem cache for swapped entries
++ */
++void __init prepare_swap_prefetch(void)
++{
++	struct zone *zone;
++
++	swapped.cache = kmem_cache_create("swapped_entry",
++		sizeof(struct swapped_entry), 0, SLAB_PANIC, NULL, NULL);
++
++	/*
++	 * We set the limit to more entries than the physical ram.
++	 * We remove entries lazily so we need some headroom.
++	 */
++	swapped.maxcount = nr_free_pagecache_pages() * 2;
++
++	for_each_zone(zone) {
++		struct node_stats *ns;
++		int idx;
++
++		if (!populated_zone(zone))
++			continue;
++
++		ns = &sp_stat.node[zone_to_nid(zone)];
++		idx = zone_idx(zone);
++		ns->pointfree[idx] = &ns->highfree[idx];
++	}
++}
++
++static int __init kprefetchd_init(void)
++{
++	kprefetchd_task = kthread_run(kprefetchd, NULL, "kprefetchd");
++
++	return 0;
++}
++
++static void __exit kprefetchd_exit(void)
++{
++	kthread_stop(kprefetchd_task);
++}
++
++module_init(kprefetchd_init);
++module_exit(kprefetchd_exit);
+Index: linux-2.6.22-ck1/mm/swap_state.c
+===================================================================
+--- linux-2.6.22-ck1.orig/mm/swap_state.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/mm/swap_state.c	2007-07-10 14:55:22.000000000 +1000
+@@ -10,6 +10,7 @@
+ #include <linux/mm.h>
+ #include <linux/kernel_stat.h>
+ #include <linux/swap.h>
++#include <linux/swap-prefetch.h>
+ #include <linux/init.h>
+ #include <linux/pagemap.h>
+ #include <linux/buffer_head.h>
+@@ -95,7 +96,7 @@
+ 	return error;
+ }
+ 
+-static int add_to_swap_cache(struct page *page, swp_entry_t entry)
++int add_to_swap_cache(struct page *page, swp_entry_t entry)
+ {
+ 	int error;
+ 
+@@ -148,6 +149,9 @@
+ 	swp_entry_t entry;
+ 	int err;
+ 
++	/* Swap prefetching is delayed if we're swapping pages */
++	delay_swap_prefetch();
++
+ 	BUG_ON(!PageLocked(page));
+ 
+ 	for (;;) {
+@@ -320,6 +324,9 @@
+ 	struct page *found_page, *new_page = NULL;
+ 	int err;
+ 
++	/* Swap prefetching is delayed if we're already reading from swap */
++	delay_swap_prefetch();
++
+ 	do {
+ 		/*
+ 		 * First check the swap cache.  Since this is normally
+Index: linux-2.6.22-ck1/mm/vmscan.c
+===================================================================
+--- linux-2.6.22-ck1.orig/mm/vmscan.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/mm/vmscan.c	2007-07-10 14:55:23.000000000 +1000
+@@ -16,6 +16,7 @@
+ #include <linux/slab.h>
+ #include <linux/kernel_stat.h>
+ #include <linux/swap.h>
++#include <linux/swap-prefetch.h>
+ #include <linux/pagemap.h>
+ #include <linux/init.h>
+ #include <linux/highmem.h>
+@@ -36,6 +37,7 @@
+ #include <linux/rwsem.h>
+ #include <linux/delay.h>
+ #include <linux/kthread.h>
++#include <linux/timer.h>
+ #include <linux/freezer.h>
+ 
+ #include <asm/tlbflush.h>
+@@ -63,7 +65,7 @@
+ 	 * whole list at once. */
+ 	int swap_cluster_max;
+ 
+-	int swappiness;
++	int mapped;
+ 
+ 	int all_unreclaimable;
+ };
+@@ -110,9 +112,10 @@
+ #endif
+ 
+ /*
+- * From 0 .. 100.  Higher means more swappy.
++ * From 0 .. 100.  Lower means more swappy.
+  */
+-int vm_swappiness = 60;
++int vm_mapped __read_mostly = 66;
++int vm_hardmaplimit __read_mostly = 1;
+ long vm_total_pages;	/* The total number of pages which the VM controls */
+ 
+ static LIST_HEAD(shrinker_list);
+@@ -803,10 +806,14 @@
+ 		 * The distress ratio is important - we don't want to start
+ 		 * going oom.
+ 		 *
+-		 * A 100% value of vm_swappiness overrides this algorithm
+-		 * altogether.
++		 * This distress value is ignored if we apply a hardmaplimit except
++		 * in extreme distress.
++		 *
++		 * A 0% value of vm_mapped overrides this algorithm altogether.
+ 		 */
+-		swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
++		swap_tendency = mapped_ratio * 100 / (sc->mapped + 1);
++		if (!vm_hardmaplimit || distress == 100)
++			swap_tendency += distress;
+ 
+ 		/*
+ 		 * Now use this metric to decide whether to start moving mapped
+@@ -955,6 +962,41 @@
+ }
+ 
+ /*
++ * Helper functions to adjust nice level of kswapd, based on the priority of
++ * the task (p) that called it. If it is already higher priority we do not
++ * demote its nice level since it is still working on behalf of a higher
++ * priority task. With kernel threads we leave it at nice 0.
++ *
++ * We don't ever run kswapd real time, so if a real time task calls kswapd we
++ * set it to highest SCHED_NORMAL priority.
++ */
++static int effective_sc_prio(struct task_struct *p)
++{
++	if (likely(p->mm)) {
++		if (rt_task(p))
++			return -20;
++		if (idleprio_task(p))
++			return 19;
++		return task_nice(p);
++	}
++	return 0;
++}
++
++static void set_kswapd_nice(struct task_struct *kswapd, struct task_struct *p,
++			    int active)
++{
++	long nice = effective_sc_prio(p);
++
++	if (task_nice(kswapd) > nice || !active)
++		set_user_nice(kswapd, nice);
++}
++
++static int sc_priority(struct task_struct *p)
++{
++	return (DEF_PRIORITY + (DEF_PRIORITY * effective_sc_prio(p) / 40));
++}
++
++/*
+  * This is the direct reclaim path, for page-allocating processes.  We only
+  * try to reclaim pages from zones which will satisfy the caller's allocation
+  * request.
+@@ -1011,7 +1053,8 @@
+  * holds filesystem locks which prevent writeout this might not work, and the
+  * allocation attempt will fail.
+  */
+-unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask)
++unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask,
++				struct task_struct *p)
+ {
+ 	int priority;
+ 	int ret = 0;
+@@ -1019,15 +1062,20 @@
+ 	unsigned long nr_reclaimed = 0;
+ 	struct reclaim_state *reclaim_state = current->reclaim_state;
+ 	unsigned long lru_pages = 0;
+-	int i;
++	int i, scan_priority = DEF_PRIORITY;
+ 	struct scan_control sc = {
+ 		.gfp_mask = gfp_mask,
+ 		.may_writepage = !laptop_mode,
+ 		.swap_cluster_max = SWAP_CLUSTER_MAX,
+ 		.may_swap = 1,
+-		.swappiness = vm_swappiness,
++		.mapped = vm_mapped,
+ 	};
+ 
++	if (p)
++		scan_priority = sc_priority(p);
++
++	delay_swap_prefetch();
++
+ 	count_vm_event(ALLOCSTALL);
+ 
+ 	for (i = 0; zones[i] != NULL; i++) {
+@@ -1040,7 +1088,7 @@
+ 				+ zone_page_state(zone, NR_INACTIVE);
+ 	}
+ 
+-	for (priority = DEF_PRIORITY; priority >= 0; priority--) {
++	for (priority = scan_priority; priority >= 0; priority--) {
+ 		sc.nr_scanned = 0;
+ 		if (!priority)
+ 			disable_swap_token();
+@@ -1070,7 +1118,7 @@
+ 		}
+ 
+ 		/* Take a nap, wait for some writeback to complete */
+-		if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
++		if (sc.nr_scanned && priority < scan_priority - 2)
+ 			congestion_wait(WRITE, HZ/10);
+ 	}
+ 	/* top priority shrink_caches still had more to do? don't OOM, then */
+@@ -1120,9 +1168,9 @@
+  */
+ static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
+ {
+-	int all_zones_ok;
++	int all_zones_ok = 0;
+ 	int priority;
+-	int i;
++	int i, scan_priority;
+ 	unsigned long total_scanned;
+ 	unsigned long nr_reclaimed;
+ 	struct reclaim_state *reclaim_state = current->reclaim_state;
+@@ -1130,7 +1178,7 @@
+ 		.gfp_mask = GFP_KERNEL,
+ 		.may_swap = 1,
+ 		.swap_cluster_max = SWAP_CLUSTER_MAX,
+-		.swappiness = vm_swappiness,
++		.mapped = vm_mapped,
+ 	};
+ 	/*
+ 	 * temp_priority is used to remember the scanning priority at which
+@@ -1138,6 +1186,8 @@
+ 	 */
+ 	int temp_priority[MAX_NR_ZONES];
+ 
++	scan_priority = sc_priority(pgdat->kswapd);
++
+ loop_again:
+ 	total_scanned = 0;
+ 	nr_reclaimed = 0;
+@@ -1145,9 +1195,9 @@
+ 	count_vm_event(PAGEOUTRUN);
+ 
+ 	for (i = 0; i < pgdat->nr_zones; i++)
+-		temp_priority[i] = DEF_PRIORITY;
++		temp_priority[i] = scan_priority;
+ 
+-	for (priority = DEF_PRIORITY; priority >= 0; priority--) {
++	for (priority = scan_priority; priority >= 0; priority--) {
+ 		int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
+ 		unsigned long lru_pages = 0;
+ 
+@@ -1163,15 +1213,22 @@
+ 		 */
+ 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
+ 			struct zone *zone = pgdat->node_zones + i;
++			unsigned long watermark;
+ 
+ 			if (!populated_zone(zone))
+ 				continue;
+ 
+-			if (zone->all_unreclaimable && priority != DEF_PRIORITY)
++			if (zone->all_unreclaimable && priority != scan_priority)
+ 				continue;
+ 
+-			if (!zone_watermark_ok(zone, order, zone->pages_high,
+-					       0, 0)) {
++			/*
++			 * The watermark is relaxed depending on the
++			 * level of "priority" till it drops to
++			 * pages_high.
++			 */
++			watermark = zone->pages_high + (zone->pages_high *
++				    priority / scan_priority);
++			if (!zone_watermark_ok(zone, order, watermark, 0, 0)) {
+ 				end_zone = i;
+ 				break;
+ 			}
+@@ -1198,14 +1255,18 @@
+ 		for (i = 0; i <= end_zone; i++) {
+ 			struct zone *zone = pgdat->node_zones + i;
+ 			int nr_slab;
++			unsigned long watermark;
+ 
+ 			if (!populated_zone(zone))
+ 				continue;
+ 
+-			if (zone->all_unreclaimable && priority != DEF_PRIORITY)
++			if (zone->all_unreclaimable && priority != scan_priority)
+ 				continue;
+ 
+-			if (!zone_watermark_ok(zone, order, zone->pages_high,
++			watermark = zone->pages_high + (zone->pages_high *
++				    priority / scan_priority);
++
++			if (!zone_watermark_ok(zone, order, watermark,
+ 					       end_zone, 0))
+ 				all_zones_ok = 0;
+ 			temp_priority[i] = priority;
+@@ -1238,7 +1299,7 @@
+ 		 * OK, kswapd is getting into trouble.  Take a nap, then take
+ 		 * another pass across the zones.
+ 		 */
+-		if (total_scanned && priority < DEF_PRIORITY - 2)
++		if (total_scanned && priority < scan_priority - 2)
+ 			congestion_wait(WRITE, HZ/10);
+ 
+ 		/*
+@@ -1272,6 +1333,8 @@
+ 	return nr_reclaimed;
+ }
+ 
++#define WT_EXPIRY	(HZ * 5)	/* Time to wakeup watermark_timer */
++
+ /*
+  * The background pageout daemon, started as a kernel thread
+  * from the init process. 
+@@ -1319,6 +1382,8 @@
+ 	for ( ; ; ) {
+ 		unsigned long new_order;
+ 
++		/* kswapd has been busy so delay watermark_timer */
++		mod_timer(&pgdat->watermark_timer, jiffies + WT_EXPIRY);
+ 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
+ 		new_order = pgdat->kswapd_max_order;
+ 		pgdat->kswapd_max_order = 0;
+@@ -1332,6 +1397,7 @@
+ 			if (!freezing(current))
+ 				schedule();
+ 
++			set_user_nice(tsk, 0);
+ 			order = pgdat->kswapd_max_order;
+ 		}
+ 		finish_wait(&pgdat->kswapd_wait, &wait);
+@@ -1349,9 +1415,10 @@
+ /*
+  * A zone is low on free memory, so wake its kswapd task to service it.
+  */
+-void wakeup_kswapd(struct zone *zone, int order)
++void wakeup_kswapd(struct zone *zone, int order, struct task_struct *p)
+ {
+ 	pg_data_t *pgdat;
++	int active;
+ 
+ 	if (!populated_zone(zone))
+ 		return;
+@@ -1363,7 +1430,9 @@
+ 		pgdat->kswapd_max_order = order;
+ 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
+ 		return;
+-	if (!waitqueue_active(&pgdat->kswapd_wait))
++	active = waitqueue_active(&pgdat->kswapd_wait);
++	set_kswapd_nice(pgdat->kswapd, p, active);
++	if (!active)
+ 		return;
+ 	wake_up_interruptible(&pgdat->kswapd_wait);
+ }
+@@ -1382,6 +1451,8 @@
+ 	struct zone *zone;
+ 	unsigned long nr_to_scan, ret = 0;
+ 
++	delay_swap_prefetch();
++
+ 	for_each_zone(zone) {
+ 
+ 		if (!populated_zone(zone))
+@@ -1441,7 +1512,7 @@
+ 		.may_swap = 0,
+ 		.swap_cluster_max = nr_pages,
+ 		.may_writepage = 1,
+-		.swappiness = vm_swappiness,
++		.mapped = vm_mapped,
+ 	};
+ 
+ 	current->reclaim_state = &reclaim_state;
+@@ -1476,7 +1547,7 @@
+ 		/* Force reclaiming mapped pages in the passes #3 and #4 */
+ 		if (pass > 2) {
+ 			sc.may_swap = 1;
+-			sc.swappiness = 100;
++			sc.mapped = 0;
+ 		}
+ 
+ 		for (prio = DEF_PRIORITY; prio >= 0; prio--) {
+@@ -1540,20 +1611,57 @@
+ }
+ 
+ /*
++ * We wake up kswapd every WT_EXPIRY till free ram is above pages_lots
++ */
++static void watermark_wakeup(unsigned long data)
++{
++	pg_data_t *pgdat = (pg_data_t *)data;
++	struct timer_list *wt = &pgdat->watermark_timer;
++	int i;
++
++	if (!waitqueue_active(&pgdat->kswapd_wait) || above_background_load())
++		goto out;
++	for (i = pgdat->nr_zones - 1; i >= 0; i--) {
++		struct zone *z = pgdat->node_zones + i;
++
++		if (!populated_zone(z) || is_highmem(z)) {
++			/* We are better off leaving highmem full */
++			continue;
++		}
++		if (!zone_watermark_ok(z, 0, z->pages_lots, 0, 0)) {
++			wake_up_interruptible(&pgdat->kswapd_wait);
++			goto out;
++		}
++	}
++out:
++	mod_timer(wt, jiffies + WT_EXPIRY);
++	return;
++}
++
++/*
+  * This kswapd start function will be called by init and node-hot-add.
+  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
+  */
+ int kswapd_run(int nid)
+ {
+ 	pg_data_t *pgdat = NODE_DATA(nid);
++	struct timer_list *wt;
+ 	int ret = 0;
+ 
+ 	if (pgdat->kswapd)
+ 		return 0;
+ 
++	wt = &pgdat->watermark_timer;
++	init_timer(wt);
++	wt->data = (unsigned long)pgdat;
++	wt->function = watermark_wakeup;
++	wt->expires = jiffies + WT_EXPIRY;
++	add_timer(wt);
++
+ 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
+ 	if (IS_ERR(pgdat->kswapd)) {
+ 		/* failure at boot is fatal */
++		del_timer(wt);
+ 		BUG_ON(system_state == SYSTEM_BOOTING);
+ 		printk("Failed to start kswapd on node %d\n",nid);
+ 		ret = -1;
+@@ -1624,7 +1732,7 @@
+ 		.swap_cluster_max = max_t(unsigned long, nr_pages,
+ 					SWAP_CLUSTER_MAX),
+ 		.gfp_mask = gfp_mask,
+-		.swappiness = vm_swappiness,
++		.mapped = vm_mapped,
+ 	};
+ 	unsigned long slab_reclaimable;
+ 
+Index: linux-2.6.22-ck1/include/linux/mm_inline.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/mm_inline.h	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/mm_inline.h	2007-07-10 14:55:22.000000000 +1000
+@@ -13,6 +13,13 @@
+ }
+ 
+ static inline void
++add_page_to_inactive_list_tail(struct zone *zone, struct page *page)
++{
++	list_add_tail(&page->lru, &zone->inactive_list);
++	__inc_zone_state(zone, NR_INACTIVE);
++}
++
++static inline void
+ del_page_from_active_list(struct zone *zone, struct page *page)
+ {
+ 	list_del(&page->lru);
+Index: linux-2.6.22-ck1/include/linux/swap-prefetch.h
+===================================================================
+--- /dev/null	1970-01-01 00:00:00.000000000 +0000
++++ linux-2.6.22-ck1/include/linux/swap-prefetch.h	2007-07-10 14:55:22.000000000 +1000
+@@ -0,0 +1,53 @@
++#ifndef SWAP_PREFETCH_H_INCLUDED
++#define SWAP_PREFETCH_H_INCLUDED
++
++#ifdef CONFIG_SWAP_PREFETCH
++/* mm/swap_prefetch.c */
++extern int swap_prefetch;
++extern int swap_prefetch_delay;
++extern int swap_prefetch_sleep;
++
++struct swapped_entry {
++	swp_entry_t		swp_entry;	/* The actual swap entry */
++	struct list_head	swapped_list;	/* Linked list of entries */
++#if MAX_NUMNODES > 1
++	int			node;		/* Node id */
++#endif
++} __attribute__((packed));
++
++static inline void store_swap_entry_node(struct swapped_entry *entry,
++	struct page *page)
++{
++#if MAX_NUMNODES > 1
++	entry->node = page_to_nid(page);
++#endif
++}
++
++static inline int get_swap_entry_node(struct swapped_entry *entry)
++{
++#if MAX_NUMNODES > 1
++	return entry->node;
++#else
++	return 0;
++#endif
++}
++
++extern void add_to_swapped_list(struct page *page);
++extern void delay_swap_prefetch(void);
++extern void prepare_swap_prefetch(void);
++
++#else	/* CONFIG_SWAP_PREFETCH */
++static inline void add_to_swapped_list(struct page *__unused)
++{
++}
++
++static inline void prepare_swap_prefetch(void)
++{
++}
++
++static inline void delay_swap_prefetch(void)
++{
++}
++#endif	/* CONFIG_SWAP_PREFETCH */
++
++#endif		/* SWAP_PREFETCH_H_INCLUDED */
+Index: linux-2.6.22-ck1/mm/page_io.c
+===================================================================
+--- linux-2.6.22-ck1.orig/mm/page_io.c	2007-07-10 14:55:00.000000000 +1000
++++ linux-2.6.22-ck1/mm/page_io.c	2007-07-10 14:55:22.000000000 +1000
+@@ -17,6 +17,7 @@
+ #include <linux/bio.h>
+ #include <linux/swapops.h>
+ #include <linux/writeback.h>
++#include <linux/swap-prefetch.h>
+ #include <asm/pgtable.h>
+ 
+ static struct bio *get_swap_bio(gfp_t gfp_flags, pgoff_t index,
+@@ -118,6 +119,7 @@
+ 		ret = -ENOMEM;
+ 		goto out;
+ 	}
++	add_to_swapped_list(page);
+ 	if (wbc->sync_mode == WB_SYNC_ALL)
+ 		rw |= (1 << BIO_RW_SYNC);
+ 	count_vm_event(PSWPOUT);
+Index: linux-2.6.22-ck1/include/linux/sysctl.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/sysctl.h	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/sysctl.h	2007-07-10 14:55:22.000000000 +1000
+@@ -190,7 +190,7 @@
+ 	VM_OVERCOMMIT_RATIO=16, /* percent of RAM to allow overcommit in */
+ 	VM_PAGEBUF=17,		/* struct: Control pagebuf parameters */
+ 	VM_HUGETLB_PAGES=18,	/* int: Number of available Huge Pages */
+-	VM_SWAPPINESS=19,	/* Tendency to steal mapped memory */
++	VM_UNUSED19=19,		/* was: Tendency to steal mapped memory */
+ 	VM_LOWMEM_RESERVE_RATIO=20,/* reservation ratio for lower memory zones */
+ 	VM_MIN_FREE_KBYTES=21,	/* Minimum free kilobytes to maintain */
+ 	VM_MAX_MAP_COUNT=22,	/* int: Maximum number of mmaps/address-space */
+Index: linux-2.6.22-ck1/include/linux/mmzone.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/mmzone.h	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/mmzone.h	2007-07-10 14:55:23.000000000 +1000
+@@ -13,6 +13,7 @@
+ #include <linux/init.h>
+ #include <linux/seqlock.h>
+ #include <linux/nodemask.h>
++#include <linux/timer.h>
+ #include <asm/atomic.h>
+ #include <asm/page.h>
+ 
+@@ -181,7 +182,7 @@
+ 
+ struct zone {
+ 	/* Fields commonly accessed by the page allocator */
+-	unsigned long		pages_min, pages_low, pages_high;
++	unsigned long		pages_min, pages_low, pages_high, pages_lots;
+ 	/*
+ 	 * We don't know if the memory that we're going to allocate will be freeable
+ 	 * or/and it will be released eventually, so to avoid totally wasting several
+@@ -452,6 +453,7 @@
+ 	wait_queue_head_t kswapd_wait;
+ 	struct task_struct *kswapd;
+ 	int kswapd_max_order;
++	struct timer_list watermark_timer;
+ } pg_data_t;
+ 
+ #define node_present_pages(nid)	(NODE_DATA(nid)->node_present_pages)
+@@ -468,7 +470,7 @@
+ void get_zone_counts(unsigned long *active, unsigned long *inactive,
+ 			unsigned long *free);
+ void build_all_zonelists(void);
+-void wakeup_kswapd(struct zone *zone, int order);
++void wakeup_kswapd(struct zone *zone, int order, struct task_struct *p);
+ int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
+ 		int classzone_idx, int alloc_flags);
+ enum memmap_context {
+Index: linux-2.6.22-ck1/mm/page_alloc.c
+===================================================================
+--- linux-2.6.22-ck1.orig/mm/page_alloc.c	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/mm/page_alloc.c	2007-07-10 14:55:22.000000000 +1000
+@@ -1250,7 +1250,7 @@
+ 		goto nopage;
+ 
+ 	for (z = zonelist->zones; *z; z++)
+-		wakeup_kswapd(*z, order);
++		wakeup_kswapd(*z, order, p);
+ 
+ 	/*
+ 	 * OK, we're below the kswapd watermark and have kicked background
+@@ -1314,7 +1314,7 @@
+ 	reclaim_state.reclaimed_slab = 0;
+ 	p->reclaim_state = &reclaim_state;
+ 
+-	did_some_progress = try_to_free_pages(zonelist->zones, gfp_mask);
++	did_some_progress = try_to_free_pages(zonelist->zones, gfp_mask, p);
+ 
+ 	p->reclaim_state = NULL;
+ 	p->flags &= ~PF_MEMALLOC;
+@@ -1570,6 +1570,7 @@
+ 			" min:%lukB"
+ 			" low:%lukB"
+ 			" high:%lukB"
++			" lots:%lukB"
+ 			" active:%lukB"
+ 			" inactive:%lukB"
+ 			" present:%lukB"
+@@ -1581,6 +1582,7 @@
+ 			K(zone->pages_min),
+ 			K(zone->pages_low),
+ 			K(zone->pages_high),
++			K(zone->pages_lots),
+ 			K(zone_page_state(zone, NR_ACTIVE)),
+ 			K(zone_page_state(zone, NR_INACTIVE)),
+ 			K(zone->present_pages),
+@@ -3142,6 +3144,7 @@
+ 
+ 		zone->pages_low   = zone->pages_min + (tmp >> 2);
+ 		zone->pages_high  = zone->pages_min + (tmp >> 1);
++		zone->pages_lots  = zone->pages_min + tmp;
+ 		spin_unlock_irqrestore(&zone->lru_lock, flags);
+ 	}
+ 
+Index: linux-2.6.22-ck1/fs/buffer.c
+===================================================================
+--- linux-2.6.22-ck1.orig/fs/buffer.c	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/fs/buffer.c	2007-07-10 14:55:22.000000000 +1000
+@@ -356,7 +356,7 @@
+ 	for_each_online_pgdat(pgdat) {
+ 		zones = pgdat->node_zonelists[gfp_zone(GFP_NOFS)].zones;
+ 		if (*zones)
+-			try_to_free_pages(zones, GFP_NOFS);
++			try_to_free_pages(zones, GFP_NOFS, NULL);
+ 	}
+ }
+ 
+Index: linux-2.6.22-ck1/mm/filemap.c
+===================================================================
+--- linux-2.6.22-ck1.orig/mm/filemap.c	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/mm/filemap.c	2007-07-10 14:55:23.000000000 +1000
+@@ -466,6 +466,16 @@
+ 	return ret;
+ }
+ 
++int add_to_page_cache_lru_tail(struct page *page,
++	struct address_space *mapping, pgoff_t offset, gfp_t gfp_mask)
++{
++	int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
++
++	if (ret == 0)
++		lru_cache_add_tail(page);
++	return ret;
++}
++
+ #ifdef CONFIG_NUMA
+ struct page *__page_cache_alloc(gfp_t gfp)
+ {
+@@ -839,6 +849,34 @@
+ 	ra->ra_pages /= 4;
+ }
+ 
++/*
++ * Sysctl which determines whether we should read from large files to the
++ * tail of the inactive lru list.
++ */
++int vm_tail_largefiles __read_mostly = 1;
++
++static inline int nr_mapped(void)
++{
++	return global_page_state(NR_FILE_MAPPED) +
++		global_page_state(NR_ANON_PAGES);
++}
++
++/*
++ * This examines how large in pages a file size is and returns 1 if it is
++ * more than half the unmapped ram. Avoid doing read_page_state which is
++ * expensive unless we already know it is likely to be large enough.
++ */
++static int large_isize(unsigned long nr_pages)
++{
++	if (nr_pages * 6 > vm_total_pages) {
++		 unsigned long unmapped_ram = vm_total_pages - nr_mapped();
++
++		if (nr_pages * 2 > unmapped_ram)
++			return 1;
++	}
++	return 0;
++}
++
+ /**
+  * do_generic_mapping_read - generic file read routine
+  * @mapping:	address_space to be read
+@@ -1051,8 +1089,19 @@
+ 				goto out;
+ 			}
+ 		}
+-		error = add_to_page_cache_lru(cached_page, mapping,
+-						index, GFP_KERNEL);
++
++		/*
++		 * If we know the file is large we add the pages read to the
++		 * end of the lru as we're unlikely to be able to cache the
++		 * whole file in ram so make those pages the first to be
++		 * dropped if not referenced soon.
++		 */
++		if (vm_tail_largefiles && large_isize(end_index))
++			error = add_to_page_cache_lru_tail(cached_page,
++						mapping, index, GFP_KERNEL);
++		else
++			error = add_to_page_cache_lru(cached_page, mapping,
++							index, GFP_KERNEL);
+ 		if (error) {
+ 			if (error == -EEXIST)
+ 				goto find_page;
+Index: linux-2.6.22-ck1/Documentation/filesystems/proc.txt
+===================================================================
+--- linux-2.6.22-ck1.orig/Documentation/filesystems/proc.txt	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/Documentation/filesystems/proc.txt	2007-07-10 14:55:23.000000000 +1000
+@@ -1333,6 +1333,14 @@
+ As this is a non-destructive operation and dirty objects are not freeable, the
+ user should run `sync' first.
+ 
++tail_largefiles
++---------------
++
++When enabled reads from large files to the tail end of the inactive lru list.
++This means that any cache from reading large files is dropped very quickly,
++preventing loss of mapped ram and useful pagecache when large files are read.
++This does, however, make caching less effective when working with large files.
++
+ 
+ 2.5 /proc/sys/dev - Device specific parameters
+ ----------------------------------------------
+Index: linux-2.6.22-ck1/arch/i386/Kconfig
+===================================================================
+--- linux-2.6.22-ck1.orig/arch/i386/Kconfig	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/arch/i386/Kconfig	2007-07-10 14:55:23.000000000 +1000
+@@ -550,7 +550,7 @@
+ 
+ choice
+ 	depends on EXPERIMENTAL
+-	prompt "Memory split" if EMBEDDED
++	prompt "Memory split"
+ 	default VMSPLIT_3G
+ 	help
+ 	  Select the desired split between kernel and user memory.
+@@ -569,17 +569,17 @@
+ 	  option alone!
+ 
+ 	config VMSPLIT_3G
+-		bool "3G/1G user/kernel split"
++		bool "Default 896MB lowmem (3G/1G user/kernel split)"
+ 	config VMSPLIT_3G_OPT
+ 		depends on !HIGHMEM
+-		bool "3G/1G user/kernel split (for full 1G low memory)"
++		bool "1GB lowmem (3G/1G user/kernel split)"
+ 	config VMSPLIT_2G
+-		bool "2G/2G user/kernel split"
++		bool "2GB lowmem (2G/2G user/kernel split)"
+ 	config VMSPLIT_2G_OPT
+ 		depends on !HIGHMEM
+-		bool "2G/2G user/kernel split (for full 2G low memory)"
++		bool "2GB lowmem (2G/2G user/kernel split)"
+ 	config VMSPLIT_1G
+-		bool "1G/3G user/kernel split"
++		bool "3GB lowmem (1G/3G user/kernel split)"
+ endchoice
+ 
+ config PAGE_OFFSET
+Index: linux-2.6.22-ck1/kernel/Kconfig.hz
+===================================================================
+--- linux-2.6.22-ck1.orig/kernel/Kconfig.hz	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/kernel/Kconfig.hz	2007-07-10 14:55:24.000000000 +1000
+@@ -4,7 +4,7 @@
+ 
+ choice
+ 	prompt "Timer frequency"
+-	default HZ_250
++	default HZ_1000
+ 	help
+ 	 Allows the configuration of the timer frequency. It is customary
+ 	 to have the timer interrupt run at 1000 Hz but 100 Hz may be more
+@@ -13,8 +13,7 @@
+ 	 contention and cacheline bounces as a result of timer interrupts.
+ 	 Note that the timer interrupt occurs on each processor in an SMP
+ 	 environment leading to NR_CPUS * HZ number of timer interrupts
+-	 per second.
+-
++	 per second.Laptops may also show improved battery life.
+ 
+ 	config HZ_100
+ 		bool "100 HZ"
+@@ -23,13 +22,14 @@
+ 	  with lots of processors that may show reduced performance if
+ 	  too many timer interrupts are occurring.
+ 
+-	config HZ_250
++	config HZ_250_NODEFAULT
+ 		bool "250 HZ"
+ 	help
+-	 250 Hz is a good compromise choice allowing server performance
+-	 while also showing good interactive responsiveness even
+-	 on SMP and NUMA systems. If you are going to be using NTSC video
+-	 or multimedia, selected 300Hz instead.
++	 250 HZ is a lousy compromise choice allowing server interactivity
++	 while also showing desktop throughput and no extra power saving on
++	 laptops. Good for when you can't make up your mind.
++
++	 Recommend 100 or 1000 instead.
+ 
+ 	config HZ_300
+ 		bool "300 HZ"
+@@ -45,12 +45,76 @@
+ 	 1000 Hz is the preferred choice for desktop systems and other
+ 	 systems requiring fast interactive responses to events.
+ 
++	config HZ_1500
++		bool "1500 HZ"
++	help
++	 1500 Hz is an insane value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_2000
++		bool "2000 HZ"
++	help
++	 2000 Hz is an insane value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_3000
++		bool "3000 HZ"
++	help
++	 3000 Hz is an insane value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_4000
++		bool "4000 HZ"
++	help
++	 4000 Hz is an insane value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_5000
++		bool "5000 HZ"
++	help
++	 5000 Hz is an obscene value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_7500
++		bool "7500 HZ"
++	help
++	 7500 Hz is an obscene value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++	config HZ_10000
++		bool "10000 HZ"
++	help
++	 10000 Hz is an obscene value to use to run broken software that is Hz
++	 limited.
++
++	 Being over 1000, driver breakage is likely.
++
++
+ endchoice
+ 
+ config HZ
+ 	int
+ 	default 100 if HZ_100
+-	default 250 if HZ_250
++	default 250 if HZ_250_NODEFAULT
+ 	default 300 if HZ_300
+ 	default 1000 if HZ_1000
++	default 1500 if HZ_1500
++	default 2000 if HZ_2000
++	default 3000 if HZ_3000
++	default 4000 if HZ_4000
++	default 5000 if HZ_5000
++	default 7500 if HZ_7500
++	default 10000 if HZ_10000
+ 
+Index: linux-2.6.22-ck1/arch/i386/defconfig
+===================================================================
+--- linux-2.6.22-ck1.orig/arch/i386/defconfig	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/arch/i386/defconfig	2007-07-10 14:55:23.000000000 +1000
+@@ -226,10 +226,10 @@
+ # CONFIG_IRQBALANCE is not set
+ CONFIG_SECCOMP=y
+ # CONFIG_HZ_100 is not set
+-CONFIG_HZ_250=y
++# CONFIG_HZ_250 is not set
+ # CONFIG_HZ_300 is not set
+-# CONFIG_HZ_1000 is not set
+-CONFIG_HZ=250
++CONFIG_HZ_1000=y
++CONFIG_HZ=1000
+ # CONFIG_KEXEC is not set
+ # CONFIG_CRASH_DUMP is not set
+ CONFIG_PHYSICAL_START=0x100000
+Index: linux-2.6.22-ck1/arch/x86_64/defconfig
+===================================================================
+--- linux-2.6.22-ck1.orig/arch/x86_64/defconfig	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/arch/x86_64/defconfig	2007-07-10 14:55:23.000000000 +1000
+@@ -185,10 +185,10 @@
+ CONFIG_SECCOMP=y
+ # CONFIG_CC_STACKPROTECTOR is not set
+ # CONFIG_HZ_100 is not set
+-CONFIG_HZ_250=y
++# CONFIG_HZ_250 is not set
+ # CONFIG_HZ_300 is not set
+-# CONFIG_HZ_1000 is not set
+-CONFIG_HZ=250
++CONFIG_HZ_1000=y
++CONFIG_HZ=1000
+ CONFIG_K8_NB=y
+ CONFIG_GENERIC_HARDIRQS=y
+ CONFIG_GENERIC_IRQ_PROBE=y
+Index: linux-2.6.22-ck1/include/linux/jiffies.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/jiffies.h	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/jiffies.h	2007-07-10 14:55:24.000000000 +1000
+@@ -29,6 +29,12 @@
+ # define SHIFT_HZ	9
+ #elif HZ >= 768 && HZ < 1536
+ # define SHIFT_HZ	10
++#elif HZ >= 1536 && HZ < 3072
++# define SHIFT_HZ	11
++#elif HZ >= 3072 && HZ < 6144
++# define SHIFT_HZ	12
++#elif HZ >= 6144 && HZ < 12288
++# define SHIFT_HZ	13
+ #else
+ # error You lose.
+ #endif
+Index: linux-2.6.22-ck1/include/net/inet_timewait_sock.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/net/inet_timewait_sock.h	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/include/net/inet_timewait_sock.h	2007-07-10 14:55:24.000000000 +1000
+@@ -38,8 +38,8 @@
+  * If time > 4sec, it is "slow" path, no recycling is required,
+  * so that we select tick to get range about 4 seconds.
+  */
+-#if HZ <= 16 || HZ > 4096
+-# error Unsupported: HZ <= 16 or HZ > 4096
++#if HZ <= 16 || HZ > 16384
++# error Unsupported: HZ <= 16 or HZ > 16384
+ #elif HZ <= 32
+ # define INET_TWDR_RECYCLE_TICK (5 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
+ #elif HZ <= 64
+@@ -54,8 +54,12 @@
+ # define INET_TWDR_RECYCLE_TICK (10 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
+ #elif HZ <= 2048
+ # define INET_TWDR_RECYCLE_TICK (11 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
+-#else
++#elif HZ <= 4096
+ # define INET_TWDR_RECYCLE_TICK (12 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
++#elif HZ <= 8192
++# define INET_TWDR_RECYCLE_TICK (13 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
++#else
++# define INET_TWDR_RECYCLE_TICK (14 + 2 - INET_TWDR_RECYCLE_SLOTS_LOG)
+ #endif
+ 
+ /* TIME_WAIT reaping mechanism. */
+Index: linux-2.6.22-ck1/init/calibrate.c
+===================================================================
+--- linux-2.6.22-ck1.orig/init/calibrate.c	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/init/calibrate.c	2007-07-10 14:55:24.000000000 +1000
+@@ -122,12 +122,12 @@
+ 		printk("Calibrating delay loop (skipped)... "
+ 			"%lu.%02lu BogoMIPS preset\n",
+ 			loops_per_jiffy/(500000/HZ),
+-			(loops_per_jiffy/(5000/HZ)) % 100);
++			(loops_per_jiffy * 10/(50000/HZ)) % 100);
+ 	} else if ((loops_per_jiffy = calibrate_delay_direct()) != 0) {
+ 		printk("Calibrating delay using timer specific routine.. ");
+ 		printk("%lu.%02lu BogoMIPS (lpj=%lu)\n",
+ 			loops_per_jiffy/(500000/HZ),
+-			(loops_per_jiffy/(5000/HZ)) % 100,
++			(loops_per_jiffy * 10/(50000/HZ)) % 100,
+ 			loops_per_jiffy);
+ 	} else {
+ 		loops_per_jiffy = (1<<12);
+@@ -166,7 +166,7 @@
+ 		/* Round the value and print it */
+ 		printk("%lu.%02lu BogoMIPS (lpj=%lu)\n",
+ 			loops_per_jiffy/(500000/HZ),
+-			(loops_per_jiffy/(5000/HZ)) % 100,
++			(loops_per_jiffy * 10/(50000/HZ)) % 100,
+ 			loops_per_jiffy);
+ 	}
+ 
+Index: linux-2.6.22-ck1/arch/i386/kernel/cpu/proc.c
+===================================================================
+--- linux-2.6.22-ck1.orig/arch/i386/kernel/cpu/proc.c	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/arch/i386/kernel/cpu/proc.c	2007-07-10 14:55:24.000000000 +1000
+@@ -157,7 +157,7 @@
+ 
+ 	seq_printf(m, "\nbogomips\t: %lu.%02lu\n",
+ 		     c->loops_per_jiffy/(500000/HZ),
+-		     (c->loops_per_jiffy/(5000/HZ)) % 100);
++		     (c->loops_per_jiffy * 10/(50000/HZ)) % 100);
+ 	seq_printf(m, "clflush size\t: %u\n\n", c->x86_clflush_size);
+ 
+ 	return 0;
+Index: linux-2.6.22-ck1/arch/i386/kernel/smpboot.c
+===================================================================
+--- linux-2.6.22-ck1.orig/arch/i386/kernel/smpboot.c	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/arch/i386/kernel/smpboot.c	2007-07-10 14:55:24.000000000 +1000
+@@ -1094,7 +1094,7 @@
+ 		"Total of %d processors activated (%lu.%02lu BogoMIPS).\n",
+ 		cpucount+1,
+ 		bogosum/(500000/HZ),
+-		(bogosum/(5000/HZ))%100);
++		(bogosum * 10/(50000/HZ))%100);
+ 	
+ 	Dprintk("Before bogocount - setting activated=1.\n");
+ 
+Index: linux-2.6.22-ck1/include/linux/nfsd/stats.h
+===================================================================
+--- linux-2.6.22-ck1.orig/include/linux/nfsd/stats.h	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/include/linux/nfsd/stats.h	2007-07-10 14:55:24.000000000 +1000
+@@ -35,8 +35,8 @@
+ 
+ };
+ 
+-/* thread usage wraps very million seconds (approx one fortnight) */
+-#define	NFSD_USAGE_WRAP	(HZ*1000000)
++/* thread usage wraps every one hundred thousand seconds (approx one day) */
++#define	NFSD_USAGE_WRAP	(HZ*100000)
+ 
+ #ifdef __KERNEL__
+ 
+Index: linux-2.6.22-ck1/arch/x86_64/kernel/setup.c
+===================================================================
+--- linux-2.6.22-ck1.orig/arch/x86_64/kernel/setup.c	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/arch/x86_64/kernel/setup.c	2007-07-10 14:55:24.000000000 +1000
+@@ -1047,7 +1047,7 @@
+ 		
+ 	seq_printf(m, "\nbogomips\t: %lu.%02lu\n",
+ 		   c->loops_per_jiffy/(500000/HZ),
+-		   (c->loops_per_jiffy/(5000/HZ)) % 100);
++		   (c->loops_per_jiffy * 10/(50000/HZ)) % 100);
+ 
+ 	if (c->x86_tlbsize > 0) 
+ 		seq_printf(m, "TLB size\t: %d 4K pages\n", c->x86_tlbsize);
+Index: linux-2.6.22-ck1/Makefile
+===================================================================
+--- linux-2.6.22-ck1.orig/Makefile	2007-07-10 14:54:59.000000000 +1000
++++ linux-2.6.22-ck1/Makefile	2007-07-10 14:55:24.000000000 +1000
+@@ -1,8 +1,9 @@
+ VERSION = 2
+ PATCHLEVEL = 6
+ SUBLEVEL = 22
+-EXTRAVERSION =
+-NAME = Holy Dancing Manatees, Batman!
++EXTRAVERSION = -ck1
++NAME = So long, and thanks for all the fish
++JANAME = ã•ã‚ˆã†ãªã‚‰ã€ã„ã¾ã¾ã§é­šã‚’ã‚ã‚ŠãŒã¨ã†
+ 
+ # *DOCUMENTATION*
+ # To see a list of typical targets execute "make help"
diff --git a/pkgs/os-specific/linux/kqemu/1.3.0pre11.nix b/pkgs/os-specific/linux/kqemu/1.3.0pre11.nix
new file mode 100644
index 00000000000..20e738e0692
--- /dev/null
+++ b/pkgs/os-specific/linux/kqemu/1.3.0pre11.nix
@@ -0,0 +1,32 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://fabrice.bellard.free.fr/qemu/kqemu-1.3.0pre11.tar.gz;
+			sha256 = "03svg2x52ziglf9r9irf6ziiz8iwa731fk1mdskwdip5jxbyy6jl";
+		};
+		buildInputs = [];
+		configureFlags = [''--prefix=$out'' ''--kernel-path=$(ls -d ${kernel}/lib/modules/*/build)''];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+  debugStep = FullDepEntry (''
+  	cat config-host.mak
+  '') [minInit];
+  preConfigure = FullDepEntry ('' 
+  	sed -e 's/`uname -r`/'"$(basename ${kernel}/lib/modules/*)"'/' -i install.sh
+  	sed -e '/kernel_path=/akernel_path=$out$kernel_path' -i install.sh
+	sed -e '/depmod/d' -i install.sh
+	cat install.sh
+  '') [minInit doUnpack];
+in
+stdenv.mkDerivation rec {
+	name = "kqemu-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [preConfigure doConfigure debugStep doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Kernel module for Qemu acceleration
+";
+	};
+}
diff --git a/pkgs/os-specific/linux/kvm/57.nix b/pkgs/os-specific/linux/kvm/57.nix
new file mode 100644
index 00000000000..c7859eed178
--- /dev/null
+++ b/pkgs/os-specific/linux/kvm/57.nix
@@ -0,0 +1,24 @@
+{stdenv, fetchurl, kernelHeaders, zlib, e2fsprogs, SDL, alsaLib}:
+   
+assert stdenv.isLinux;
+   
+stdenv.mkDerivation {
+  name = "kvm-57";
+   
+  src = fetchurl {
+    url = mirror://sourceforge/kvm/kvm-57.tar.gz;
+    sha256 = "016h5pf59fyz7skzsaprii2mdpxpb8hfnnr1w475qcfyy6ccr9r0";
+  };
+
+  configureFlags = "--with-patched-kernel --kerneldir=${kernelHeaders}";
+
+  # e2fsprogs is needed for libuuid.
+  buildInputs = [zlib e2fsprogs SDL alsaLib];
+
+  preConfigure = "for i in configure user/configure; do substituteInPlace $i --replace /bin/bash $shell; done";
+
+  meta = {
+    homepage = http://kvm.qumranet.com/;
+    description = "A full virtualization solution for Linux on x86 hardware containing virtualization extensions";
+  };
+}
diff --git a/pkgs/os-specific/linux/module-init-tools/aggregator.nix b/pkgs/os-specific/linux/module-init-tools/aggregator.nix
new file mode 100644
index 00000000000..76111eacfd2
--- /dev/null
+++ b/pkgs/os-specific/linux/module-init-tools/aggregator.nix
@@ -0,0 +1,38 @@
+args : with args;
+	let localDefs = builderDefs {
+		addSbinPath = true;
+		src = "";
+		buildInputs = [module_init_tools];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let 
+
+doCollect = FullDepEntry (''
+ensureDir $out/lib/modules
+cd $out/
+for i in $moduleSources; do 
+	cp -rfs $i/* .
+	chmod -R u+w .
+done
+rm -rf nix-support
+cd lib/modules/
+rm */modules.*
+#  linux-* will pass the new kernel version to depmod to take rather than `uname -r` (see man page)
+MODULE_DIR=$PWD/ depmod -a $(basename lib/modules/2.*)
+cd $out/
+'') [minInit addInputs defEnsureDir];
+in
+stdenv.mkDerivation rec {
+	name = "kernel-modules";
+	inherit moduleSources;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doCollect doForceShare doPropagate]);
+	meta = {
+		description = "
+		A directory to hold all  the modules, including those 
+		built separately from kernel. Later mentioned directories in 
+		moduleSources have higher priority.
+";
+	};
+}
diff --git a/pkgs/os-specific/linux/ndiswrapper/default.nix b/pkgs/os-specific/linux/ndiswrapper/default.nix
new file mode 100644
index 00000000000..5138ae4f9b8
--- /dev/null
+++ b/pkgs/os-specific/linux/ndiswrapper/default.nix
@@ -0,0 +1,28 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "ndiswrapper-1.49-stable";
+
+  # need at least .config and include 
+  inherit kernel;
+
+  buildPhase = "
+    make KBUILD=\$kernel/lib/modules/*/build;
+  ";
+
+  # should we use unstable? 
+  src = args.fetchurl {
+    url = http://kent.dl.sourceforge.net/sourceforge/ndiswrapper/ndiswrapper-1.49.tar.gz;
+    sha256 = "1b9nqkk7gv6gffzj9b8mjy5myxf2afwpyr2n5wbfsylf15dvvvjr";
+  };
+
+  buildInputs =[kernelHeaders kernel];
+
+  # this is a patch against svn head, not stable version
+  patches = [./prefix.patch];
+
+  meta = { 
+      description = "Ndis driver wrapper for the Linux kernel";
+      homepage = http://sourceforge.net/projects/ndiswrapper;
+      license = "GPL";
+  };
+}
diff --git a/pkgs/os-specific/linux/ndiswrapper/prefix.patch b/pkgs/os-specific/linux/ndiswrapper/prefix.patch
new file mode 100644
index 00000000000..7d44c4fe757
--- /dev/null
+++ b/pkgs/os-specific/linux/ndiswrapper/prefix.patch
@@ -0,0 +1,78 @@
+diff --git a/ndiswrapper/driver/Makefile b/ndiswrapper/driver/Makefile
+index b0c2a9d..8907a05 100644
+--- a/ndiswrapper/driver/Makefile
++++ b/ndiswrapper/driver/Makefile
+@@ -119,6 +119,10 @@ ifdef WRAP_PREEMPT
+ MOD_CFLAGS += -DWRAP_PREEMPT
+ endif
+ 
++ifdef DIST_DESTDIR
++MOD_CFLAGS += -DPREFIX=\"$(DIST_DESTDIR)\"
++endif
++
+ .PHONY: prereq_check gen_exports clean dist_clean install stack_check
+ 
+ all : prereq_check win2lin_stubs.h gen_exports compat.h default stack_check
+@@ -355,7 +359,7 @@ install: prereq_check win2lin_stubs.h gen_exports compat.h default stack_check
+ 	echo $(INST_DIR)
+ 	mkdir -p $(INST_DIR)
+ 	install -m 0644 $(MODULE) $(INST_DIR)
+-	-@/bin/rm -rf $(SRC_DIR)/.tmp_versions
++	-@rm -rf $(SRC_DIR)/.tmp_versions
+ ifndef DIST_DESTDIR
+ 	-/sbin/depmod -a $(KVERS) -b $(DESTDIR)
+ endif
+diff --git a/ndiswrapper/driver/loader.c b/ndiswrapper/driver/loader.c
+index 930606f..9a8e9f0 100644
+--- a/ndiswrapper/driver/loader.c
++++ b/ndiswrapper/driver/loader.c
+@@ -106,7 +106,7 @@ struct wrap_driver *load_wrap_driver(struct wrap_device *wd)
+ 			EXIT1(return NULL);
+ 		}
+ 		INIT_COMPLETION(loader_complete);
+-		ret = call_usermodehelper("/sbin/loadndisdriver", argv, env
++		ret = call_usermodehelper(USERMOD_HELPER, argv, env
+ #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
+ 					  , 1
+ #endif
+@@ -272,7 +272,7 @@ struct wrap_bin_file *get_bin_file(char *bin_file_name)
+ 			EXIT1(return NULL);
+ 		}
+ 		INIT_COMPLETION(loader_complete);
+-		ret = call_usermodehelper("/sbin/loadndisdriver", argv, env
++		ret = call_usermodehelper(USERMOD_HELPER, argv, env
+ #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
+ 					  , 1
+ #endif
+@@ -711,7 +711,7 @@ struct wrap_device *load_wrap_device(struct load_device *load_device)
+ 			EXIT1(return NULL);
+ 		}
+ 		INIT_COMPLETION(loader_complete);
+-		ret = call_usermodehelper("/sbin/loadndisdriver", argv, env
++		ret = call_usermodehelper(USERMOD_HELPER, argv, env
+ #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
+ 					  , 1
+ #endif
+diff --git a/ndiswrapper/driver/ndiswrapper.h b/ndiswrapper/driver/ndiswrapper.h
+index 4a78dc6..c11a074 100644
+--- a/ndiswrapper/driver/ndiswrapper.h
++++ b/ndiswrapper/driver/ndiswrapper.h
+@@ -19,8 +19,17 @@
+ #define DRIVER_VERSION "1.50"
+ #define UTILS_VERSION "1.9"
+ 
++#ifndef PREFIX
++#define PREFIX
++#endif
++
+ #define DRIVER_NAME "ndiswrapper"
+-#define DRIVER_CONFIG_DIR "/etc/ndiswrapper"
++
++#ifndef DRIVER_CONFIG_DIR
++#  define DRIVER_CONFIG_DIR PREFIX "/etc/ndiswrapper"
++#endif
++
++#define USERMOD_HELPER PREFIX "/sbin/loadndisdriver"
+ 
+ #define SSID_MAX_WPA_IE_LEN 40
+ #define NDIS_ESSID_MAX_SIZE 32
diff --git a/pkgs/os-specific/linux/nfs-utils/default.nix b/pkgs/os-specific/linux/nfs-utils/default.nix
new file mode 100644
index 00000000000..18278ef3c34
--- /dev/null
+++ b/pkgs/os-specific/linux/nfs-utils/default.nix
@@ -0,0 +1,17 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "nfs-utils-1.1.1";
+
+  src = fetchurl {
+    url = mirror://sourceforge/nfs/nfs-utils-1.1.1.tar.gz;
+    sha256 = "0aa434cv7lgbrhks0rzhwxvbk2zsa17kjwxqjrrh87zrv9d2sr1x";
+  };
+
+  buildInputs = [kernelHeaders tcp_wrapper];
+
+  meta = { 
+      description = "nfs utils";
+      homepage = http://nfs.sourceforge.net/;
+      license = "GPL2";
+  };
+}
diff --git a/pkgs/os-specific/linux/nvidia/builder.sh b/pkgs/os-specific/linux/nvidia/builder.sh
index 9ec3428e878..00d70d6198f 100755
--- a/pkgs/os-specific/linux/nvidia/builder.sh
+++ b/pkgs/os-specific/linux/nvidia/builder.sh
@@ -1,101 +1,77 @@
 source $stdenv/setup
 
-echo "Building linux driver against kernel: " $kernelOutPath;
-echo "LD_LIBRARY_PATH: $LD_LIBRARY_PATH"
-
-echo $nvidiasrc
-cp $nvidiasrc .
-chmod 755 ./*-NVIDIA*
-./*-NVIDIA* -x
-cd NVIDIA*/
-
-cd usr/src/nv/
-pwd -P
-
-#Clean up
-#make clean
-
-#Create the module
-echo $out
-mkdir $out
-make SYSSRC=$kernelOutPath/lib/modules/2.*/build/ module	
-
-#go to the usr dir of the nvidia package
-cd ../../
-
-echo "Copying all files to " $out/lib""
-
-cp -R * $out
-
-#add extra symlinks in $out
-ln -snf $out/lib/libGLcore.so.$versionNumber $out/lib/libGLcore.so
-ln -snf $out/lib/libGLcore.so.$versionNumber $out/lib/libGLcore.so.1
-ln -snf $out/lib/libGL.so.$versionNumber $out/lib/libGL.so
-ln -snf $out/lib/libGL.so.$versionNumber $out/lib/libGL.so.1
-ln -snf $out/lib/libnvidia-cfg.so.$versionNumber $out/lib/libnvidia-cfg.so.1
-ln -snf $out/lib/libnvidia-tls.so.$versionNumber $out/lib/libnvidia-tls.so.1
-ln -snf $out/X11R6/lib/libXvMCNVIDIA.so.$versionNumber $out/X11R6/lib/libXvMCNVIDIA.so.1
-ln -snf $out/X11R6/lib/libXvMCNVIDIA.so.$versionNumber $out/lib/libXvMCNVIDIA.so.1
-ln -snf $out/X11R6/lib/modules/libnvidia-wfb.so.$versionNumber $out/X11R6/lib/modules/libnvidia-wfb.so.1
-ln -snf $out/X11R6/lib/modules/libnvidia-wfb.so.$versionNumber $out/lib/libnvidia-wfb.so.1
-ln -snf $out/X11R6/lib/modules/extensions/libglx.so.$versionNumber $out/X11R6/lib/modules/extensions/libglx.so.1
-ln -snf $out/X11R6/lib/modules/extensions/libglx.so.$versionNumber $out/lib/libglx.so.1
-
-#TODO: patchelf binaries !
-#patchelf --set-interpreter ${path glibc TODO  /lib/ld-linux.so.2 $out/bin/....
-
-#from dep on xorg-sys-opengl: add symlinks in /usr/lib/ (especially libGL.so.1) to the real location...
-
-ensureDir /usr/lib/
-cd /usr/lib
-ln -snf $out/lib/libGLcore.so.$versionNumber libGLcore.so.1
-ln -snf $out/lib/libGL.la libGL.la
-ln -snf $out/lib/libGL.so.$versionNumber libGL.so.1
-ln -snf $out/lib/libnvidia-cfg.so.$versionNumber libnvidia-cfg.so.1
-ln -snf $out/lib/libnvidia-tls.so.$versionNumber libnvidia-tls.so.1
-ensureDir /usr/lib/tls/
-ln -snf $out/lib/tls/libnvidia-tls.so.$versionNumber /usr/lib/tls/libnvidia-tls.so.1
-ln -snf $out/X11R6/lib/modules/extensions/libglx.so.$versionNumber libglx.so.1
-ln -snf $out/X11R6/lib/modules/libnvidia-wfb.so.$versionNumber libnvidia-wfb.so.1
-ln -snf $out/X11R6/lib/modules/drivers/nvidia_drv.so nvidia_drv.so
-ln -snf $out/X11R6/lib/libXvMCNVIDIA.so.$versionNumber libXvMCNVIDIA.so.1
-ln -snf $out/bin/tls_test_dso.so tls_test_dso.so
-ln -snf $out/src/nv/nvidia.ko nvidia.ko
-
-echo "YOU! need to add symlinks as root to the libs in the current $xorgOutPath/lib/xorg/modules/extensions/     (especially libglx.so)"
-rwlibs="
-cd $xorgOutPath/lib/xorg/modules/extensions/;
-mv libglx.so libglx.so.org;
-mv libglx.la libglx.la.org;
-mv libGLcore.so libGLcore.so.org;
-ln -snf /usr/lib/libglx.so.1 libglx.so;
-ln -snf /usr/lib/libglx.so.1 libglx.so.1;
-ln -snf /usr/lib/libGLcore.so.1 libGLcore.so;
-ln -snf /usr/lib/libGLcore.so.1 libGLcore.so.1;
-ln -snf /usr/lib/libGL.so.1 libGL.so;
-ln -snf /usr/lib/libGL.so.1 libGL.so.1;
-ln -snf /usr/lib/libglx.la libglx.la;
-ln -snf /usr/lib/libglx.so.1 libglx.so;
-ln -snf /usr/lib/libglx.so.1 libglx.so.1;
-ln -snf /usr/lib/nvidia_drv.so nvidia_drv.so;
-
-# rm /var/run/opengl-driver;
-ln -snf /var/run/opengl-driver $out;
-
-kerneldrvnvpath=$kernelOutPath/lib/modules/*-default/kernel/drivers/video/nvidia;
-#echo TODO kerneldrvnvpath: \$kerneldrvnvpath
-ln -snf $out/src/nv/nvidia.ko \$kerneldrvnvpath/nvidia.ko;
-"
-#TODO ADD ln -sf is sometimes not strong enough ...
-
-rwlibsfile="$out/bin/nvidia-rewriteLibs.sh"
-
-echo "--------------------------------------------------------"
-echo "YOU MUST RUN $rwlibsfile as ROOT after this installation"
-echo "--------------------------------------------------------"
-echo $rwlibs > $rwlibsfile
-chmod 755 $rwlibsfile
-
-sleep 5
+dontPatchELF=1 # must keep libXv, $out in RPATH
 
 
+unpackFile() {
+    sh $src -x
+}
+
+
+buildPhase=myBuildPhase
+myBuildPhase() {
+    echo "Building linux driver against kernel: " $kernel;
+
+    cd usr/src/nv/
+
+    # Workaround: get it to build on kernels that have CONFIG_XEN set.
+    # Disable the test, apply a patch to disable the Xen functionality.
+    #substituteInPlace Makefile.kbuild --replace xen_sanity_check fnord
+    #patch -p1 < $xenPatch
+
+    # Create the module.
+    kernelVersion=$(cd $kernel/lib/modules && ls)
+    sysSrc=$(echo $kernel/lib/modules/$kernelVersion/build/)
+    unset src # used by the nv makefile
+    make SYSSRC=$sysSrc module
+    cd ../../..
+}
+
+
+installPhase=myInstallPhase
+myInstallPhase() {
+
+    # Install the kernel module.
+    ensureDir $out/lib/modules/$kernelVersion/misc
+    cp usr/src/nv/nvidia.ko $out/lib/modules/$kernelVersion/misc
+
+    # Install libGL and friends.
+    cp -prd usr/lib/* usr/X11R6/lib/libXv* $out/lib/
+
+    ln -snf libGLcore.so.$versionNumber $out/lib/libGLcore.so
+    ln -snf libGLcore.so.$versionNumber $out/lib/libGLcore.so.1
+    ln -snf libGL.so.$versionNumber $out/lib/libGL.so
+    ln -snf libGL.so.$versionNumber $out/lib/libGL.so.1
+    ln -snf libnvidia-cfg.so.$versionNumber $out/lib/libnvidia-cfg.so.1
+    ln -snf libnvidia-tls.so.$versionNumber $out/lib/libnvidia-tls.so.1
+    ln -snf libnvidia-tls.so.$versionNumber $out/lib/tls/libnvidia-tls.so.1
+    ln -snf libXvMCNVIDIA.so.$versionNumber $out/lib/libXvMCNVIDIA_dynamic.so.1
+    ln -snf libcuda.so.$versionNumber $out/lib/libcuda.so.1
+
+    # Install the X driver.
+    ensureDir $out/lib/xorg/modules
+    cp -prd usr/X11R6/lib/modules/* $out/lib/xorg/modules/
+
+    ln -snf libnvidia-wfb.so.$versionNumber $out/lib/xorg/modules/libnvidia-wfb.so.1
+    ln -snf libglx.so.$versionNumber $out/lib/xorg/modules/extensions/libglx.so
+
+    # Install the programs.
+    ensureDir $out/bin
+
+    fullPath=$out/lib
+    for i in $libPath; do
+	fullPath=$fullPath:$i/lib
+    done
+
+    for i in nvidia-settings nvidia-xconfig; do
+	cp usr/bin/$i $out/bin/$i
+	patchelf --interpreter "$(cat $NIX_GCC/nix-support/dynamic-linker)" \
+	    --set-rpath $fullPath $out/bin/$i
+    done
+    
+    # Header files etc.
+    cp -prd usr/include usr/share $out
+}
+
+
+genericBuild
diff --git a/pkgs/os-specific/linux/nvidia/default.nix b/pkgs/os-specific/linux/nvidia/default.nix
index d4f1c8ac9bc..c8eaa0a8936 100644
--- a/pkgs/os-specific/linux/nvidia/default.nix
+++ b/pkgs/os-specific/linux/nvidia/default.nix
@@ -1,46 +1,26 @@
-{ stdenv
-, fetchurl
-
-, kernel
-, coreutils
-, xorg_server
-
-#deps
-,libXext, libX11
-
-}:
+{stdenv, fetchurl, kernel, xlibs, gtkLibs}:
 
 let 
 
-  versionNumber = "100.14.19";  #important ! to also update this if the sources are updated, this is used as follows: extensions/libglx.so.$versionNumber
+  versionNumber = "169.09";
 
 in
+
 stdenv.mkDerivation {
   name = "nvidiaDrivers-" + versionNumber;
   builder = ./builder.sh;
   
-  
-  nvidiasrc = fetchurl {										#we cannot use $src since this variable is also used in the nvidia sources
-    #url = http://www.denbreejen.net/public/nixos/NVIDIA-Linux-x86-1.0-9755-pkg1.run;
-    #sha256 = "1985373866b1dcae80f3da66dbbbd3c28ad76e75a620865be321ee870ad9d1ea";
-    #url = http://us.download.nvidia.com/XFree86/Linux-x86/100.14.11/NVIDIA-Linux-x86-100.14.11-pkg1.run;
-    #sha256 = "8665370e590328cc5bf3d13737739a80dacbfb6844436cab03c992e84bf16b0c";
-    url = http://us.download.nvidia.com/XFree86/Linux-x86/100.14.19/NVIDIA-Linux-x86-100.14.19-pkg1.run;
-    sha256 = "4dc97d8ff5340954f3cd446093636261c54b147e9721eb295574207d79e9a7e7";
+  src = fetchurl {
+    url = "http://us.download.nvidia.com/XFree86/Linux-x86/${versionNumber}/NVIDIA-Linux-x86-${versionNumber}-pkg1.run";
+    sha256 = "1m3k2jyxi3xxpm6890y0d97jisnxiyyay59ss2r9abyvpkv3by8i";
   };
-  inherit versionNumber;  
 
-  kernelOutPath = kernel.outPath;
-  xorgOutPath = xorg_server.outPath;
+  #xenPatch = ./nvidia-2.6.24-xen.patch;
 
-  buildInputs = [
-    libXext libX11
-  ];
+  inherit versionNumber kernel;
 
-  propagatedBuildInputs = [
-    libX11 libXext
+  libPath = [
+    gtkLibs.gtk gtkLibs.atk gtkLibs.pango gtkLibs.glib 
+    xlibs.libXext xlibs.libX11 xlibs.libXv
   ];
-
-  NIX_LDFLAGS = "-rpath ${libX11}/lib -rpath ${libXext}/lib";
-  LD_LIBRARY_PATH = "${libX11}/lib:${libXext}/lib/";
 }
diff --git a/pkgs/os-specific/linux/radeontools/default.nix b/pkgs/os-specific/linux/radeontools/default.nix
index 67d6cc4575f..d4d39606d62 100644
--- a/pkgs/os-specific/linux/radeontools/default.nix
+++ b/pkgs/os-specific/linux/radeontools/default.nix
@@ -1,8 +1,8 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "radeontool-1.5";
 
-  inherit (args) pciutils;
+  inherit pciutils;
 
   # Don't know wether it's a good idea to hardcode the lspci path..
   # But it will work on nix..
@@ -12,7 +12,7 @@ args.stdenv.mkDerivation {
     cd ..
   ";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://fdd.com/software/radeon/radeontool-1.5.tar.gz;
     sha256 = "0qbkawhhq0y0gqbbql7q04y0v0hims5c4jkjsbc1y03rf9kr10ar";
   };
diff --git a/pkgs/os-specific/linux/reiser4progs/default.nix b/pkgs/os-specific/linux/reiser4progs/default.nix
new file mode 100644
index 00000000000..235b2b8381b
--- /dev/null
+++ b/pkgs/os-specific/linux/reiser4progs/default.nix
@@ -0,0 +1,21 @@
+{stdenv, fetchurl, libaal}:
+
+stdenv.mkDerivation {
+  name = "reiser4progs-1.0.6";
+
+  src = fetchurl {
+    url = http://chichkin_i.zelnet.ru/namesys/reiser4progs-1.0.6.tar.gz;
+    sha256 = "0x6m6px19hz54r8q4wwpf437qmqh44c5ddw9846isr64zs2rpld0";
+  };
+
+  buildInputs = [libaal];
+
+  preInstall = ''
+    substituteInPlace Makefile --replace ./run-ldconfig true
+  '';
+
+  meta = {
+    homepage = http://www.namesys.com/;
+    description = "Reiser4 utilities";
+  };
+}
diff --git a/pkgs/os-specific/linux/reiserfsprogs/default.nix b/pkgs/os-specific/linux/reiserfsprogs/default.nix
index 49d018175d2..1fc4fed12d5 100644
--- a/pkgs/os-specific/linux/reiserfsprogs/default.nix
+++ b/pkgs/os-specific/linux/reiserfsprogs/default.nix
@@ -2,14 +2,15 @@ args: with args;
 
 stdenv.mkDerivation {
   name = "reiserfsprogs-3.6.19";
-  src = fetchurl {
-      url = ftp://ftp.namesys.com/pub/reiserfsprogs/reiserfsprogs-3.6.19.tar.gz;
-      sha256 = "1gv8gr0l5l2j52540y2wj9c9h7fn0r3vabykf95748ydmr9jr1n0";
-    };
-
-  homepage=http://www.namesys.com/;
 
-  description="Reiserfs Utilities";
+  src = fetchurl {
+    url = http://chichkin_i.zelnet.ru/namesys/reiserfsprogs-3.6.19.tar.gz;
+    sha256 = "1gv8gr0l5l2j52540y2wj9c9h7fn0r3vabykf95748ydmr9jr1n0";
+  };
 
-  license="GPL-2";
+  meta = {
+    homepage = http://www.namesys.com/;
+    description = "Reiserfs utilities";
+    license = "GPL-2";
+  };
 }
diff --git a/pkgs/os-specific/linux/sdparm/1.02.nix b/pkgs/os-specific/linux/sdparm/1.02.nix
new file mode 100644
index 00000000000..edff04444e0
--- /dev/null
+++ b/pkgs/os-specific/linux/sdparm/1.02.nix
@@ -0,0 +1,22 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://sg.torque.net/sg/p/sdparm-1.02.tgz;
+			sha256 = "13acyg6r65gypdprjhfkmvaykgfcj1riwpnycpvv9znzgq9fxsiv";
+		};
+
+		buildInputs = [];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "sdparm-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	SCSI parameters utility.
+";
+	};
+}
diff --git a/pkgs/os-specific/linux/squashfs/default.nix b/pkgs/os-specific/linux/squashfs/default.nix
index 1f2bde7feac..00ce8fba56e 100644
--- a/pkgs/os-specific/linux/squashfs/default.nix
+++ b/pkgs/os-specific/linux/squashfs/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl, zlib}:
 
 stdenv.mkDerivation {
-  name = "squashfs-3.1-r2";
+  name = "squashfs-3.3";
   builder = ./builder.sh;
   src = fetchurl {
-    url = mirror://sourceforge/squashfs/squashfs3.1-r2.tar.gz;
-    md5 = "c252e5286b142afa54ca49829c51a33f";
+    url = mirror://sourceforge/squashfs/squashfs3.3.tgz;
+    sha256 = "1j55m26nyvlbld4yxad0r6s1f4rdw9yg89y2gv93ihkx3rx048w4";
   };
   buildInputs = [zlib];
 }
diff --git a/pkgs/os-specific/linux/sysklogd/builder.sh b/pkgs/os-specific/linux/sysklogd/builder.sh
index 9f2b8d9282c..62df45ea7c9 100644
--- a/pkgs/os-specific/linux/sysklogd/builder.sh
+++ b/pkgs/os-specific/linux/sysklogd/builder.sh
@@ -3,7 +3,8 @@ source $stdenv/setup
 prefix=$out
 export prefix
 
-installFlags="BINDIR=$out/sbin MANDIR=$out/share/man"
+installFlags="BINDIR=$out/sbin MANDIR=$out/share/man INSTALL=install"
+patchPhase="sed -e 's@-o \${MAN_USER} -g \${MAN_GROUP} -m \${MAN_PERMS} @@' -i Makefile"
 
 ensureDir "$out/share/man/man8/"
 ensureDir "$out/share/man/man5/"
diff --git a/pkgs/os-specific/linux/sysklogd/default.nix b/pkgs/os-specific/linux/sysklogd/default.nix
index d991d7e653e..2fe27add5bf 100644
--- a/pkgs/os-specific/linux/sysklogd/default.nix
+++ b/pkgs/os-specific/linux/sysklogd/default.nix
@@ -1,11 +1,10 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "sysklogd-1.4.1";
+  name = "sysklogd-1.5";
   builder = ./builder.sh;
   src = fetchurl {
-    url = http://www.infodrom.org/projects/sysklogd/download/sysklogd-1.4.1.tar.gz;
-    md5 = "d214aa40beabf7bdb0c9b3c64432c774";
+    url = http://www.infodrom.org/projects/sysklogd/download/sysklogd-1.5.tar.gz;
+    sha256 = "0wxpkrznqwz4dy11k90s2sqszwp7d4mlc0ag8288wa193plvhsb1";
   };
-  patches = [./sysklogd-1.4.1-cvs-20050525-local.diff ./sysklogd-1.4.1-asm.patch];
 }
diff --git a/pkgs/os-specific/linux/sysklogd/sysklogd-1.4.1-asm.patch b/pkgs/os-specific/linux/sysklogd/sysklogd-1.4.1-asm.patch
deleted file mode 100644
index a66bf70542b..00000000000
--- a/pkgs/os-specific/linux/sysklogd/sysklogd-1.4.1-asm.patch
+++ /dev/null
@@ -1,12 +0,0 @@
-diff -ruN sysklogd-1.4.1/module.h sysklogd-1.4.1.new/module.h
---- sysklogd-1.4.1/module.h	2005-09-28 15:53:58.000000000 +0200
-+++ sysklogd-1.4.1.new/module.h	2005-09-28 15:54:56.000000000 +0200
-@@ -28,7 +28,7 @@
-  *	recent content from Linux 2.4/2.6.
-  */
- 
--#include <asm/atomic.h>
-+/* #include <asm/atomic.h> */
- 
- #define MODULE_NAME_LEN 60
- 
diff --git a/pkgs/os-specific/linux/sysklogd/sysklogd-1.4.1-cvs-20050525-local.diff b/pkgs/os-specific/linux/sysklogd/sysklogd-1.4.1-cvs-20050525-local.diff
deleted file mode 100644
index 5f36fc5e535..00000000000
--- a/pkgs/os-specific/linux/sysklogd/sysklogd-1.4.1-cvs-20050525-local.diff
+++ /dev/null
@@ -1,901 +0,0 @@
-diff -ruN sysklogd-1.4.1/CHANGES sysklogd-1.4.1.new/CHANGES
---- sysklogd-1.4.1/CHANGES	2001-03-11 20:35:51.000000000 +0100
-+++ sysklogd-1.4.1.new/CHANGES	2006-03-14 16:22:13.000000000 +0100
-@@ -1,3 +1,42 @@
-+Version 1.4.2
-+
-+ . Dmitry V. Levin <ldv@altlinux.org>
-+   - Close file descriptor in FindSymbolFile() in ksym.c in order not to
-+     leak file descriptors.
-+ . Solar Designer <solar@openwall.com>
-+   - improve crunch_list()
-+   - Prevent potential buffer overflow in reading messages from the
-+     kernel log ringbuffer.
-+   - Ensure that "len" is not placed in a register, and that the
-+     endtty() signal handler is not installed too early which could
-+     cause a segmentation fault or worse.
-+ . Steve Grubb <linux_4ever@yahoo.com>
-+   - fix memory calculation in crunch_list()
-+ . Martin Schulze <joey@infodrom.org>
-+   - klogd will reconnect to the logger (mostly syslogd) after it went
-+     away
-+   - On heavily loaded system syslog will not spit out error messages
-+     anymore when recvfrom() results in EAGAIN
-+   - Makefile improvements
-+   - Local copy of module.h
-+   - Improved sysklogd.8
-+   - Always log with syslogd's timezone and locale
-+   - Remove trailing newline when forwarding messages
-+ . Jon Burgess <Jon_Burgess@eur.3com.com>
-+   - Moved the installation of the signal handler up a little bit so it
-+     guaranteed to be available when the child is forked, hence, fixing a
-+     race condition.  This used to create problems with UML and fast
-+     machines.
-+ . Greg Trounson <gregt@maths.otago.ac.nz>
-+   - Improved README.linux
-+ . Ulf Härnhammar <Ulf.Harnhammar.9485@student.uu.se>
-+   - Bondary check for fscanf() in InitKsyms() and CheckMapVersion()
-+ . Colin Phipps <cph@cph.demon.co.uk>
-+   - Don't block on the network socket in case of package los
-+ . Dirk Mueller <mueller@kde.org>
-+   - Don't crash when filesize limit is reached (e.g. without LFS)
-+
-+
- Version 1.4.1
- 
-  . klogd will set the console log level only if `-c' is given on the
-@@ -30,3 +69,9 @@
-  . Olaf Kirch <okir@caldera.de>
-    - Remove Unix Domain Sockets and switch to Datagram Unix Sockets
-  . Several bugfixes and improvements, please refer to the .c files
-+
-+
-+Local variables:
-+mode: indented-text
-+fill-column: 72
-+End:
-diff -ruN sysklogd-1.4.1/klogd.8 sysklogd-1.4.1.new/klogd.8
---- sysklogd-1.4.1/klogd.8	2001-03-11 20:35:51.000000000 +0100
-+++ sysklogd-1.4.1.new/klogd.8	2006-03-14 16:22:13.000000000 +0100
-@@ -3,8 +3,9 @@
- .\" Sun Jul 30 01:35:55 MET: Martin Schulze: Updates
- .\" Sun Nov 19 23:22:21 MET: Martin Schulze: Updates
- .\" Mon Aug 19 09:42:08 CDT 1996: Dr. G.W. Wettstein: Updates
-+.\" Fri Mar 11 17:11:46 CET 2005: Martin Schulze: sysctl updates
- .\"
--.TH KLOGD 8 "21 August, 1999" "Version 1.4" "Linux System Administration"
-+.TH KLOGD 8 "11 March 2005" "Version 1.4" "Linux System Administration"
- .SH NAME
- klogd \- Kernel Log Daemon
- .LP
-@@ -38,6 +39,12 @@
- .TP
- .BI "\-c " n
- Sets the default log level of console messages to \fIn\fR.
-+This should nowardays be configured with the
-+.BR sysctl (8)
-+program, e.g. via
-+.BI "sysctl kernel.printk=" n
-+or via
-+.IR /etc/sysctl.conf .
- .TP
- .B "\-d"
- Enable debugging mode.  This will generate \fBLOTS\fR of output to
-@@ -321,7 +328,7 @@
- .B klogd
- to reload the module symbol information whenever a protection fault
- is detected.  Caution should be used before invoking the program in
--\'paranoid\' mode.  The stability of the kernel and the operating
-+\&'paranoid\&' mode.  The stability of the kernel and the operating
- environment is always under question when a protection fault occurs.
- Since the klogd daemon must execute system calls in order to read the
- module symbol information there is the possibility that the system may
-diff -ruN sysklogd-1.4.1/klogd.c sysklogd-1.4.1.new/klogd.c
---- sysklogd-1.4.1/klogd.c	2001-03-11 20:40:10.000000000 +0100
-+++ sysklogd-1.4.1.new/klogd.c	2006-03-14 16:22:13.000000000 +0100
-@@ -243,6 +243,9 @@
-  *	people have submitted patches: Troels Walsted Hansen
-  *	<troels@thule.no>, Wolfgang Oertl <Wolfgang.Oertl@uibk.ac.at>
-  *	and Thomas Roessler.
-+ * Thu Apr 29 15:24:07 2004: Solar Designer <solar@openwall.com>
-+ *	Prevent potential buffer overflow in reading messages from the
-+ *	kernel log rinbuffer.
-  */
- 
- 
-@@ -938,7 +941,7 @@
- 	 * messages into this fresh buffer.
- 	 */
- 	memset(log_buffer, '\0', sizeof(log_buffer));
--	if ( (rdcnt = ksyslog(2, log_buffer, sizeof(log_buffer))) < 0 )
-+	if ( (rdcnt = ksyslog(2, log_buffer, sizeof(log_buffer)-1)) < 0 )
- 	{
- 		if ( errno == EINTR )
- 			return;
-diff -ruN sysklogd-1.4.1/ksym.c sysklogd-1.4.1.new/ksym.c
---- sysklogd-1.4.1/ksym.c	2000-09-12 23:53:31.000000000 +0200
-+++ sysklogd-1.4.1.new/ksym.c	2006-03-14 16:22:13.000000000 +0100
-@@ -105,6 +105,15 @@
-  *
-  * Tue Sep 12 23:48:12 CEST 2000: Martin Schulze <joey@infodrom.ffis.de>
-  *	Close symbol file in InitKsyms() when an error occurred.
-+ *
-+ * Thu Apr 29 18:07:16 CEST 2004: Dmitry Levin <ldv@altlinux.org>
-+ *	Close file descriptor in FindSymbolFile() in order not to leak
-+ *	file descriptors.
-+ *
-+ * Fri Jul 16 08:32:49 CEST 2004: Ulf Härnhammar <Ulf.Harnhammar.9485@student.uu.se>
-+ *	Added boundary check for fscanf() in InitKsyms() and
-+ *	CheckMapVersion() to prevent an unintended crash when reading
-+ *	an incorrect System.map.
-  */
- 
- 
-@@ -236,7 +245,7 @@
- 	 */
- 	while ( !feof(sym_file) )
- 	{
--		if ( fscanf(sym_file, "%lx %c %s\n", &address, &type, sym)
-+		if ( fscanf(sym_file, "%lx %c %511s\n", &address, &type, sym)
- 		    != 3 )
- 		{
- 			Syslog(LOG_ERR, "Error in symbol table input (#1).");
-@@ -344,6 +353,7 @@
- 		if ( (sym_file = fopen(symfile, "r")) != (FILE *) 0 ) {
- 			if (CheckMapVersion(symfile) == 1)
- 				file = symfile;
-+			fclose (sym_file);
- 		}
- 		if (sym_file == (FILE *) 0 || file == (char *) 0) {
- 			sprintf (symfile, "%s", *mf);
-@@ -352,6 +362,7 @@
- 			if ( (sym_file = fopen(symfile, "r")) != (FILE *) 0 ) {
- 				if (CheckMapVersion(symfile) == 1)
- 					file = symfile;
-+				fclose (sym_file);
- 			}
- 		}
- 
-@@ -533,7 +544,7 @@
- 		version = 0;
- 		while ( !feof(sym_file) && (version == 0) )
- 		{
--			if ( fscanf(sym_file, "%lx %c %s\n", &address, \
-+			if ( fscanf(sym_file, "%lx %c %511s\n", &address, \
- 				    &type, sym) != 3 )
- 			{
- 				Syslog(LOG_ERR, "Error in symbol table input (#2).");
-@@ -899,3 +910,11 @@
- 	return;
- }
- #endif
-+
-+/*
-+ * Local variables:
-+ *  c-indent-level: 8
-+ *  c-basic-offset: 8
-+ *  tab-width: 8
-+ * End:
-+ */
-diff -ruN sysklogd-1.4.1/ksym_mod.c sysklogd-1.4.1.new/ksym_mod.c
---- sysklogd-1.4.1/ksym_mod.c	2000-09-12 23:15:28.000000000 +0200
-+++ sysklogd-1.4.1.new/ksym_mod.c	2006-03-14 16:22:13.000000000 +0100
-@@ -78,6 +78,11 @@
-  *
-  * Tue Sep 12 23:11:13 CEST 2000: Martin Schulze <joey@infodrom.ffis.de>
-  *	Changed llseek() to lseek64() in order to skip a libc warning.
-+ *
-+ * Wed Mar 31 17:35:01 CEST 2004: Martin Schulze <joey@infodrom.org>
-+ *	Removed references to <linux/module.h> since it doesn't work
-+ *	anymore with its recent content from Linux 2.4/2.6, created
-+ *	module.h locally instead.
-  */
- 
- 
-@@ -89,11 +94,12 @@
- #include <errno.h>
- #include <sys/fcntl.h>
- #include <sys/stat.h>
-+#include "module.h"
- #if !defined(__GLIBC__)
- #include <linux/time.h>
--#include <linux/module.h>
-+#include <linux/linkage.h>
- #else /* __GLIBC__ */
--#include <linux/module.h>
-+#include <linux/linkage.h>
- extern __off64_t lseek64 __P ((int __fd, __off64_t __offset, int __whence));
- extern int get_kernel_syms __P ((struct kernel_sym *__table));
- #endif /* __GLIBC__ */
-@@ -107,7 +113,7 @@
- 
- #if !defined(__GLIBC__)
- /*
-- * The following bit uses some kernel/library magic to product what
-+ * The following bit uses some kernel/library magic to produce what
-  * looks like a function call to user level code.  This function is
-  * actually a system call in disguise.  The purpose of the getsyms
-  * call is to return a current copy of the in-kernel symbol table.
-diff -ruN sysklogd-1.4.1/Makefile sysklogd-1.4.1.new/Makefile
---- sysklogd-1.4.1/Makefile	1998-10-12 22:25:15.000000000 +0200
-+++ sysklogd-1.4.1.new/Makefile	2006-03-14 16:22:41.000000000 +0100
-@@ -4,12 +4,15 @@
- #CFLAGS= -g -DSYSV -Wall
- #LDFLAGS= -g
- CFLAGS= $(RPM_OPT_FLAGS) -O3 -DSYSV -fomit-frame-pointer -Wall -fno-strength-reduce
-+# -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE
- LDFLAGS= -s
- 
- # Look where your install program is.
--INSTALL = /usr/bin/install
--BINDIR = /usr/sbin
--MANDIR = /usr/man
-+INSTALL = install
-+
-+# Destination paths, set prefix=/opt if required
-+BINDIR = $(prefix)/usr/sbin
-+MANDIR = $(prefix)/usr/share/man
- 
- # There is one report that under an all ELF system there may be a need to
- # explicilty link with libresolv.a.  If linking syslogd fails you may wish
-@@ -34,8 +37,9 @@
- # The following define establishes ownership for the man pages.
- # Avery tells me that there is a difference between Debian and
- # Slackware.  Rather than choose sides I am leaving it up to the user.
--MAN_OWNER = root
--# MAN_OWNER = man
-+MAN_USER = root
-+MAN_GROUP = root
-+MAN_PERMS = 644
- 
- # The following define establishes the name of the pid file for the
- # syslogd daemon.  The library include file (paths.h) defines the
-@@ -116,7 +120,7 @@
- 	${INSTALL} -m 500 -s klogd ${BINDIR}/klogd
- 
- install_man:
--	${INSTALL} -o ${MAN_OWNER} -g ${MAN_OWNER} -m 644 sysklogd.8 ${MANDIR}/man8/sysklogd.8
--	${INSTALL} -o ${MAN_OWNER} -g ${MAN_OWNER} -m 644 syslogd.8 ${MANDIR}/man8/syslogd.8
--	${INSTALL} -o ${MAN_OWNER} -g ${MAN_OWNER} -m 644 syslog.conf.5 ${MANDIR}/man5/syslog.conf.5
--	${INSTALL} -o ${MAN_OWNER} -g ${MAN_OWNER} -m 644 klogd.8 ${MANDIR}/man8/klogd.8
-+	${INSTALL} -m ${MAN_PERMS} sysklogd.8 ${MANDIR}/man8/sysklogd.8
-+	${INSTALL} -m ${MAN_PERMS} syslogd.8 ${MANDIR}/man8/syslogd.8
-+	${INSTALL} -m ${MAN_PERMS} syslog.conf.5 ${MANDIR}/man5/syslog.conf.5
-+	${INSTALL} -m ${MAN_PERMS} klogd.8 ${MANDIR}/man8/klogd.8
-diff -ruN sysklogd-1.4.1/module.h sysklogd-1.4.1.new/module.h
---- sysklogd-1.4.1/module.h	1970-01-01 01:00:00.000000000 +0100
-+++ sysklogd-1.4.1.new/module.h	2006-03-14 16:22:13.000000000 +0100
-@@ -0,0 +1,90 @@
-+/*
-+    module.h - Miscellaneous module definitions
-+    Copyright (c) 1996 Richard Henderson <rth@tamu.edu>
-+    Copyright (c) 2004 Martin Schulze <joey@infodrom.org>
-+
-+    This file is part of the sysklogd package.
-+
-+    This program is free software; you can redistribute it and/or modify
-+    it under the terms of the GNU General Public License as published by
-+    the Free Software Foundation; either version 2 of the License, or
-+    (at your option) any later version.
-+
-+    This program is distributed in the hope that it will be useful,
-+    but WITHOUT ANY WARRANTY; without even the implied warranty of
-+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-+    GNU General Public License for more details.
-+
-+    You should have received a copy of the GNU General Public License
-+    along with this program; if not, write to the Free Software
-+    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-+*/
-+
-+/* ChangeLog:
-+ *
-+ * Wed Mar 31 17:35:01 CEST 2004: Martin Schulze <joey@infodrom.org>
-+ *	Created local copy of module.h based on the content of Linux
-+ *	2.2 since <linux/module.h> doesn't work anymore with its
-+ *	recent content from Linux 2.4/2.6.
-+ */
-+
-+#include <asm/atomic.h>
-+
-+#define MODULE_NAME_LEN 60
-+
-+struct kernel_sym
-+{
-+	unsigned long value;
-+	char name[MODULE_NAME_LEN];
-+};
-+
-+
-+struct list_head {
-+	struct list_head *next, *prev;
-+};
-+
-+
-+struct module_info
-+{
-+	unsigned long addr;
-+	unsigned long size;
-+	unsigned long flags;
-+	long usecount;
-+};
-+
-+
-+struct module
-+{
-+	unsigned long size_of_struct;	/* == sizeof(module) */
-+	struct module *next;
-+	const char *name;
-+	unsigned long size;
-+
-+	union
-+	{
-+		int usecount;
-+		long pad;
-+	} uc;				/* Needs to keep its size - so says rth */
-+
-+	unsigned long flags;		/* AUTOCLEAN et al */
-+
-+	unsigned nsyms;
-+	unsigned ndeps;
-+
-+	struct module_symbol *syms;
-+	struct module_ref *deps;
-+	struct module_ref *refs;
-+	int (*init)(void);
-+	void (*cleanup)(void);
-+	const struct exception_table_entry *ex_table_start;
-+	const struct exception_table_entry *ex_table_end;
-+#ifdef __alpha__
-+	unsigned long gp;
-+#endif
-+	/* Members past this point are extensions to the basic
-+	   module support and are optional.  Use mod_opt_member()
-+	   to examine them.  */
-+	const struct module_persist *persist_start;
-+	const struct module_persist *persist_end;
-+	int (*can_unload)(void);
-+};
-diff -ruN sysklogd-1.4.1/pidfile.c sysklogd-1.4.1.new/pidfile.c
---- sysklogd-1.4.1/pidfile.c	1998-02-10 23:37:12.000000000 +0100
-+++ sysklogd-1.4.1.new/pidfile.c	2006-03-14 16:22:13.000000000 +0100
-@@ -87,7 +87,7 @@
-   int fd;
-   int pid;
- 
--  if ( ((fd = open(pidfile, O_RDWR|O_CREAT, 0644)) == -1)
-+  if ( ((fd = open(pidfile, O_RDWR|O_CREAT|O_TRUNC, 0644)) == -1)
-        || ((f = fdopen(fd, "r+")) == NULL) ) {
-       fprintf(stderr, "Can't open or create %s.\n", pidfile);
-       return 0;
-diff -ruN sysklogd-1.4.1/README.1st sysklogd-1.4.1.new/README.1st
---- sysklogd-1.4.1/README.1st	1997-06-02 19:21:39.000000000 +0200
-+++ sysklogd-1.4.1.new/README.1st	2006-03-14 16:22:13.000000000 +0100
-@@ -1,5 +1,5 @@
--Very important information before using version 1.3
-----------------------------------------------------
-+Important information
-+---------------------
- 
- The included version of syslogd behaves in a slightly different manner
- to the one in former releases.  Please review the following important
-@@ -63,3 +63,10 @@
-   these scripts should remove all old .pid files found in /var/run.
-   This will insure that klogd and syslogd start properly even if prior
-   executions have been terminated harshly.
-+
-+* Large file support, i.e. support to write to log files that are
-+  larger than 2 GB is not part of syslogd, but a matter of the Glibc
-+  emitting different system calls to the kernel interface.  To support
-+  large files you'll have to compile syslogd with the compiler defines
-+  -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE so that glibc adjusts the
-+  system calls.
-diff -ruN sysklogd-1.4.1/README.linux sysklogd-1.4.1.new/README.linux
---- sysklogd-1.4.1/README.linux	1999-01-19 01:09:12.000000000 +0100
-+++ sysklogd-1.4.1.new/README.linux	2006-03-14 16:22:13.000000000 +0100
-@@ -40,12 +40,17 @@
- a useful addition to the software gene pool.
- 
- There is a mailing list covering this package and syslog in general.
--The lists address is sysklogd@Infodrom.North.DE .  To subscribe send a
--mail to Majordomo@Infodrom.North.DE with a line "subscribe sysklogd"
-+The lists address is infodrom-sysklogd@lists.infodrom.org .  To subscribe send a
-+mail to majordomo@lists.infodrom.org with a line "subscribe infodrom-sysklogd"
- in the message body.
- 
--New versions of this package will be available at Joey's ftp server.
--ftp://ftp.infodrom.north.de/pub/people/joey/sysklogd/
-+A second mailing list exists as infodrom-sysklogd-cvs@lists.infodrom.org.  Only
-+CVS messages and diffs are distributed there. Whenever new code is added to
-+sysklogd, CVS generates a mail from these changes which will be sent to
-+this list.  Discussions will take place on the first list.
-+
-+The latest version of this software can be found at:
-+http://www.infodrom.org/projects/sysklogd/download.php3
- 
- Best regards,
- 
-@@ -67,6 +72,6 @@
- 
- Martin Schulze
- Infodrom Oldenburg
--joey@linux.de
-+joey@infodrom.org
- 
--And a host of bug reporters whose contributions cannot be underestimated.
-+And a number of bug reporters whose contributions cannot be underestimated.
-diff -ruN sysklogd-1.4.1/sysklogd.8 sysklogd-1.4.1.new/sysklogd.8
---- sysklogd-1.4.1/sysklogd.8	2001-03-11 20:35:51.000000000 +0100
-+++ sysklogd-1.4.1.new/sysklogd.8	2006-03-14 16:22:13.000000000 +0100
-@@ -84,7 +84,7 @@
- .B MAXFUNIX
- within the syslogd.c source file.  An example for a chroot() daemon is
- described by the people from OpenBSD at
--http://www.psionic.com/papers/dns.html.
-+<http://www.guides.sk/psionic/dns/>.
- .TP
- .B "\-d"
- Turns on debug mode.  Using this the daemon will not proceed a 
-@@ -117,7 +117,8 @@
- between two \fI-- MARK --\fR lines is 20 minutes.  This can be changed
- with this option.  Setting the
- .I interval
--to zero turns it off entirely.
-+to zero turns it off entirely.  Depending on other log messages
-+generated these lines may not be written consecutively.
- .TP
- .B "\-n"
- Avoid auto-backgrounding.  This is needed especially if the
-@@ -364,8 +365,10 @@
- 
- To avoid this in further times no messages that were received from a
- remote host are sent out to another (or the same) remote host
--anymore.  If there are scenarios where this doesn't make sense, please
--drop me (Joey) a line.
-+anymore.  If you experience are setup in which this doesn't make
-+sense, please use the
-+.B \-h
-+commandline switch.
- 
- If the remote host is located in the same domain as the host, 
- .B syslogd
-diff -ruN sysklogd-1.4.1/syslog.c sysklogd-1.4.1.new/syslog.c
---- sysklogd-1.4.1/syslog.c	2001-03-11 20:35:51.000000000 +0100
-+++ sysklogd-1.4.1.new/syslog.c	2006-03-14 16:22:13.000000000 +0100
-@@ -47,6 +47,9 @@
-  * Sun Mar 11 20:23:44 CET 2001: Martin Schulze <joey@infodrom.ffis.de>
-  *	Use SOCK_DGRAM for loggin, renables it to work.	
-  *
-+ * Wed Aug 27 17:48:16 CEST 2003: Martin Schulze <joey@Infodrom.org>
-+ *	Improved patch by Michael Pomraning <mjp@securepipe.com> to
-+ *	reconnect klogd to the logger after it went away.
-  */
- 
- #include <sys/types.h>
-@@ -98,6 +101,7 @@
- 	register char *p;
- 	time_t now;
- 	int fd, saved_errno;
-+	int result;
- 	char tbuf[2048], fmt_cpy[1024], *stdp = (char *) 0;
- 
- 	saved_errno = errno;
-@@ -167,7 +171,16 @@
- 	}
- 
- 	/* output the message to the local logger */
--	if (write(LogFile, tbuf, cnt + 1) >= 0 || !(LogStat&LOG_CONS))
-+	result = write(LogFile, tbuf, cnt + 1);
-+
-+	if (result == -1
-+	    && (errno == ECONNRESET || errno == ENOTCONN || errno == ECONNREFUSED)) {
-+		closelog();
-+		openlog(LogTag, LogStat | LOG_NDELAY, LogFacility);
-+		result = write(LogFile, tbuf, cnt + 1);
-+	}
-+
-+	if (result >= 0 || !(LogStat&LOG_CONS))
- 		return;
- 
- 	/*
-diff -ruN sysklogd-1.4.1/syslog.conf.5 sysklogd-1.4.1.new/syslog.conf.5
---- sysklogd-1.4.1/syslog.conf.5	1999-08-21 12:49:14.000000000 +0200
-+++ sysklogd-1.4.1.new/syslog.conf.5	2006-03-14 16:22:13.000000000 +0100
-@@ -64,7 +64,7 @@
- The
- .I facility
- is one of the following keywords:
--.BR auth ", " authpriv ", " cron ", " daemon ", " kern ", " lpr ", "
-+.BR auth ", " authpriv ", " cron ", " daemon ", " ftp ", " kern ", " lpr ", "
- .BR mail ", " mark ", " news ", " security " (same as " auth "), "
- .BR syslog ", " user ", " uucp " and " local0 " through " local7 .
- The keyword 
-@@ -121,12 +121,21 @@
- 
- This 
- .BR syslogd (8)
--has a syntax extension to the original BSD source, that makes its use
-+has a syntax extension to the original BSD source, which makes its use
- more intuitively.  You may precede every priority with an equation sign
--(``='') to specify only this single priority and not any of the
--above.  You may also (both is valid, too) precede the priority with an
--exclamation mark (``!'') to ignore all that priorities, either exact
--this one or this and any higher priority.  If you use both extensions
-+(``='') to specify that
-+.B syslogd
-+should only refer to this single priority and not this priority and
-+all higher priorities.
-+
-+You may also precide the priority with an exclamation mark (``!'') if
-+you want
-+.B syslogd
-+to ignore this priority and all higher priorities.
-+You may even use both, the exclamation mark and the equation sign if
-+you want
-+.B syslogd
-+to ignore only this single priority.  If you use both extensions
- than the exclamation mark must occur before the equation sign, just
- use it intuitively.
- 
-@@ -300,7 +309,7 @@
- .B syslogd
- log all messages that come with either the
- .BR info " or the " notice
--facility into the file
-+priority into the file
- .IR /var/log/messages ,
- except for all messages that use the
- .B mail
-diff -ruN sysklogd-1.4.1/syslogd.c sysklogd-1.4.1.new/syslogd.c
---- sysklogd-1.4.1/syslogd.c	2001-03-11 20:40:10.000000000 +0100
-+++ sysklogd-1.4.1.new/syslogd.c	2006-03-14 16:22:13.000000000 +0100
-@@ -441,6 +441,39 @@
-  *	Don't return a closed fd if `-a' is called with a wrong path.
-  *	Thanks to Bill Nottingham <notting@redhat.com> for providing
-  *	a patch.
-+ * Thu Apr 13 05:08:10 CEST 2001: Jon Burgess <Jon_Burgess@eur.3com.com>
-+ *	Moved the installation of the signal handler up a little bit
-+ *	so it guaranteed to be available when the child is forked,
-+ *	hence, fixing a  race condition.  This used to create problems
-+ *	with UML and fast machines.
-+ *
-+ * Sat Apr 17 18:03:05 CEST 2004: Steve Grubb <linux_4ever@yahoo.com>
-+ *	Correct memory allocation for for commandline arguments in
-+ *	crunch_list().
-+ *
-+ * Thu Apr 29 12:38:39 CEST 2004: Solar Designer <solar@openwall.com>
-+ *	Applied Openwall paranoia patches to improve crunch_list().
-+ *
-+ * Tue May  4 16:47:30 CEST 2004: Solar Designer <solar@openwall.com>
-+ *	Ensure that "len" is not placed in a register, and that the
-+ *	endtty() signal handler is not installed too early which could
-+ *	cause a segmentation fault or worse.
-+ *
-+ * Tue May  4 16:52:01 CEST 2004: Solar Designer <solar@openwall.com>
-+ *	Adjust the size of a variable to prevent a buffer overflow
-+ *	should _PATH_DEV ever contain something different than "/dev/".
-+ *
-+ * Tue Nov  2 20:28:23 CET 2004: Colin Phipps <cph@cph.demon.co.uk>
-+ *	Don't block on the network socket, in case a packet gets lost
-+ *	between select and recv.
-+ *
-+ * Sun Nov  7 12:28:47 CET 2004: Martin Schulze <joey@infodrom.org>
-+ *	Discard any timestamp information found in received syslog
-+ *	messages.  This will affect local messages sent from a
-+ *	different timezone.
-+ *
-+ * Sun Nov  7 13:47:00 CET 2004: Martin Schulze <joey@infodrom.org>
-+ *	Remove trailing newline when forwarding messages.
-  */
- 
- 
-@@ -890,11 +923,11 @@
- 		dprintf("Checking pidfile.\n");
- 		if (!check_pid(PidFile))
- 		{
-+			signal (SIGTERM, doexit);
- 			if (fork()) {
- 				/*
- 				 * Parent process
- 				 */
--				signal (SIGTERM, doexit);
- 				sleep(300);
- 				/*
- 				 * Not reached unless something major went wrong.  5
-@@ -992,6 +1025,7 @@
- 	(void) signal(SIGCHLD, reapchild);
- 	(void) signal(SIGALRM, domark);
- 	(void) signal(SIGUSR1, Debug ? debug_switch : SIG_IGN);
-+	(void) signal(SIGXFSZ, SIG_IGN);
- 	(void) alarm(TIMERINTVL);
- 
- 	/* Create a partial message table for all file descriptors. */
-@@ -1141,13 +1175,13 @@
- 				 */
- 				printchopped(from, line, \
-  					     i + 2,  finet);
--			} else if (i < 0 && errno != EINTR) {
-+			} else if (i < 0 && errno != EINTR && errno != EAGAIN) {
- 				dprintf("INET socket error: %d = %s.\n", \
- 					errno, strerror(errno));
- 				logerror("recvfrom inet");
- 				/* should be harmless now that we set
- 				 * BSDCOMPAT on the socket */
--				sleep(10);
-+				sleep(1);
- 			}
- 		}
- #endif
-@@ -1216,6 +1250,7 @@
- {
- 	int fd, on = 1;
- 	struct sockaddr_in sin;
-+	int sockflags;
- 
- 	fd = socket(AF_INET, SOCK_DGRAM, 0);
- 	if (fd < 0) {
-@@ -1241,6 +1276,24 @@
- 		close(fd);
- 		return -1;
- 	}
-+	/* We must not block on the network socket, in case a packet
-+	 * gets lost between select and recv, otherise the process
-+	 * will stall until the timeout, and other processes trying to
-+	 * log will also stall.
-+	 */
-+	if ((sockflags = fcntl(fd, F_GETFL)) != -1) {
-+		sockflags |= O_NONBLOCK;
-+		/*
-+		 * SETFL could fail too, so get it caught by the subsequent
-+		 * error check.
-+		 */
-+		sockflags = fcntl(fd, F_SETFL, sockflags);
-+	}
-+	if (sockflags == -1) {
-+		logerror("fcntl(O_NONBLOCK), suspending inet");
-+		close(fd);
-+		return -1;
-+	}
- 	if (bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
- 		logerror("bind, suspending inet");
- 		close(fd);
-@@ -1254,30 +1307,26 @@
- crunch_list(list)
- 	char *list;
- {
--	int count, i;
-+	int i, m, n;
- 	char *p, *q;
- 	char **result = NULL;
- 
- 	p = list;
- 	
- 	/* strip off trailing delimiters */
--	while (p[strlen(p)-1] == LIST_DELIMITER) {
--		count--;
-+	while (*p && p[strlen(p)-1] == LIST_DELIMITER)
- 		p[strlen(p)-1] = '\0';
--	}
- 	/* cut off leading delimiters */
--	while (p[0] == LIST_DELIMITER) {
--		count--;
-+	while (p[0] == LIST_DELIMITER)
- 		p++; 
--	}
- 	
--	/* count delimiters to calculate elements */
--	for (count=i=0; p[i]; i++)
--		if (p[i] == LIST_DELIMITER) count++;
-+	/* count delimiters to calculate the number of elements */
-+	for (n = i = 0; p[i]; i++)
-+		if (p[i] == LIST_DELIMITER) n++;
- 	
--	if ((result = (char **)malloc(sizeof(char *) * count+2)) == NULL) {
-+	if ((result = (char **)malloc(sizeof(char *) * (n + 2))) == NULL) {
- 		printf ("Sorry, can't get enough memory, exiting.\n");
--		exit(0);
-+		exit(1);
- 	}
- 	
- 	/*
-@@ -1285,30 +1334,28 @@
- 	 * characters are different from any delimiters,
- 	 * so we don't have to care about this.
- 	 */
--	count = 0;
--	while ((q=strchr(p, LIST_DELIMITER))) {
--		result[count] = (char *) malloc((q - p + 1) * sizeof(char));
--		if (result[count] == NULL) {
-+	m = 0;
-+	while ((q = strchr(p, LIST_DELIMITER)) && m < n) {
-+		result[m] = (char *) malloc((q - p + 1) * sizeof(char));
-+		if (result[m] == NULL) {
- 			printf ("Sorry, can't get enough memory, exiting.\n");
--			exit(0);
-+			exit(1);
- 		}
--		strncpy(result[count], p, q - p);
--		result[count][q - p] = '\0';
-+		memcpy(result[m], p, q - p);
-+		result[m][q - p] = '\0';
- 		p = q; p++;
--		count++;
-+		m++;
- 	}
--	if ((result[count] = \
--	     (char *)malloc(sizeof(char) * strlen(p) + 1)) == NULL) {
-+	if ((result[m] = strdup(p)) == NULL) {
- 		printf ("Sorry, can't get enough memory, exiting.\n");
--		exit(0);
-+		exit(1);
- 	}
--	strcpy(result[count],p);
--	result[++count] = NULL;
-+	result[++m] = NULL;
- 
- #if 0
--	count=0;
--	while (result[count])
--		dprintf ("#%d: %s\n", count, StripDomains[count++]);
-+	m = 0;
-+	while (result[m])
-+		dprintf ("#%d: %s\n", m, result[m++]);
- #endif
- 	return result;
- }
-@@ -1539,30 +1586,48 @@
- 	int fac, prilev, lognum;
- 	int msglen;
- 	char *timestamp;
-+#ifdef __gnu_linux__
-+	sigset_t mask;
-+#else
-+#ifndef SYSV
-+	sigset_t omask;
-+#endif
-+#endif
- 
- 	dprintf("logmsg: %s, flags %x, from %s, msg %s\n", textpri(pri), flags, from, msg);
- 
-+#ifdef __gnu_linux__
-+	sigemptyset(&mask);
-+	sigaddset(&mask, SIGHUP);
-+	sigaddset(&mask, SIGALRM);
-+	sigprocmask(SIG_BLOCK, &mask, NULL);
-+#else
- #ifndef SYSV
- 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
- #endif
-+#endif
- 
- 	/*
- 	 * Check to see if msg looks non-standard.
-+	 *
-+	 * A message looks like
-+	 * Nov 17 11:42:33 CRON[
-+	 * 01234567890123456
-+	 *    ^  ^  ^  ^  ^
-+	 *
-+	 * Remote messages are not accompanied by a timestamp.
-+	 * Local messages are accompanied by a timestamp (program's timezone)
- 	 */
- 	msglen = strlen(msg);
--	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
--	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
--		flags |= ADDDATE;
--
--	(void) time(&now);
--	if (flags & ADDDATE)
--		timestamp = ctime(&now) + 4;
--	else {
--		timestamp = msg;
-+	if (!(msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
-+	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')) {
- 		msg += 16;
- 		msglen -= 16;
- 	}
- 
-+	(void) time(&now);
-+	timestamp = ctime(&now) + 4;
-+
- 	/* extract facility and priority level */
- 	if (flags & MARK)
- 		fac = LOG_NFACILITIES;
-@@ -1581,9 +1646,13 @@
- 			(void) close(f->f_file);
- 			f->f_file = -1;
- 		}
-+#ifdef __gnu_linux__
-+		sigprocmask(SIG_UNBLOCK, &mask, NULL);
-+#else
- #ifndef SYSV
- 		(void) sigsetmask(omask);
- #endif
-+#endif
- 		return;
- 	}
- #ifdef SYSV
-@@ -1646,9 +1715,13 @@
- 			}
- 		}
- 	}
-+#ifdef __gnu_linux__
-+	sigprocmask(SIG_UNBLOCK, &mask, NULL);
-+#else
- #ifndef SYSV
- 	(void) sigsetmask(omask);
- #endif
-+#endif
- }
- #if FALSE
- } /* balance parentheses for emacs */
-@@ -1771,7 +1844,7 @@
- 			dprintf("Not sending message to remote.\n");
- 		else {
- 			f->f_time = now;
--			(void) snprintf(line, sizeof(line), "<%d>%s\n", f->f_prevpri, \
-+			(void) snprintf(line, sizeof(line), "<%d>%s", f->f_prevpri, \
- 				(char *) iov[4].iov_base);
- 			l = strlen(line);
- 			if (l > MAXLINE)
-@@ -1815,7 +1888,7 @@
- 			v->iov_len = 1;
- 		}
- 	again:
--		/* f->f_file == -1 is an indicator that the we couldn't
-+		/* f->f_file == -1 is an indicator that we couldn't
- 		   open the file at startup. */
- 		if (f->f_file == -1)
- 			break;
-@@ -1852,7 +1925,7 @@
- 				errno = e;
- 				logerror(f->f_un.f_fname);
- 			}
--		} else if (f->f_flags & SYNC_FILE)
-+		} else if (f->f_type == F_FILE && (f->f_flags & SYNC_FILE))
- 			(void) fsync(f->f_file);
- 		break;
- 
-@@ -1891,7 +1964,7 @@
- 	register struct filed *f;
- 	struct iovec *iov;
- {
--	char p[6 + UNAMESZ];
-+	char p[sizeof (_PATH_DEV) + UNAMESZ];
- 	register int i;
- 	int ttyf, len;
- 	static int reenter = 0;
-@@ -1899,6 +1972,8 @@
- 	struct utmp *uptr;
- 	char greetings[200];
- 
-+	(void) &len;
-+
- 	if (reenter++)
- 		return;
- 
-@@ -1913,7 +1988,6 @@
- 	if (fork() == 0) {
- 		(void) signal(SIGTERM, SIG_DFL);
- 		(void) alarm(0);
--		(void) signal(SIGALRM, endtty);
- #ifndef SYSV
- 		(void) signal(SIGTTOU, SIG_IGN);
- 		(void) sigsetmask(0);
-@@ -1929,7 +2003,7 @@
- 			/* is this slot used? */
- 			if (ut.ut_name[0] == '\0')
- 				continue;
--			if (ut.ut_type == LOGIN_PROCESS)
-+			if (ut.ut_type != USER_PROCESS)
- 			        continue;
- 			if (!(strcmp (ut.ut_name,"LOGIN"))) /* paranoia */
- 			        continue;
-@@ -1959,6 +2033,7 @@
- 				iov[1].iov_len = 0;
- 			}
- 			if (setjmp(ttybuf) == 0) {
-+				(void) signal(SIGALRM, endtty);
- 				(void) alarm(15);
- 				/* open the terminal */
- 				ttyf = open(p, O_WRONLY|O_NOCTTY);
diff --git a/pkgs/os-specific/linux/tcp-wrapper/default.nix b/pkgs/os-specific/linux/tcp-wrapper/default.nix
new file mode 100644
index 00000000000..9c952bcabf8
--- /dev/null
+++ b/pkgs/os-specific/linux/tcp-wrapper/default.nix
@@ -0,0 +1,26 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "tcp-wrappers-7.6";
+
+  src = fetchurl {
+    url = http://ftp.debian.org/debian/pool/main/t/tcp-wrappers/tcp-wrappers_7.6.dbs.orig.tar.gz;
+    sha256 = "0k68ziinx6biwar5lcb9jvv0rp6b3vmj6861n75bvrz4w1piwkdp";
+  };
+  
+  # we need to set REAL_DAEMON_DIR somehow. I'm getting compilation errors
+  # I've managed to compile tcpd manually using 
+  # make CFLAGS='-DSYS_ERRLIST_DEFINED=1  -Dvsyslog=1' tcpd
+  # see Makefile target all for details
+
+  postUnpack="cd upstream/tarballs; tar xfz *; cd tcp_wrappers_7.6;
+    sed -i -e 's=#REAL_DAEMON_DIR=/usr/sbin=REAL_DAEMON_DIR=/usr/sbin=' Makefile
+          ";
+
+  buildPhase="
+    make CFLAGS='-DSYS_ERRLIST_DEFINED=1  -Dvsyslog=1' tcpd
+  "
+
+  buildInputs = [kernelHeaders gnused];
+
+  # meta = ...
+}
diff --git a/pkgs/os-specific/linux/udev/default.nix b/pkgs/os-specific/linux/udev/default.nix
index 14393f59958..a2de2e08ce9 100644
--- a/pkgs/os-specific/linux/udev/default.nix
+++ b/pkgs/os-specific/linux/udev/default.nix
@@ -1,11 +1,25 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "udev-112";
+  name = "udev-118";
+
   src = fetchurl {
-    url = mirror://kernel/linux/utils/kernel/hotplug/udev-112.tar.bz2;
-    sha256 = "0vhqnli4va3yzvr90rcpbgs42sphpk9prdis9x2qmlmdynzangw2";
+    url = mirror://kernel/linux/utils/kernel/hotplug/udev-118.tar.bz2;
+    sha256 = "1i488wqm7i6nz6gidbkxkb47hr427ika48i8imwrvvnpg1kzhska";
+  };
+
+  # "DESTDIR=/" is a hack to prevent "make install" from trying to
+  # mess with /dev.
+  preBuild = ''
+    makeFlagsArray=(etcdir=$out/etc sbindir=$out/sbin usrbindir=$out/bin usrsbindir=$out/sbin mandir=$out/share/man INSTALL='install -c' DESTDIR=/)
+  '';
+
+  preInstall = ''
+    installFlagsArray=(udevdir=$TMPDIR/dummy)
+  '';
+
+  meta = {
+    homepage = http://www.kernel.org/pub/linux/utils/kernel/hotplug/udev.html;
+    description = "Udev manages the /dev filesystem";
   };
-  preBuild = "makeFlagsArray=(etcdir=$out/etc sbindir=$out/sbin usrbindir=$out/bin usrsbindir=$out/sbin mandir=$out/share/man INSTALL='install -c')";
-  preInstall = "installFlagsArray=(udevdir=dummy)";
 }
diff --git a/pkgs/os-specific/linux/upstart/jobcontrol.nix b/pkgs/os-specific/linux/upstart/jobcontrol.nix
new file mode 100644
index 00000000000..5be0276ffd5
--- /dev/null
+++ b/pkgs/os-specific/linux/upstart/jobcontrol.nix
@@ -0,0 +1,15 @@
+args: with args;
+stdenv.mkDerivation {
+	name = "upstart-jobcontrol";
+	buildCommand = "
+		mkdir -p \$out/bin
+		echo '
+			file=/etc/event.d/\$1
+			shift
+			controlscript=\$(egrep exec\\|respawn \$file | tail | sed -e s/^\\\\s\\\\+//g  | sed -e s/\\\\s\\\\+/\\ /g | cut -f 2 -d \\  )
+			echo Running \$controlscript \"\$@\"
+			\$controlscript \"\$@\"
+		' >\$out/bin/jobcontrol
+		chmod a+x \$out/bin/jobcontrol
+	";
+}
diff --git a/pkgs/os-specific/linux/usbutils/default.nix b/pkgs/os-specific/linux/usbutils/default.nix
index b7d2c349e25..1f123fadc87 100644
--- a/pkgs/os-specific/linux/usbutils/default.nix
+++ b/pkgs/os-specific/linux/usbutils/default.nix
@@ -3,17 +3,17 @@
 let
 
   usbids = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/usb.ids.20061212.bz2;
-    sha256 = "112l4fzjn5p3y6fv3x10vbrd36n2v5n04s7pjdlkb2yqv4crp84m";
+    url = http://nix.cs.uu.nl/dist/tarballs/usb.ids.20080115.bz2;
+    sha256 = "0xymp8fpp9pnkj2i4ry8zpsvy18zw14sx03pnz316lpgwc6dx12n";
   };
 
 in
 
 stdenv.mkDerivation {
-  name = "usbutils-0.72";
+  name = "usbutils-0.73";
   src = fetchurl {
-    url = mirror://sourceforge/linux-usb/usbutils-0.72.tar.gz;
-    sha256 = "08s4g4sz7p3a1afvphxd7h5bbfywvp0j611y85wbhwr14i9m6f00";
+    url = mirror://sourceforge/linux-usb/usbutils-0.73.tar.gz;
+    sha256 = "1x27mc2apyipf8fa2ac49rfnkm7f5dwv784b1ncgc5yjiz4prp1f";
   };
   buildInputs = [libusb];
   preBuild = "bunzip2 < ${usbids} > usb.ids";
diff --git a/pkgs/os-specific/linux/util-linux/default.nix b/pkgs/os-specific/linux/util-linux/default.nix
index 7f54a0c32ee..0c7ebef7eb3 100644
--- a/pkgs/os-specific/linux/util-linux/default.nix
+++ b/pkgs/os-specific/linux/util-linux/default.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl}:
+args: with args;
 
 stdenv.mkDerivation {
   name = "util-linux-2.13-pre7";
@@ -10,6 +10,10 @@ stdenv.mkDerivation {
   
   configureFlags = "--disable-use-tty-group";
 
+  buildInputs = [] 
+  	++ (if args ? ncurses then [args.ncurses] else [])
+  ;
+
   preBuild = "
     makeFlagsArray=(usrbinexecdir=$out/bin usrsbinexecdir=$out/sbin datadir=$out/share exampledir=$out/share/getopt)
   ";
diff --git a/pkgs/os-specific/linux/wis-go7007/default.nix b/pkgs/os-specific/linux/wis-go7007/default.nix
new file mode 100644
index 00000000000..3e35c83488a
--- /dev/null
+++ b/pkgs/os-specific/linux/wis-go7007/default.nix
@@ -0,0 +1,59 @@
+{stdenv, fetchurl, kernel, ncurses, fxload}:
+
+stdenv.mkDerivation {
+  name = "wis-go7007-0.9.8";
+
+  src = fetchurl {
+    url = http://gentoo.osuosl.org/distfiles/wis-go7007-linux-0.9.8.tar.bz2;
+    sha256 = "06lvlz42c5msvwc081p8vjcbv8qq1j1g1myxhh27xi8zi06n1mzg";
+  };
+
+  patches = map fetchurl [
+    { url = "http://sources.gentoo.org/viewcvs.py/*checkout*/gentoo-x86/media-tv/wis-go7007/files/wis-go7007-0.9.8-kernel-2.6.17.diff?rev=1.1";
+      sha256 = "0cizbg82fdl5byhvpkdx64qa02xcahdyddi2l2jn95sxab28a5yg";
+    }
+    { url = "http://sources.gentoo.org/viewcvs.py/*checkout*/gentoo-x86/media-tv/wis-go7007/files/wis-go7007-0.9.8-fix-udev.diff?rev=1.2";
+      sha256 = "1985lcb7gh5zsf3lm0b43zd6q0cb9q4z376n9q060bh99yw6m0w1";
+    }
+    { url = "http://sources.gentoo.org/viewcvs.py/*checkout*/gentoo-x86/media-tv/wis-go7007/files/snd.patch?rev=1.1";
+      sha256 = "0a6dz1l16pz1fk77s3awxh635cacbivfcfnd1carbx5jp2gq3jna";
+    }
+  ];
+
+  buildInputs = [ncurses];
+
+  preBuild = ''
+    # Urgh, we need the complete kernel sources for some header
+    # files.  So unpack the original kernel source tarball and copy
+    # the configured include directory etc. on top of it.
+    kernelVersion=$(cd ${kernel}/lib/modules && ls)
+    kernelBuild=$(echo ${kernel}/lib/modules/$kernelVersion/source)
+    tar xvfj ${kernel.src}
+    kernelSource=$(echo $(pwd)/linux-*)
+    cp -prd $kernelBuild/* $kernelSource
+
+    #includeDir=$out/lib/modules/$kernelVersion/source/include/linux
+    includeDir=$TMPDIR/scratch
+    substituteInPlace Makefile \
+        --replace '$(DESTDIR)$(KSRC)/include/linux' $includeDir \
+        --replace '$(DESTDIR)$(FIRMWARE_DIR)' '$(FIRMWARE_DIR)'
+    ensureDir $includeDir
+    ensureDir $out/etc/hotplug/usb
+    ensureDir $out/etc/udev/rules.d
+ 
+    makeFlagsArray=(KERNELSRC=$kernelSource \
+        FIRMWARE_DIR=$out/firmware FXLOAD=${fxload}/sbin/fxload \
+        DESTDIR=$out SKIP_DEPMOD=1 \
+        USE_UDEV=y)
+  ''; # */
+
+  postInstall = ''
+    ensureDir $out/bin
+    cp apps/gorecord apps/modet $out/bin/
+  '';
+
+  meta = {
+    description = "Kernel module for the Micronas GO7007, used in a number of USB TV devices";
+    homepage = http://oss.wischip.com/;
+  };
+}
diff --git a/pkgs/os-specific/linux/wpa_supplicant/default.nix b/pkgs/os-specific/linux/wpa_supplicant/default.nix
index bf6795f4b1e..f58a360ac8d 100644
--- a/pkgs/os-specific/linux/wpa_supplicant/default.nix
+++ b/pkgs/os-specific/linux/wpa_supplicant/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl, openssl}:
 
 stdenv.mkDerivation {
-  name = "wpa_supplicant-0.5.7";
+  name = "wpa_supplicant-0.5.9";
 
   src = fetchurl {
-    url = http://hostap.epitest.fi/releases/wpa_supplicant-0.5.7.tar.gz;
-    sha256 = "0mvb2fpvn7qdjinpn86hvmhfwg2ax1822hdkfrw25wx5dglqns6g";
+    url = http://hostap.epitest.fi/releases/wpa_supplicant-0.5.9.tar.gz;
+    sha256 = "1dylaiikp2jb13jbxdrl1h9b9p2lkjmzx06hpmkcpyq5c5g7p0xy";
   };
 
   preBuild = "
diff --git a/pkgs/servers/fingerd/bsd-fingerd/default.nix b/pkgs/servers/fingerd/bsd-fingerd/default.nix
new file mode 100644
index 00000000000..eacf2371d36
--- /dev/null
+++ b/pkgs/servers/fingerd/bsd-fingerd/default.nix
@@ -0,0 +1,17 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "bsd-fingerd-0.17";
+
+	src = fetchurl {
+		url = "ftp://ftp.metalab.unc.edu/pub/linux/system/network/finger/bsd-finger-0.17.tar.gz";
+		sha256 = "1yhkiv0in588il7f84k2xiy78g9lv12ll0y7047gazhiimk5v244";
+	};
+
+	NIX_CFLAGS_COMPILE="-D_GNU_SOURCE";
+
+	patches = [./ubuntu-0.17-9.patch];
+
+	preBuild = "cd fingerd";
+
+	preInstall = '' ensureDir $out/man/man8 $out/sbin '';
+}
diff --git a/pkgs/servers/fingerd/bsd-fingerd/ubuntu-0.17-9.patch b/pkgs/servers/fingerd/bsd-fingerd/ubuntu-0.17-9.patch
new file mode 100644
index 00000000000..80968d587ba
--- /dev/null
+++ b/pkgs/servers/fingerd/bsd-fingerd/ubuntu-0.17-9.patch
@@ -0,0 +1,67 @@
+--- bsd-finger-0.17.orig/fingerd/fingerd.8
++++ bsd-finger-0.17/fingerd/fingerd.8
+@@ -36,10 +36,10 @@
+ .Dt FINGERD 8
+ .Os "Linux NetKit (0.17)"
+ .Sh NAME
+-.Nm fingerd
++.Nm in.fingerd
+ .Nd remote user information server
+ .Sh SYNOPSIS
+-.Nm fingerd
++.Nm in.fingerd
+ .Op Fl wulf
+ .Op Fl pL Ar path
+ .Op Fl t Ar timeout
+@@ -61,7 +61,7 @@
+ banner
+ which also shows some informations (e.g. uptime, operating system name and
+ release) about the system the
+-.Nm fingerd
++.Nm in.fingerd
+ is running on. Some sites may consider this a security risk as it
+ gives out information that may be useful to crackers. 
+ .Pp
+@@ -85,7 +85,7 @@
+ .Pp
+ The 
+ .Fl p
+-option allows specification of an alternate location for fingerd to find
++option allows specification of an alternate location for in.fingerd to find
+ the 
+ .Dq finger
+ program. The
+@@ -97,7 +97,7 @@
+ option specifies the time to wait for a request before closing the
+ connection.  A value of 0 waits forever.  The default is 60 seconds.
+ .Pp
+-Options to fingerd should be specified in 
++Options to in.fingerd should be specified in 
+ .Pa /etc/inetd.conf .
+ .Pp
+ The finger protocol consists mostly of specifying command arguments.
+@@ -105,12 +105,12 @@
+ .Xr inetd 8
+ .Dq super-server
+ runs
+-.Nm fingerd
++.Nm in.fingerd
+ for 
+ .Tn TCP
+ requests received on port 79.
+ Once connected 
+-.Nm fingerd
++.Nm in.fingerd
+ reads a single command line
+ terminated by a
+ .Aq Tn CRLF
+--- bsd-finger-0.17.orig/fingerd/fingerd.c
++++ bsd-finger-0.17/fingerd/fingerd.c
+@@ -55,6 +55,7 @@
+ #include <netinet/in.h>
+ #include <sys/utsname.h>
+ #include <sys/wait.h>
++#include <sys/socket.h>
+ 
+ #include "pathnames.h"
+ #include "../version.h"
diff --git a/pkgs/servers/ftp/vsftpd/default.nix b/pkgs/servers/ftp/vsftpd/default.nix
index 861845ab24f..7961448428d 100644
--- a/pkgs/servers/ftp/vsftpd/default.nix
+++ b/pkgs/servers/ftp/vsftpd/default.nix
@@ -1,16 +1,20 @@
-{stdenv, fetchurl, openssl}:
+args: with args;
 
-stdenv.mkDerivation {
-  name = "vsftpd-2.0.3";
+stdenv.mkDerivation rec {
+  name = "vsftpd-2.0.5";
   src = fetchurl {
-    url = ftp://vsftpd.beasts.org/users/cevans/vsftpd-2.0.3.tar.gz;
-    md5 = "74936cbd8e8251deb1cd99c5fb18b6f8";
+    url = "ftp://vsftpd.beasts.org/users/cevans/${name}.tar.gz";
+    sha256 = "0nzsxknnaqnfk853yjsmi31sl02jf5ydix9wxbldv4i7vzqfnqjl";
   };
   
-  NIX_LDFLAGS = [ "-lcrypt" "-lssl" "-lcrypto" ];
+  NIX_LDFLAGS = "-lcrypt -lssl -lcrypto -lpam -lcap";
 
-  builder = ./builder.sh ;
+  preInstall = ''
+  ensureDir $out/{,s}bin
+  ensureDir $out/man/man{5,8}
+  '';
 
   patches = [ ./fix.patch ] ;
-  buildInputs = [ openssl ];
+  preConfigure = ''sed -i "/VSF_BUILD_SSL/s/^#undef/#define/" builddefs.h'';
+  buildInputs = [ openssl libcap pam ];
 }
diff --git a/pkgs/servers/http/apache-httpd/builder.sh b/pkgs/servers/http/apache-httpd/builder.sh
deleted file mode 100644
index 3a5ccd846ee..00000000000
--- a/pkgs/servers/http/apache-httpd/builder.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-buildInputs="$openssl $db4 $expat $perl"
-source $stdenv/setup
-
-configureFlags="\
- --with-expat=$expat \
- --with-z=$zlib \
- --enable-mods-shared=all \
- --enable-authn-alias \
- --without-gdbm \
- --enable-threads \
- --with-devrandom=/dev/urandom"
-
-if test $db4Support; then
-    configureFlags="--with-berkeley-db=$db4 $configureFlags"
-fi
-
-if test $sslSupport; then
-    configureFlags="--enable-ssl --with-ssl=$openssl $configureFlags"
-fi
-
-
-postInstall() {
-    echo "removing manual"
-    rm -rf $out/manual
-}
-postInstall=postInstall
-
-
-genericBuild
diff --git a/pkgs/servers/http/apache-httpd/default.nix b/pkgs/servers/http/apache-httpd/default.nix
index 2f33b4d497f..4e2af7ff900 100644
--- a/pkgs/servers/http/apache-httpd/default.nix
+++ b/pkgs/servers/http/apache-httpd/default.nix
@@ -1,5 +1,5 @@
 { stdenv, fetchurl, openssl, db4, expat, perl, zlib
-, sslSupport, db4Support
+, sslSupport, db4Support, proxySupport ? true
 }:
 
 assert sslSupport -> openssl != null;
@@ -7,21 +7,50 @@ assert db4Support -> db4 != null;
 assert expat != null && perl != null;
 
 stdenv.mkDerivation {
-  name = "apache-httpd-2.2.6";
+  name = "apache-httpd-2.2.8x";
 
-  builder = ./builder.sh;
   src = fetchurl {
-    url = http://archive.apache.org/dist/httpd/httpd-2.2.6.tar.bz2;
-    md5 = "203bea91715064f0c787f6499d33a377";
+    url = http://archive.apache.org/dist/httpd/httpd-2.2.8.tar.bz2;
+    md5 = "76d2598a4797163d07cd50e5304aa7cd";
   };
 
-  inherit sslSupport db4Support;
+  #inherit sslSupport db4Support;
 
-  inherit perl expat zlib;
-  openssl = if sslSupport then openssl else null;
-  db4 = if db4Support then db4 else null;
+  buildInputs = [expat perl] ++
+    stdenv.lib.optional sslSupport openssl ++
+    stdenv.lib.optional db4Support db4;
 
+  configureFlags = ''
+    --with-expat=${expat}
+    --with-z=${zlib}
+    --enable-mods-shared=all
+    --enable-authn-alias
+    ${if proxySupport then "--enable-proxy" else ""}
+    --without-gdbm
+    --enable-threads
+    --with-devrandom=/dev/urandom
+    ${if sslSupport then "--enable-ssl --with-ssl=${openssl}" else ""}
+    ${if db4Support then "--with-berkeley-db=${db4}" else ""}
+  '';
+
+  postInstall = ''
+    echo "removing manual"
+    rm -rf $out/manual
+  '';
+
+  # For now, disable detection of epoll to ensure that Apache still
+  # runs on Linux 2.4 kernels.  Once we've dropped support for 2.4 in
+  # Nixpkgs, this can go.  In general, it's a problem that APR
+  # detects characteristics of the build system's kernel to decide
+  # what to use at runtime, since it's impure.
+  apr_cv_epoll = "no";
+
+  passthru = {
+    inherit expat sslSupport db4Support proxySupport;
+  };
+  
   meta = {
     description = "Apache HTTPD, the world's most popular web server";
+    homepage = http://httpd.apache.org/;
   };
 }
diff --git a/pkgs/servers/http/apache-modules/mod_python/default.nix b/pkgs/servers/http/apache-modules/mod_python/default.nix
index 16d247fe8dc..4c83070e9ca 100644
--- a/pkgs/servers/http/apache-modules/mod_python/default.nix
+++ b/pkgs/servers/http/apache-modules/mod_python/default.nix
@@ -1,13 +1,13 @@
 {stdenv, fetchurl, apacheHttpd, python}:
 
 stdenv.mkDerivation {
-  name = "mod_python-3.2.10";
+  name = "mod_python-3.3.1";
 
   builder = ./builder.sh;
 
   src = fetchurl {
-    url = http://apache.surfnet.nl/httpd/modpython/mod_python-3.2.10.tgz;
-    md5 = "cc6439f546a6e70cfff7ca51b8c62541";
+    url = http://archive.eu.apache.org/dist/httpd/modpython/mod_python-3.3.1.tgz;
+    sha256 = "0sss2xi6l1a2z8y6ji0cp8vgyvnhq8zrg0ilkvpj1mygbzyk28xd";
   };
 
   patches = [./install.patch];
diff --git a/pkgs/servers/http/apache-modules/tomcat-connectors/builder.sh b/pkgs/servers/http/apache-modules/tomcat-connectors/builder.sh
new file mode 100644
index 00000000000..70b609e6465
--- /dev/null
+++ b/pkgs/servers/http/apache-modules/tomcat-connectors/builder.sh
@@ -0,0 +1,8 @@
+source $stdenv/setup
+
+tar xfvz $src
+cd tomcat-connectors-*-src/native
+./configure --with-apxs=$apacheHttpd/bin/apxs --with-java-home=$jdk
+make
+ensureDir $out/modules
+cp apache-2.0/mod_jk.so $out/modules
diff --git a/pkgs/servers/http/apache-modules/tomcat-connectors/default.nix b/pkgs/servers/http/apache-modules/tomcat-connectors/default.nix
new file mode 100644
index 00000000000..5c33c444c0d
--- /dev/null
+++ b/pkgs/servers/http/apache-modules/tomcat-connectors/default.nix
@@ -0,0 +1,14 @@
+{stdenv, fetchurl, apacheHttpd, jdk}:
+
+stdenv.mkDerivation {
+  name = "tomcat-connectors-1.2.26";
+  builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://apache.proserve.nl/tomcat/tomcat-connectors/jk/source/jk-1.2.26/tomcat-connectors-1.2.26-src.tar.gz;
+    md5 = "feaec245136bc4d99a9dde95a00ea93c";
+  };
+
+  inherit apacheHttpd;
+  buildInputs = [apacheHttpd jdk];
+}
diff --git a/pkgs/servers/http/jboss/builder.sh b/pkgs/servers/http/jboss/builder.sh
new file mode 100644
index 00000000000..33562000919
--- /dev/null
+++ b/pkgs/servers/http/jboss/builder.sh
@@ -0,0 +1,15 @@
+buildInputs="$jdk5"
+source $stdenv/setup
+
+export JDK_HOME=$jdk5
+export JAVA_HOME=$jdk5
+
+tar xfvz $src
+cd jboss-*
+cd build
+sh build.sh
+ensureDir $out
+cp -av output/jboss-*/* $out
+
+# Insert JAVA_HOME variable to make sure the latest JRE is used and not version 5
+sed -i -e "/GREP/aJAVA_HOME=$jdk" $out/bin/run.sh
diff --git a/pkgs/servers/http/jboss/default.nix b/pkgs/servers/http/jboss/default.nix
new file mode 100644
index 00000000000..279e4bfae71
--- /dev/null
+++ b/pkgs/servers/http/jboss/default.nix
@@ -0,0 +1,20 @@
+{ stdenv, fetchurl, jdk5, jdk }:
+
+stdenv.mkDerivation {
+  name = "jboss-4.2.2.GA";
+
+  builder = ./builder.sh;
+  src = 
+    fetchurl {
+      url = http://garr.dl.sourceforge.net/sourceforge/jboss/jboss-4.2.2.GA-src.tar.gz;
+      md5 = "2a626cdccabe712628555676d67ad44a";
+    };
+
+  inherit jdk5 jdk;
+
+  meta = {
+    homepage = "http://www.jboss.org/";
+    description = "JBoss, Open Source J2EE application server";
+    license = "GPL/LGPL";
+  };
+}
diff --git a/pkgs/servers/http/jboss/jdbc/mysql/builder.sh b/pkgs/servers/http/jboss/jdbc/mysql/builder.sh
new file mode 100644
index 00000000000..06d60fc5e12
--- /dev/null
+++ b/pkgs/servers/http/jboss/jdbc/mysql/builder.sh
@@ -0,0 +1,5 @@
+buildInputs="$mysql_jdbc"
+source $stdenv/setup
+
+ensureDir $out/server/default/lib
+ln -s $mysql_jdbc/share/java/mysql-connector-java.jar $out/server/default/lib/mysql-connector-java.jar
diff --git a/pkgs/servers/http/jboss/jdbc/mysql/default.nix b/pkgs/servers/http/jboss/jdbc/mysql/default.nix
new file mode 100644
index 00000000000..8544ce050af
--- /dev/null
+++ b/pkgs/servers/http/jboss/jdbc/mysql/default.nix
@@ -0,0 +1,9 @@
+{ stdenv, jboss, mysql_jdbc }:
+
+stdenv.mkDerivation {
+  name = "jboss-mysql-jdbc";
+
+  builder = ./builder.sh;
+
+  inherit mysql_jdbc;
+}
diff --git a/pkgs/servers/http/tomcat/6.0.nix b/pkgs/servers/http/tomcat/6.0.nix
new file mode 100644
index 00000000000..32a3dedde47
--- /dev/null
+++ b/pkgs/servers/http/tomcat/6.0.nix
@@ -0,0 +1,15 @@
+{stdenv, fetchurl, jdk}:
+
+stdenv.mkDerivation {
+
+  name = "apache-tomcat-6.0.14";
+
+  builder = ./builder-6.0.sh;
+
+  src = fetchurl {
+    url = http://apache.mirrors.webazilla.nl/tomcat/tomcat-6/v6.0.14/bin/apache-tomcat-6.0.14.tar.gz;
+    md5 = "3b18ff250d8172737c4f67f11631f68a";
+  };
+
+  inherit jdk;
+}
diff --git a/pkgs/servers/http/tomcat/axis2/builder.sh b/pkgs/servers/http/tomcat/axis2/builder.sh
new file mode 100644
index 00000000000..fa58a9e5292
--- /dev/null
+++ b/pkgs/servers/http/tomcat/axis2/builder.sh
@@ -0,0 +1,15 @@
+buildInputs="$unzip $apacheAnt $jdk"
+source $stdenv/setup
+
+unzip $src
+cd axis2-*
+ensureDir $out/share/java/axis2
+cp lib/* $out/share/java/axis2
+cd webapp
+ant
+ensureDir $out/webapps
+cp ../dist/axis2.war $out/webapps
+cd $out/webapps
+mkdir axis2
+cd axis2
+unzip ../axis2.war
diff --git a/pkgs/servers/http/tomcat/axis2/default.nix b/pkgs/servers/http/tomcat/axis2/default.nix
new file mode 100644
index 00000000000..aeb103c0e7d
--- /dev/null
+++ b/pkgs/servers/http/tomcat/axis2/default.nix
@@ -0,0 +1,15 @@
+{stdenv, fetchurl, apacheAnt, jdk, unzip}:
+
+stdenv.mkDerivation {
+
+  name = "axis2-1.3";
+
+  builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://apache.hippo.nl/ws/axis2/1_3/axis2-1.3-bin.zip;
+    md5 = "ab2bc77452288ebf80d861270734a83e";
+  };
+
+  inherit apacheAnt jdk unzip;
+}
diff --git a/pkgs/servers/http/tomcat/builder-6.0.sh b/pkgs/servers/http/tomcat/builder-6.0.sh
new file mode 100644
index 00000000000..ae2f934af59
--- /dev/null
+++ b/pkgs/servers/http/tomcat/builder-6.0.sh
@@ -0,0 +1,6 @@
+source $stdenv/setup
+
+tar zxf $src
+
+mkdir $out
+mv apache-tomcat*/* $out
diff --git a/pkgs/servers/irc/ircd-hybrid/default.nix b/pkgs/servers/irc/ircd-hybrid/default.nix
index 3f9fd380d14..572cc28e55b 100644
--- a/pkgs/servers/irc/ircd-hybrid/default.nix
+++ b/pkgs/servers/irc/ircd-hybrid/default.nix
@@ -1,17 +1,17 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "ircd-hybrid-7.2.2";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = mirror://sourceforge/ircd-hybrid/ircd-hybrid-7.2.2.tgz;
     sha256 = "1xn4dfbgx019mhismfnr2idhslvarlajyahj7c6bqzmarcwwrvck";
   };
 
-  buildInputs =(with args; [openssl zlib]);
+  buildInputs = [openssl zlib];
 
-  configureFlags = (with args; ["--with-nicklen=100" 
+  configureFlags =  ["--with-nicklen=100" 
 	"--with-topiclen=360" 
-	("--enable-openssl=" + openssl)]);
+	("--enable-openssl=" + openssl)];
 
   preInstall = "mkdir -p \${out}/ ; ln -s /home/ircd \${out}/logs;";
 
diff --git a/pkgs/servers/monitoring/nagios/default.nix b/pkgs/servers/monitoring/nagios/default.nix
index 8a24e9dfaa4..dba063bb106 100644
--- a/pkgs/servers/monitoring/nagios/default.nix
+++ b/pkgs/servers/monitoring/nagios/default.nix
@@ -1,4 +1,6 @@
-{ stdenv, fetchurl, perl }:
+{ stdenv, fetchurl, perl, gdSupport ? false
+, gd ? null, libpng ? null, zlib ? null
+}:
 
 stdenv.mkDerivation {
   name = "nagios-2.10";
@@ -9,7 +11,7 @@ stdenv.mkDerivation {
   };
 
   patches = [./nagios.patch];
-  buildInputs = [perl];
+  buildInputs = [perl] ++ (if gdSupport then [gd libpng zlib] else []);
   buildFlags = "all";
   installTargets = "install install-config";
 
diff --git a/pkgs/servers/monitoring/nagios/plugins/official/default.nix b/pkgs/servers/monitoring/nagios/plugins/official/default.nix
index d415e833742..29eb7bbb7a0 100644
--- a/pkgs/servers/monitoring/nagios/plugins/official/default.nix
+++ b/pkgs/servers/monitoring/nagios/plugins/official/default.nix
@@ -20,6 +20,8 @@ stdenv.mkDerivation {
     )
   ";
 
+  postInstall = "ln -s libexec $out/bin";
+
   buildInputs = [openssh]; # !!! make openssh a runtime dependency only
 
   meta = {
diff --git a/pkgs/servers/samba/default.nix b/pkgs/servers/samba/default.nix
index b46f6494c16..629ac2a31b8 100644
--- a/pkgs/servers/samba/default.nix
+++ b/pkgs/servers/samba/default.nix
@@ -1,14 +1,23 @@
 args: with args;
 
-stdenv.mkDerivation {
-  name = "samba-3.0.26a";
+stdenv.mkDerivation rec {
+  name = "samba-3.0.28";
 
   src = fetchurl {
-    url = http://us1.samba.org/samba/ftp/stable/samba-3.0.26a.tar.gz;
-    sha256 = "41e11f69288b2291f12f8db093e2c55dc1360555d4542c83c0758c4c7a3d4d37";
+    url = "http://us1.samba.org/samba/ftp/stable/${name}.tar.gz";
+    sha256 = "13nr4mvh6vxgl7nb94qnqx3njcyd10cf4ji18srlkizpp49r5byw";
   };
 
-  buildInputs = [readline pam openldap];
-  configureFlags = "--with-pam --with-smbmount";
+  buildInputs = [readline pam openldap kerberos popt iniparser libunwind fam];
+  configureFlags = ''--with-pam --with-smbmount --datadir=$out/share
+  --with-aio-support ''
+  + (if (stdenv.gcc.libc != null) then "--with-libiconv=${stdenv.gcc.libc}" else "");
   postUnpack = "sourceRoot=\$sourceRoot/source";
+  
+  configFile = ./smb.conf;
+  postInstall = ''
+  rm -rf $out/var
+  ln -s /var/samba $out/var
+  cp ${configFile} $out/lib/smb.conf
+  '';
 }
diff --git a/pkgs/servers/samba/smb.conf b/pkgs/servers/samba/smb.conf
new file mode 100644
index 00000000000..c9da0d2cbb5
--- /dev/null
+++ b/pkgs/servers/samba/smb.conf
@@ -0,0 +1,271 @@
+# This is the main Samba configuration file. You should read the
+# smb.conf(5) manual page in order to understand the options listed
+# here. Samba has a huge number of configurable options (perhaps too
+# many!) most of which are not shown in this example
+#
+# For a step to step guide on installing, configuring and using samba, 
+# read the Samba-HOWTO-Collection. This may be obtained from:
+#  http://www.samba.org/samba/docs/Samba-HOWTO-Collection.pdf
+#
+# Many working examples of smb.conf files can be found in the 
+# Samba-Guide which is generated daily and can be downloaded from: 
+#  http://www.samba.org/samba/docs/Samba-Guide.pdf
+#
+# Any line which starts with a ; (semi-colon) or a # (hash) 
+# is a comment and is ignored. In this example we will use a #
+# for commentry and a ; for parts of the config file that you
+# may wish to enable
+#
+# NOTE: Whenever you modify this file you should run the command "testparm"
+# to check that you have not made any basic syntactic errors. 
+#
+#======================= Global Settings =====================================
+[global]
+
+# workgroup = NT-Domain-Name or Workgroup-Name, eg: MIDEARTH
+   workgroup = NIXOSGROUP
+
+# server string is the equivalent of the NT Description field
+   server string = Samba Server
+
+# Security mode. Defines in which mode Samba will operate. Possible 
+# values are share, user, server, domain and ads. Most people will want 
+# user level security. See the Samba-HOWTO-Collection for details.
+   security = user
+
+# This option is important for security. It allows you to restrict
+# connections to machines which are on your local network. The
+# following example restricts access to two C class networks and
+# the "loopback" interface. For more examples of the syntax see
+# the smb.conf man page
+;   hosts allow = 192.168.1. 192.168.2. 127.
+
+# If you want to automatically load your printer list rather
+# than setting them up individually then you'll need this
+   load printers = yes
+
+# you may wish to override the location of the printcap file
+;   printcap name = /etc/printcap
+
+# on SystemV system setting printcap name to lpstat should allow
+# you to automatically obtain a printer list from the SystemV spool
+# system
+;   printcap name = lpstat
+
+# It should not be necessary to specify the print system type unless
+# it is non-standard. Currently supported print systems include:
+# bsd, cups, sysv, plp, lprng, aix, hpux, qnx
+;   printing = cups
+
+# Uncomment this if you want a guest account, you must add this to /etc/passwd
+# otherwise the user "nobody" is used
+  guest account = smbguest
+
+# this tells Samba to use a separate log file for each machine
+# that connects
+   log file = /var/samba/sambalog/log.%m
+
+# Put a capping on the size of the log files (in Kb).
+   max log size = 50
+
+# Use password server option only with security = server
+# The argument list may include:
+#   password server = My_PDC_Name [My_BDC_Name] [My_Next_BDC_Name]
+# or to auto-locate the domain controller/s
+#   password server = *
+;   password server = <NT-Server-Name>
+
+# Use the realm option only with security = ads
+# Specifies the Active Directory realm the host is part of
+;   realm = MY_REALM
+
+# Backend to store user information in. New installations should 
+# use either tdbsam or ldapsam. smbpasswd is available for backwards 
+# compatibility. tdbsam requires no further configuration.
+   passdb backend = tdbsam:/var/samba/passdb.tdb
+
+# Using the following line enables you to customise your configuration
+# on a per machine basis. The %m gets replaced with the netbios name
+# of the machine that is connecting.
+# Note: Consider carefully the location in the configuration file of
+#       this line.  The included file is read at that point.
+;   include = /usr/local/samba/lib/smb.conf.%m
+
+# Configure Samba to use multiple interfaces
+# If you have multiple network interfaces then you must list them
+# here. See the man page for details.
+;   interfaces = 192.168.12.2/24 192.168.13.2/24 
+
+# Browser Control Options:
+# set local master to no if you don't want Samba to become a master
+# browser on your network. Otherwise the normal election rules apply
+;   local master = no
+
+# OS Level determines the precedence of this server in master browser
+# elections. The default value should be reasonable
+;   os level = 33
+
+# Domain Master specifies Samba to be the Domain Master Browser. This
+# allows Samba to collate browse lists between subnets. Don't use this
+# if you already have a Windows NT domain controller doing this job
+;   domain master = yes 
+
+# Preferred Master causes Samba to force a local browser election on startup
+# and gives it a slightly higher chance of winning the election
+;   preferred master = yes
+
+# Enable this if you want Samba to be a domain logon server for 
+# Windows95 workstations. 
+;   domain logons = yes
+
+# if you enable domain logons then you may want a per-machine or
+# per user logon script
+# run a specific logon batch file per workstation (machine)
+;   logon script = %m.bat
+# run a specific logon batch file per username
+;   logon script = %U.bat
+
+# Where to store roving profiles (only for Win95 and WinNT)
+#        %L substitutes for this servers netbios name, %U is username
+#        You must uncomment the [Profiles] share below
+;   logon path = \\%L\Profiles\%U
+
+# Windows Internet Name Serving Support Section:
+# WINS Support - Tells the NMBD component of Samba to enable it's WINS Server
+;   wins support = yes
+
+# WINS Server - Tells the NMBD components of Samba to be a WINS Client
+#	Note: Samba can be either a WINS Server, or a WINS Client, but NOT both
+;   wins server = w.x.y.z
+
+# WINS Proxy - Tells Samba to answer name resolution queries on
+# behalf of a non WINS capable client, for this to work there must be
+# at least one	WINS Server on the network. The default is NO.
+;   wins proxy = yes
+
+# DNS Proxy - tells Samba whether or not to try to resolve NetBIOS names
+# via DNS nslookups. The default is NO.
+   dns proxy = no 
+
+# These scripts are used on a domain controller or stand-alone 
+# machine to add or delete corresponding unix accounts
+;  add user script = /usr/sbin/useradd %u
+;  add group script = /usr/sbin/groupadd %g
+;  add machine script = /usr/sbin/adduser -n -g machines -c Machine -d /dev/null -s /bin/false %u
+;  delete user script = /usr/sbin/userdel %u
+;  delete user from group script = /usr/sbin/deluser %u %g
+;  delete group script = /usr/sbin/groupdel %g
+
+
+#============================ Share Definitions ==============================
+[homes]
+   comment = Home Directories
+   browseable = yes
+   writable = yes
+
+# Un-comment the following and create the netlogon directory for Domain Logons
+; [netlogon]
+;   comment = Network Logon Service
+;   path = /usr/local/samba/lib/netlogon
+;   guest ok = yes
+;   writable = no
+;   share modes = no
+
+
+# Un-comment the following to provide a specific roving profile share
+# the default is to use the user's home directory
+;[Profiles]
+;    path = /usr/local/samba/profiles
+;    browseable = no
+;    guest ok = yes
+
+
+# NOTE: If you have a BSD-style print system there is no need to 
+# specifically define each individual printer
+[printers]
+   comment = All Printers
+   path = /usr/spool/samba
+   browseable = no
+# Set public = yes to allow user 'guest account' to print
+   guest ok = no
+   writable = no
+   printable = yes
+
+# This one is useful for people to share files
+;[tmp]
+;   comment = Temporary file space
+;   path = /tmp
+;   read only = no
+;   public = yes
+
+# A publicly accessible directory, but read only, except for people in
+# the "staff" group
+;[public]
+;   comment = Public Stuff
+;   path = /home/samba
+;   public = yes
+;   writable = yes
+;   printable = no
+;   write list = @staff
+
+# Other examples. 
+#
+# A private printer, usable only by fred. Spool data will be placed in fred's
+# home directory. Note that fred must have write access to the spool directory,
+# wherever it is.
+;[fredsprn]
+;   comment = Fred's Printer
+;   valid users = fred
+;   path = /homes/fred
+;   printer = freds_printer
+;   public = no
+;   writable = no
+;   printable = yes
+
+# A private directory, usable only by fred. Note that fred requires write
+# access to the directory.
+;[fredsdir]
+;   comment = Fred's Service
+;   path = /usr/somewhere/private
+;   valid users = fred
+;   public = no
+;   writable = yes
+;   printable = no
+
+# a service which has a different directory for each machine that connects
+# this allows you to tailor configurations to incoming machines. You could
+# also use the %U option to tailor it by user name.
+# The %m gets replaced with the machine name that is connecting.
+;[pchome]
+;  comment = PC Directories
+;  path = /usr/pc/%m
+;  public = no
+;  writable = yes
+
+# A publicly accessible directory, read/write to all users. Note that all files
+# created in the directory by users will be owned by the default user, so
+# any user with access can delete any other user's files. Obviously this
+# directory must be writable by the default user. Another user could of course
+# be specified, in which case all files would be owned by that user instead.
+;[public]
+;   path = /usr/somewhere/else/public
+;   public = yes
+;   only guest = yes
+;   writable = yes
+;   printable = no
+
+# The following two entries demonstrate how to share a directory so that two
+# users can place files there that will be owned by the specific users. In this
+# setup, the directory should be writable by both users and should have the
+# sticky bit set on it to prevent abuse. Obviously this could be extended to
+# as many users as required.
+;[myshare]
+;   comment = Mary's and Fred's stuff
+;   path = /usr/somewhere/shared
+;   valid users = mary fred
+;   public = no
+;   writable = yes
+;   printable = no
+;   create mask = 0765
+
+
diff --git a/pkgs/servers/sql/mysql5/default.nix b/pkgs/servers/sql/mysql5/default.nix
index d76a81184d2..89107d10864 100644
--- a/pkgs/servers/sql/mysql5/default.nix
+++ b/pkgs/servers/sql/mysql5/default.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl, ps, ncurses, zlib ? null, perl}:
+args: with args;
 
 # Note: zlib is not required; MySQL can use an internal zlib.
 
@@ -10,7 +10,8 @@ stdenv.mkDerivation {
     sha256 = "e4443d8dc859ed53bd9f3bef143ce30c7f5dee66a02748e9a003136be25e0060";
   };
 
-  buildInputs = [ps ncurses zlib perl];
+  buildInputs = [ps ncurses zlib perl openssl];
+  postInstall = "ln -s mysqld_safe $out/bin/mysqld";
 
-  configureFlags = "--enable-thread-safe-client";
+  configureFlags = "--enable-thread-safe-client --with-embedded-server --disable-static --with-openssl=${openssl} --with-berkeley-db";
 }
diff --git a/pkgs/servers/sql/postgresql/8.2.6.nix b/pkgs/servers/sql/postgresql/8.2.6.nix
new file mode 100644
index 00000000000..f5ce8741f86
--- /dev/null
+++ b/pkgs/servers/sql/postgresql/8.2.6.nix
@@ -0,0 +1,14 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "postgresql-" + version;
+  LC_ALL = "en_US";
+
+  src = fetchurl {
+    url = "ftp://ftp.de.postgresql.org/mirror/postgresql/source/v${version}/${name}.tar.bz2";
+    sha256="056ixbsfmdwhniryc0mr1kl66jywkqqhqvjdi7i3v4qzh9z34hgf";
+  };
+
+  passthru = { inherit readline; };
+  buildInputs = [zlib ncurses readline];
+}
diff --git a/pkgs/servers/sql/postgresql/8.3.0.nix b/pkgs/servers/sql/postgresql/8.3.0.nix
new file mode 100644
index 00000000000..04244fff85b
--- /dev/null
+++ b/pkgs/servers/sql/postgresql/8.3.0.nix
@@ -0,0 +1,14 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "postgresql-" + version;
+  LC_ALL = "en_US";
+
+  src = fetchurl {
+    url = "ftp://ftp.de.postgresql.org/mirror/postgresql/source/v${version}/${name}.tar.bz2";
+    sha256="19kf0q45d5zd1rxffin0iblizckk8cp6fpgb52sipqkpnmm6sdc5";
+  };
+
+  passthru = { inherit readline; };
+  buildInputs = [zlib ncurses readline];
+}
diff --git a/pkgs/servers/sql/postgresql/default.nix b/pkgs/servers/sql/postgresql/default.nix
index b9ed02ffd20..d04712d3418 100644
--- a/pkgs/servers/sql/postgresql/default.nix
+++ b/pkgs/servers/sql/postgresql/default.nix
@@ -5,14 +5,21 @@ assert ncurses != null;
 assert readline != null;
 
 stdenv.mkDerivation {
-  name = "postgresql-8.0.6";
-  builder = ./builder.sh;
+  name = "postgresql-8.3.0";
 
   src = fetchurl {
-    url = ftp://ftp2.nl.postgresql.org/mirror/postgresql/source/v8.0.6/postgresql-8.0.6.tar.bz2;
-    md5 = "f3b27b8171267f9a87592f931c09f0ee";
+    url = http://ftp2.nl.postgresql.org/source/v8.3.0/postgresql-8.3.0.tar.bz2;
+    sha256 = "19kf0q45d5zd1rxffin0iblizckk8cp6fpgb52sipqkpnmm6sdc5";
   };
 
   inherit readline;
+  
   buildInputs = [zlib ncurses readline];
+
+  LANG = "en_US"; # is this needed anymore?
+
+  meta = {
+    description = "The world's most advanced open source database";
+    homepage = http://www.postgresql.org/;
+  };
 }
diff --git a/pkgs/servers/squid/default.nix b/pkgs/servers/squid/default.nix
new file mode 100644
index 00000000000..6bf63ae027b
--- /dev/null
+++ b/pkgs/servers/squid/default.nix
@@ -0,0 +1,22 @@
+args:
+( args.mkDerivationByConfiguration {
+    flagConfig = {
+      mandatory = { buildInputs = [ "perl" ]; };
+      # many options I don't know wether they should be default .. 
+    }; 
+
+    extraAttrs = co : {
+      name = "squid-2.6-stable";
+
+      src = args.fetchurl {
+        url = http://www.squid-cache.org/Versions/v2/2.6/squid-2.6.STABLE16.tar.bz2;
+        sha256 = "1iv21a4cl74bqzrk07l0lbzlq3n9qpd0r31fgsjv2dsabj46qc4y";
+      };
+
+      meta = { 
+        description = "http-proxy";
+        homepage = "http://www.squid-cache.org";
+        license = "GPL2";
+      };
+  };
+} ) args
diff --git a/pkgs/servers/x11/xorg/default.nix b/pkgs/servers/x11/xorg/default.nix
index 4cd28a1f938..9ce0ce47bc8 100644
--- a/pkgs/servers/x11/xorg/default.nix
+++ b/pkgs/servers/x11/xorg/default.nix
@@ -1,8 +1,5 @@
 # This is a generated file.  Do not edit!
-{ stdenv, fetchurl, pkgconfig, freetype, fontconfig
-, libxslt, expat, libdrm, libpng, zlib, perl, mesa, mesaHeaders
-, xkeyboard_config, gettext
-}:
+args: with args;
 
 rec {
 
@@ -883,8 +880,9 @@ rec {
       url = http://mirror.switch.ch/ftp/mirror/X11/pub/X11R7.3/src/everything/libXpm-3.5.7.tar.bz2;
       sha256 = "1aibr6y6hnlgc7m1a1y5s1qx7863praq4pdp0xrpkc75gkk1lw34";
     };
-    buildInputs = [pkgconfig gettext libX11 libXext xextproto xproto libXt ];
-  }) // {inherit gettext libX11 libXext xextproto xproto libXt ;};
+    buildInputs = [pkgconfig libX11 libXext xextproto xproto libXt ];
+    patchPhase = "sed -i '/USE_GETTEXT_TRUE/d' sxpm/Makefile.in cxpm/Makefile.in";
+  }) // {inherit libX11 libXext xextproto xproto libXt ;};
     
   libXprintAppUtil = (stdenv.mkDerivation {
     name = "libXprintAppUtil-1.0.1";
@@ -1283,7 +1281,7 @@ rec {
       url = http://mirror.switch.ch/ftp/mirror/X11/pub/X11R7.3/src/everything/setxkbmap-1.0.4.tar.bz2;
       sha256 = "1b1brw1v98q2rqhr5x7f8mr3clxq62nw5175gpamg5s172916nwv";
     };
-    buildInputs = [pkgconfig libX11 libxkbfile ]; postInstall = "ln -sfn ${xkeyboard_config}/etc $out/share"; 
+    buildInputs = [pkgconfig libX11 libxkbfile ]; postInstall = "ensureDir $out/share; ln -sfn ${xkeyboard_config}/etc/X11 $out/share/X11";
   }) // {inherit libX11 libxkbfile ;};
     
   showfont = (stdenv.mkDerivation {
@@ -1744,7 +1742,7 @@ rec {
       sha256 = "15avwy8isbqagzcdj20ngqajl22k40pssfx7vjirhrqyyq19fiwb";
     };
     preBuild = "
-  	sed -e '/motion_history_proc/d; /history_size/d;' -i src/*.c
+    sed -e '/motion_history_proc/d; /history_size/d;' -i src/*.c
     ";
     buildInputs = [pkgconfig inputproto kbproto randrproto xorgserver xproto ];
   }) // {inherit inputproto kbproto randrproto xorgserver xproto ;};
@@ -1986,8 +1984,8 @@ rec {
       url = http://mirror.switch.ch/ftp/mirror/X11/pub/X11R7.3/src/everything/xf86-video-ati-6.6.3.tar.bz2;
       sha256 = "102p6nz1jvd3pgbl83a4zi99smydqr6il61r33l0lqmi3yg452nh";
     };
-    buildInputs = [pkgconfig fontsproto libdrm randrproto renderproto videoproto xextproto xf86driproto xf86miscproto xineramaproto xorgserver xproto ];
-  }) // {inherit fontsproto libdrm randrproto renderproto videoproto xextproto xf86driproto xf86miscproto xineramaproto xorgserver xproto ;};
+    buildInputs = [pkgconfig fontsproto libdrm randrproto renderproto videoproto xextproto xf86driproto xf86miscproto xineramaproto xorgserver xproto mesaHeaders glproto ];
+  }) // {inherit fontsproto libdrm randrproto renderproto videoproto xextproto xf86driproto xf86miscproto xineramaproto xorgserver xproto mesaHeaders glproto;};
     
   xf86videochips = (stdenv.mkDerivation {
     name = "xf86-video-chips-1.1.1";
@@ -2216,8 +2214,8 @@ rec {
       url = http://mirror.switch.ch/ftp/mirror/X11/pub/X11R7.3/src/everything/xf86-video-sis-0.9.3.tar.bz2;
       sha256 = "1xin2hcjjwj2810h7kxhkmqq841plbsvk0swmjl9py7z2vxyi3l9";
     };
-    buildInputs = [pkgconfig fontsproto libdrm randrproto renderproto videoproto xextproto xf86dgaproto xf86driproto xf86miscproto xineramaproto xorgserver xproto ];
-  }) // {inherit fontsproto libdrm randrproto renderproto videoproto xextproto xf86dgaproto xf86driproto xf86miscproto xineramaproto xorgserver xproto ;};
+    buildInputs = [pkgconfig fontsproto glproto mesaHeaders libdrm randrproto renderproto videoproto xextproto xf86dgaproto xf86driproto xf86miscproto xineramaproto xorgserver xproto ];
+  }) // {inherit fontsproto glproto mesaHeaders libdrm randrproto renderproto videoproto xextproto xf86dgaproto xf86driproto xf86miscproto xineramaproto xorgserver xproto ;};
     
   xf86videosisusb = (stdenv.mkDerivation {
     name = "xf86-video-sisusb-0.8.1";
@@ -2716,8 +2714,8 @@ rec {
       url = http://mirror.switch.ch/ftp/mirror/X11/pub/X11R7.3/src/everything/xorg-server-1.4.tar.bz2;
       sha256 = "1hpbq0bl1jkq84gvksp0xzbbrwwgl0wz2wakf11p2hld6bgl5cai";
     };
-    buildInputs = [pkgconfig pixman renderproto bigreqsproto compositeproto damageproto libdmx dmxproto evieext fixesproto fontcacheproto libfontenc fontsproto freetype glproto inputproto kbproto libdrm mkfontdir mkfontscale perl printproto randrproto recordproto resourceproto scrnsaverproto trapproto videoproto libX11 libXau libXaw xcmiscproto libXdmcp libXext xextproto xf86bigfontproto xf86dgaproto xf86driproto xf86miscproto xf86vidmodeproto libXfixes libXfont libXi xineramaproto libxkbfile libxkbui libXmu libXpm xproto libXrender libXres libXt xtrans libXtst libXxf86misc libXxf86vm zlib ]; mesaSrc = mesa.src; x11BuildHook = ./xorgserver.sh; patches = [./xorgserver-dri-path.patch ./xorgserver-xkbcomp-path.patch ./xorgserver-xkb-leds.patch ]; 
-  }) // {inherit pixman renderproto bigreqsproto compositeproto damageproto libdmx dmxproto evieext fixesproto fontcacheproto libfontenc fontsproto freetype glproto inputproto kbproto libdrm mkfontdir mkfontscale perl printproto randrproto recordproto resourceproto scrnsaverproto trapproto videoproto libX11 libXau libXaw xcmiscproto libXdmcp libXext xextproto xf86bigfontproto xf86dgaproto xf86driproto xf86miscproto xf86vidmodeproto libXfixes libXfont libXi xineramaproto libxkbfile libxkbui libXmu libXpm xproto libXrender libXres libXt xtrans libXtst libXxf86misc libXxf86vm zlib ;};
+    buildInputs = [pkgconfig pixman renderproto bigreqsproto compositeproto damageproto dbus.libs libdmx dmxproto evieext fixesproto fontcacheproto libfontenc fontsproto freetype glproto hal inputproto kbproto libdrm mkfontdir mkfontscale perl printproto randrproto recordproto resourceproto scrnsaverproto trapproto videoproto libX11 libXau libXaw xcmiscproto libXdmcp libXext xextproto xf86bigfontproto xf86dgaproto xf86driproto xf86miscproto xf86vidmodeproto libXfixes libXfont libXi xineramaproto libxkbfile libxkbui libXmu libXpm xproto libXrender libXres libXt xtrans libXtst libXxf86misc libXxf86vm zlib ]; mesaSrc = mesa.src; x11BuildHook = ./xorgserver.sh; patches = [./xorgserver-dri-path.patch ./xorgserver-xkbcomp-path.patch ./xorgserver-xkb-leds.patch ]; 
+  }) // {inherit pixman renderproto bigreqsproto compositeproto damageproto libdmx dmxproto evieext fixesproto fontcacheproto libfontenc fontsproto freetype glproto hal inputproto kbproto libdrm mkfontdir mkfontscale perl printproto randrproto recordproto resourceproto scrnsaverproto trapproto videoproto libX11 libXau libXaw xcmiscproto libXdmcp libXext xextproto xf86bigfontproto xf86dgaproto xf86driproto xf86miscproto xf86vidmodeproto libXfixes libXfont libXi xineramaproto libxkbfile libxkbui libXmu libXpm xproto libXrender libXres libXt xtrans libXtst libXxf86misc libXxf86vm zlib ;};
     
   xorgsgmldoctools = (stdenv.mkDerivation {
     name = "xorg-sgml-doctools-1.2";
diff --git a/pkgs/servers/x11/xorg/generate-expr-from-tarballs.pl b/pkgs/servers/x11/xorg/generate-expr-from-tarballs.pl
index 9bdf7279f52..7fb12233044 100755
--- a/pkgs/servers/x11/xorg/generate-expr-from-tarballs.pl
+++ b/pkgs/servers/x11/xorg/generate-expr-from-tarballs.pl
@@ -35,22 +35,30 @@ $pcMap{"mkfontscale"} = "mkfontscale";
 $pcMap{"mkfontdir"} = "mkfontdir";
 $pcMap{"bdftopcf"} = "bdftopcf";
 $pcMap{"libxslt"} = "libxslt";
-$pcMap{"gettext"} = "gettext";
+$pcMap{"dbus-1"} = "dbus";
+$pcMap{"hal"} = "hal";
 
 $pcMap{"\$PIXMAN"} = "pixman";
 $pcMap{"\$RENDERPROTO"} = "renderproto";
 
 
-$extraAttrs{"xorgserver"} = " mesaSrc = mesa.src; x11BuildHook = ./xorgserver.sh; patches = [./xorgserver-dri-path.patch ./xorgserver-xkbcomp-path.patch]; ";
+$extraAttrs{"xorgserver"} = " mesaSrc = mesa.src; x11BuildHook = ./xorgserver.sh; patches = [./xorgserver-dri-path.patch ./xorgserver-xkbcomp-path.patch ./xorgserver-xkb-leds.patch ]; ";
 
 $extraAttrs{"imake"} = " inherit xorgcffiles; x11BuildHook = ./imake.sh; patches = [./imake.patch]; ";
 
-$extraAttrs{"setxkbmap"} = " postInstall = \"ln -sfn \${xkeyboard_config}/etc \$out/share\"; ";
+$extraAttrs{"setxkbmap"} = " postInstall = \"ensureDir \$out/share; ln -sfn \${xkeyboard_config}/etc/X11 \$out/share/X11\";";
 
 $extraAttrs{"fontmiscmisc"} = " postInstall = \"ln -s \${fontalias}/lib/X11/fonts/misc/fonts.alias \$out/lib/X11/fonts/misc/fonts.alias\"; ";
 
 $extraAttrs{"mkfontdir"} = " preBuild = \"substituteInPlace mkfontdir.cpp --replace BINDIR \${mkfontscale}/bin\"; ";
 
+$extraAttrs{"xf86inputevdev"} = "
+    preBuild = \"
+    sed -e '/motion_history_proc/d; /history_size/d;' -i src/*.c
+    \";";
+
+$extraAttrs{"libXpm"} = "
+    patchPhase = \"sed -i '/USE_GETTEXT_TRUE/d' sxpm/Makefile.in cxpm/Makefile.in\";";
 
 my $downloadCache = "./download-cache";
 $ENV{'NIX_DOWNLOAD_CACHE'} = $downloadCache;
@@ -107,7 +115,7 @@ while (<>) {
     my $file;
     {
         local $/;
-        open FOO, "cd '$tmpDir'/* && cat configure.ac |";
+        open FOO, "cd '$tmpDir'/* && grep -v '^ *#' configure.ac |";
         $file = <FOO>;
         close FOO;
     }
@@ -174,11 +182,11 @@ while (<>) {
     process \@requires, $1 while $file =~ /XORG_DRIVER_CHECK_EXT\([^,]*,([^\)]*)\)/g;
 
     push @requires, "glproto", "mesaHeaders" if $pkg =~ /xf86videoi810/;
+    push @requires, "glproto", "mesaHeaders" if $pkg =~ /xf86videosis/;
     push @requires, "glproto", "mesaHeaders" if $pkg =~ /xf86videointel/;
     push @requires, "zlib" if $pkg =~ /xorgserver/;
     push @requires, "xf86bigfontproto" if $pkg =~ /xorgserver/;
     push @requires, "libxslt" if $pkg =~ /libxcb/;
-    push @requires, "gettext" if $pkg =~ /libXpm/;
     
     print "REQUIRES @requires => $pkg\n";
     $pkgRequires{$pkg} = \@requires;
@@ -194,10 +202,7 @@ open OUT, ">default2.nix";
 print OUT "";
 print OUT <<EOF;
 # This is a generated file.  Do not edit!
-{ stdenv, fetchurl, pkgconfig, freetype, fontconfig
-, libxslt, expat, libdrm, libpng, zlib, perl, mesa, mesaHeaders
-, xkeyboard_config, gettext
-}:
+args: with args;
 
 rec {
 
diff --git a/pkgs/servers/xmpp/ejabberd/builder.sh b/pkgs/servers/xmpp/ejabberd/builder.sh
new file mode 100644
index 00000000000..3d746054f38
--- /dev/null
+++ b/pkgs/servers/xmpp/ejabberd/builder.sh
@@ -0,0 +1,9 @@
+buildInputs="$expat $erlang $zlib $openssl"
+
+source $stdenv/setup
+
+tar xfvz $src
+cd ejabberd-*/src
+./configure --prefix=$out
+make
+make install
diff --git a/pkgs/servers/xmpp/ejabberd/default.nix b/pkgs/servers/xmpp/ejabberd/default.nix
new file mode 100644
index 00000000000..c3c88337c5d
--- /dev/null
+++ b/pkgs/servers/xmpp/ejabberd/default.nix
@@ -0,0 +1,11 @@
+{stdenv, fetchurl, expat, erlang, zlib, openssl}:
+
+stdenv.mkDerivation {
+  name = "ejabberd-2.0.0-rc1";
+  builder = ./builder.sh;
+  src = fetchurl {
+    url = http://www.process-one.net/downloads/ejabberd/2.0.0-rc1/ejabberd-2.0.0-rc1.tar.gz;
+    sha256 = "02ldssvsy0rkvxm96018fpk5lc3iqgkrira9cw1ym2snas0k8nzy";
+  };
+  inherit expat erlang zlib openssl;
+}
diff --git a/pkgs/shells/bash/default.nix b/pkgs/shells/bash/default.nix
index 1877080049b..31fa5e77649 100644
--- a/pkgs/shells/bash/default.nix
+++ b/pkgs/shells/bash/default.nix
@@ -3,11 +3,11 @@
 assert interactive -> ncurses != null;
 
 stdenv.mkDerivation {
-  name = "bash-3.2-p17";
+  name = "bash-3.2-p33";
 
   src = fetchurl {
-    url = http://losser.st-lab.cs.uu.nl/~eelco/dist/bash-3.2-p17.tar.bz2;
-    sha256 = "153gg2z2s3ar7vni3345nnmdisha4b8cxzsj79d8ap6m6i4c35f5";
+    url = http://losser.st-lab.cs.uu.nl/~eelco/dist/bash-3.2-p33.tar.bz2;
+    sha256 = "11fv73nbcckmm4f1q9cf73754chsgfps9pklwcaj2ryfd5ql9wnb";
   };
 
   postInstall = "ln -s bash $out/bin/sh";
@@ -21,6 +21,7 @@ stdenv.mkDerivation {
   buildInputs = [bison] ++ stdenv.lib.optional interactive ncurses;
 
   meta = {
+    homepage = http://www.gnu.org/software/bash/;
     description =
       "GNU Bourne-Again Shell, the de facto standard shell on Linux" +
         (if interactive then " (for interactive use)" else "");
diff --git a/pkgs/shells/tcsh/default.nix b/pkgs/shells/tcsh/default.nix
index cd374289d54..f0ef071bb56 100644
--- a/pkgs/shells/tcsh/default.nix
+++ b/pkgs/shells/tcsh/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, ncurses}:
 
 stdenv.mkDerivation {
-  name = "tcsh-6.14.00";
+  name = "tcsh-6.15.00";
   src = fetchurl {
-    url = ftp://ftp.gw.com/pub/unix/tcsh/tcsh-6.14.00.tar.gz;
-    md5 = "353d1bb7d2741bf8de602c7b6f0efd79";
+    url = ftp://ftp.funet.fi/pub/unix/shells/tcsh/tcsh-6.15.00.tar.gz;
+    sha256 = "1p5chgvj87m2dv4ci9qf4i81gav0lzr7rkcm320sj62z09ckxa6w";
   };
   buildInputs = [ncurses];
 }
diff --git a/pkgs/shells/zsh/default.nix b/pkgs/shells/zsh/4.3.4.nix
index 0b227b031b8..ea9a82cf683 100644
--- a/pkgs/shells/zsh/default.nix
+++ b/pkgs/shells/zsh/4.3.4.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl, coreutils, ncurses}:
+args: with args;
 stdenv.mkDerivation {
   name = "zsh-4.3.4";
 
diff --git a/pkgs/shells/zsh/4.3.5.nix b/pkgs/shells/zsh/4.3.5.nix
new file mode 100644
index 00000000000..227da7995fb
--- /dev/null
+++ b/pkgs/shells/zsh/4.3.5.nix
@@ -0,0 +1,22 @@
+args: with args;
+let documentation = fetchurl {
+    url = http://www.math.technion.ac.il/pub/zsh/zsh-4.3.5-doc.tar.bz2;
+    sha256 = "0jf35xibp8wfka7rdk9q8spkwprlhjx1sp7vp6img8wks12cvlkx";
+  };
+in
+stdenv.mkDerivation {
+  name = "zsh-${version}";
+
+  src = fetchurl {
+    url = http://www.math.technion.ac.il/pub/zsh/zsh-4.3.5.tar.bz2;
+    sha256 = "0191j3liflkjrj39i2yrs3ab9jcx4zd93rirx3j17dymfgqlvrzb";
+  };
+  configureFlags = "--with-tcsetpgrp --enable-maildir-support --enable-multibyte";
+
+  postInstall = ''
+    ensureDir $out/share/
+    tar xf ${documentation} -C $out/share
+  '';
+
+  buildInputs = [ncurses coreutils];
+}
diff --git a/pkgs/stdenv/common-path.nix b/pkgs/stdenv/common-path.nix
index 0ad0d83255b..3b267a543c6 100644
--- a/pkgs/stdenv/common-path.nix
+++ b/pkgs/stdenv/common-path.nix
@@ -11,4 +11,5 @@
   pkgs.gnumake
   pkgs.bash
   pkgs.patch
+  pkgs.replace
 ]
diff --git a/pkgs/stdenv/cygwin/prehook.sh b/pkgs/stdenv/cygwin/prehook.sh
index 673640c0d4a..b2ada869b29 100644
--- a/pkgs/stdenv/cygwin/prehook.sh
+++ b/pkgs/stdenv/cygwin/prehook.sh
@@ -3,3 +3,5 @@ export NIX_ENFORCE_PURITY=
 if test -z "$cygwinConfigureEnableShared"; then
   export configureFlags="$configureFlags --disable-shared"
 fi
+
+PATH_DELIMITER=';'
diff --git a/pkgs/stdenv/generic/builder.sh b/pkgs/stdenv/generic/builder.sh
index ee2dbb3d0f9..0af3210dbc9 100644
--- a/pkgs/stdenv/generic/builder.sh
+++ b/pkgs/stdenv/generic/builder.sh
@@ -3,19 +3,26 @@ p2=$param2
 p3=$param3
 p4=$param4
 p5=$param5
+_preHook="$preHook"
+_postHook="$postHook"
+preHook=
+postHook=
 
 source $stdenv/setup
 
 mkdir $out
 
-substitute "$setup" "$out/setup" \
-    --subst-var preHook \
-    --subst-var postHook \
-    --subst-var initialPath \
-    --subst-var gcc \
-    --subst-var shell \
-    --subst-var-by param1 "$p1" \
-    --subst-var-by param2 "$p2" \
-    --subst-var-by param3 "$p3" \
-    --subst-var-by param4 "$p4" \
-    --subst-var-by param5 "$p5"
+# Can't use substitute() here, because replace may not have been
+# built yet (in the bootstrap).
+sed \
+    -e "s^@preHook@^$_preHook^g" \
+    -e "s^@postHook@^$_postHook^g" \
+    -e "s^@initialPath@^$initialPath^g" \
+    -e "s^@gcc@^$gcc^g" \
+    -e "s^@shell@^$shell^g" \
+    -e "s^@param1@^$p1^g" \
+    -e "s^@param2@^$p2^g" \
+    -e "s^@param3@^$p3^g" \
+    -e "s^@param4@^$p4^g" \
+    -e "s^@param5@^$p5^g" \
+    < "$setup" > "$out/setup"
diff --git a/pkgs/stdenv/generic/setup-new-2.sh b/pkgs/stdenv/generic/setup-new-2.sh
deleted file mode 100644
index 5e330846a4d..00000000000
--- a/pkgs/stdenv/generic/setup-new-2.sh
+++ /dev/null
@@ -1,878 +0,0 @@
-set -e
-
-test -z $NIX_GCC && NIX_GCC=@gcc@
-
-if [ -z ${system##*cygwin*} ]; then
-  PATH_DELIMITER=';'
-else
-  PATH_DELIMITER=':'
-fi
-
-addToSearchPathWithCustomDelimiter() {
-	local delimiter=$1
-	local varName=$2
-	local needDir=$3
-	local addDir=${4:-$needDir}
-	local prefix=$5
-	if [ -d $prefix$needDir ]; then
-		if [ -z ${!varName} ]; then
-			eval export ${varName}=${prefix}$addDir
-		else
-			eval export ${varName}=${!varName}${delimiter}${prefix}$addDir
-		fi
-	fi
-}
-
-addToSearchPath()
-{
-	addToSearchPathWithCustomDelimiter "${PATH_DELIMITER}" "$@"
-}
-
-# Set up the initial path.
-PATH=
-for i in $NIX_GCC @initialPath@; do
-    PATH=$PATH${PATH:+:}$i/bin
-done
-
-if test "$NIX_DEBUG" = "1"; then
-    echo "Initial path: $PATH"
-fi
-
-
-# Execute the pre-hook.
-export SHELL=@shell@
-if test -z "$shell"; then
-    export shell=@shell@
-fi
-param1=@param1@
-param2=@param2@
-param3=@param3@
-param4=@param4@
-param5=@param5@
-if test -n "@preHook@"; then
-    source @preHook@
-fi
-
-
-# Check that the pre-hook initialised SHELL.
-if test -z "$SHELL"; then echo "SHELL not set"; exit 1; fi
-
-
-# Hack: run gcc's setup hook.
-envHooks=()
-if test -f $NIX_GCC/nix-support/setup-hook; then
-    source $NIX_GCC/nix-support/setup-hook
-fi
-
-
-# Ensure that the given directories exists.
-ensureDir() {
-    local dir
-    for dir in "$@"; do
-        if ! test -x "$dir"; then mkdir -p "$dir"; fi
-    done
-}
-
-installBin() {
-  ensureDir $out/bin
-  cp "$@" $out/bin
-}
-
-assertEnvExists(){
-  if test -z "${!1}"; then
-      msg=${2:-error: assertion failed: env var $1 is required}
-      echo $msg >&2; exit 1
-  fi
-}
-
-# Called when some build action fails.  If $succeedOnFailure is set,
-# create the file `$out/nix-support/failed' to signal failure, and
-# exit normally.  Otherwise, exit with failure.
-fail() {
-    exitCode=$?
-    if test "$succeedOnFailure" = 1; then
-        ensureDir "$out/nix-support"
-        touch "$out/nix-support/failed"
-        exit 0
-    else
-        exit $?
-    fi
-}
-
-
-# Allow the caller to augment buildInputs (it's not always possible to
-# do this before the call to setup.sh, since the PATH is empty at that
-# point; here we have a basic Unix environment).
-eval "$addInputsHook"
-
-
-# Recursively find all build inputs.
-findInputs()
-{
-    local pkg=$1
-
-    case $pkgs in
-        *\ $pkg\ *)
-            return 0
-            ;;
-    esac
-
-    pkgs="$pkgs $pkg "
-
-    if test -f $pkg/nix-support/setup-hook; then
-        source $pkg/nix-support/setup-hook
-    fi
-
-    if test -f $pkg/nix-support/propagated-build-inputs; then
-        for i in $(cat $pkg/nix-support/propagated-build-inputs); do
-            findInputs $i
-        done
-    fi
-}
-
-pkgs=""
-if test -n "$buildinputs"; then
-    buildInputs="$buildinputs" # compatibility
-fi
-for i in $buildInputs $propagatedBuildInputs; do
-    findInputs $i
-done
-
-
-# Set the relevant environment variables to point to the build inputs
-# found above.
-addToEnv()
-{
-    local pkg=$1
-
-    if test "$ignoreFailedInputs" != "1" -a -e $1/nix-support/failed; then
-        echo "failed input $1" >&2
-        fail
-    fi
-
-    if test -d $1/bin; then
-        export _PATH=$_PATH${_PATH:+:}$1/bin
-    fi
-
-    for i in "${envHooks[@]}"; do
-        $i $pkg
-    done
-}
-
-for i in $pkgs; do
-    addToEnv $i
-done
-
-
-# Add the output as an rpath.
-if test "$NIX_NO_SELF_RPATH" != "1"; then
-    export NIX_LDFLAGS="-rpath $out/lib $NIX_LDFLAGS"
-fi
-
-
-# Strip debug information by default.
-if test -z "$NIX_STRIP_DEBUG"; then
-    export NIX_STRIP_DEBUG=1
-    export NIX_CFLAGS_STRIP="-g0 -Wl,--strip-debug"
-fi
-
-
-assertEnvExists NIX_STORE \
-    "Error: you have an old version of Nix that does not set the
-     NIX_STORE variable. This is required for purity checking.
-     Please upgrade."
-
-assertEnvExists NIX_BUILD_TOP \
-    "Error: you have an old version of Nix that does not set the
-     NIX_BUILD_TOP variable. This is required for purity checking.
-     Please upgrade."
-
-
-# Set the TZ (timezone) environment variable, otherwise commands like
-# `date' will complain (e.g., `Tue Mar 9 10:01:47 Local time zone must
-# be set--see zic manual page 2004').
-export TZ=UTC
-
-
-# Set the prefix.  This is generally $out, but it can be overriden,
-# for instance if we just want to perform a test build/install to a
-# temporary location and write a build report to $out.
-if test -z "$prefix"; then
-    prefix="$out";
-fi
-
-if test "$useTempPrefix" = "1"; then
-    prefix="$NIX_BUILD_TOP/tmp_prefix";
-fi
-
-
-# Execute the post-hook.
-if test -n "@postHook@"; then
-    source @postHook@
-fi
-
-PATH=$_PATH${_PATH:+:}$PATH
-if test "$NIX_DEBUG" = "1"; then
-    echo "Final path: $PATH"
-fi
-
-stripDirs() {
-	local dirs="$1"
-	local stripFlags="$2"
-	local dirsNew=
-
-	for d in ${dirs}; do
-		if test -d "$prefix/$d"; then
-			dirsNew="${dirsNew} $prefix/$d "
-		fi
-	done
-	dirs=${dirsNew}
-
-	if test -n "${dirs}"; then
-		echo $dirs
-		find $dirs -type f -print0 | xargs -0 strip $stripFlags || true
-	fi
-}
-
-######################################################################
-# Textual substitution functions.
-
-
-# Some disgusting hackery to escape replacements in Sed substitutions.
-# We should really have a tool that replaces literal values by other
-# literal values, without any need for escaping.
-escapeSed() {
-    local s="$1"
-    # The `tr' hack is to escape newlines.  Sed handles newlines very
-    # badly, so we just replace newlines with the magic character 0xff
-    # (377 octal).  So don't use that character in replacements :-P
-    echo -n "$1" | tr '\012' '\377' | sed -e 's^\\^\\\\^g' -e 's^\xff^\\n^g' -e 's/\^/\\^/g' -e 's/&/\\&/g'
-}
-
-
-substitute() {
-    local input="$1"
-    local output="$2"
-
-    local -a params=("$@")
-
-    local sedScript=$NIX_BUILD_TOP/.sedargs
-    rm -f $sedScript
-    touch $sedScript
-
-    local n p pattern replacement varName
-
-    for ((n = 2; n < ${#params[*]}; n += 1)); do
-        p=${params[$n]}
-
-        if test "$p" = "--replace"; then
-            pattern="${params[$((n + 1))]}"
-            replacement="${params[$((n + 2))]}"
-            n=$((n + 2))
-        fi
-
-        if test "$p" = "--subst-var"; then
-            varName="${params[$((n + 1))]}"
-            pattern="@$varName@"
-            replacement="${!varName}"
-            n=$((n + 1))
-        fi
-
-        if test "$p" = "--subst-var-by"; then
-            pattern="@${params[$((n + 1))]}@"
-            replacement="${params[$((n + 2))]}"
-            n=$((n + 2))
-        fi
-
-        replacement="$(escapeSed "$replacement")"
-
-        echo "s^$pattern^$replacement^g" >> $sedScript
-    done
-
-    sed -f $sedScript < "$input" > "$output".tmp
-    if test -x "$output"; then
-        chmod +x "$output".tmp
-    fi
-    mv -f "$output".tmp "$output"
-}
-
-
-substituteInPlace() {
-    local fileName="$1"
-    shift
-    substitute "$fileName" "$fileName" "$@"
-}
-
-
-substituteAll() {
-    local input="$1"
-    local output="$2"
-
-    # Select all environment variables that start with a lowercase character.
-    for envVar in $(env | sed "s/^[^a-z].*//" | sed "s/^\([^=]*\)=.*/\1/"); do
-        if test "$NIX_DEBUG" = "1"; then
-            echo "$envVar -> ${!envVar}"
-        fi
-        args="$args --subst-var $envVar"
-    done
-
-    substitute "$input" "$output" $args
-}
-
-
-######################################################################
-# What follows is the generic builder.
-
-
-nestingLevel=0
-
-startNest() {
-    nestingLevel=$(($nestingLevel + 1))
-    echo -en "\e[$1p"
-}
-
-stopNest() {
-    nestingLevel=$(($nestingLevel - 1))
-    echo -en "\e[q"
-}
-
-header() {
-    startNest "$2"
-    echo "$1"
-}
-
-# Make sure that even when we exit abnormally, the original nesting
-# level is properly restored.
-closeNest() {
-    while test $nestingLevel -gt 0; do
-        stopNest
-    done
-}
-
-trap "closeNest" EXIT
-
-
-# This function is useful for debugging broken Nix builds.  It dumps
-# all environment variables to a file `env-vars' in the build
-# directory.  If the build fails and the `-K' option is used, you can
-# then go to the build directory and source in `env-vars' to reproduce
-# the environment used for building.
-dumpVars() {
-    if test "$noDumpEnvVars" != "1"; then
-        export > $NIX_BUILD_TOP/env-vars
-    fi
-}
-
-
-# Redirect stdout/stderr to a named pipe connected to a `tee' process
-# that writes the specified file (and also to our original stdout).
-# The original stdout is saved in descriptor 3.
-startLog() {
-    local logFile=${logNr}_$1
-    logNr=$((logNr + 1))
-    if test "$logPhases" = 1; then
-        ensureDir $logDir
-
-        exec 3>&1
-
-        if test "$dontLogThroughTee" != 1; then
-            # This required named pipes (fifos).
-            logFifo=$NIX_BUILD_TOP/log_fifo
-            test -p $logFifo || mkfifo $logFifo
-            startLogWrite "$logDir/$logFile" "$logFifo"
-            exec > $logFifo 2>&1
-        else
-            exec > $logDir/$logFile 2>&1
-        fi
-    fi
-}
-
-# Factored into a separate function so that it can be overriden.
-startLogWrite() {
-    tee "$1" < "$2" &
-    logWriterPid=$!
-}
-
-
-if test -z "$logDir"; then
-    logDir=$out/log
-fi
-
-logNr=0
-
-# Restore the original stdout/stderr.
-stopLog() {
-    if test "$logPhases" = 1; then
-        exec >&3 2>&1
-
-        # Wait until the tee process has died.  Otherwise output from
-        # different phases may be mixed up.
-        if test -n "$logWriterPid"; then
-            wait $logWriterPid
-            logWriterPid=
-            rm $logFifo
-        fi
-    fi
-}
-
-
-# Utility function: return the base name of the given path, with the
-# prefix `HASH-' removed, if present.
-stripHash() {
-    strippedName=$(basename $1);
-    if echo "$strippedName" | grep -q '^[a-z0-9]\{32\}-'; then
-        strippedName=$(echo "$strippedName" | cut -c34-)
-    fi
-}
-
-
-unpackFile() {
-    local file=$1
-    local cmd
-
-    header "unpacking source archive $file" 3
-
-    case $file in
-        *.tar)
-            tar xvf $file || fail
-            ;;
-        *.tar.gz | *.tgz | *.tar.Z)
-            gunzip < $file | tar xvf - || fail
-            ;;
-        *.tar.bz2 | *.tbz2)
-            bunzip2 < $file | tar xvf - || fail
-            ;;
-        *.zip)
-            unzip $file || fail
-            ;;
-        *)
-            if test -d "$file"; then
-                stripHash $file
-                cp -prvd $file $strippedName || fail
-            else
-                if test -n "$findUnpacker"; then
-                    $findUnpacker $1;
-                fi
-                if test -z "$unpackCmd"; then
-                    echo "source archive $file has unknown type"
-                    exit 1
-                fi
-                eval "$unpackCmd" || fail
-            fi
-            ;;
-    esac
-
-    stopNest
-}
-
-
-unpackW() {
-    if test -n "$unpackPhase"; then
-        eval "$unpackPhase"
-        return
-    fi
-
-    if test -z "$srcs"; then
-        if test -z "$src"; then
-            echo 'variable $src or $srcs should point to the source'
-            exit 1
-        fi
-        srcs="$src"
-    fi
-
-    # To determine the source directory created by unpacking the
-    # source archives, we record the contents of the current
-    # directory, then look below which directory got added.  Yeah,
-    # it's rather hacky.
-    local dirsBefore=""
-    for i in *; do
-        if test -d "$i"; then
-            dirsBefore="$dirsBefore $i "
-        fi
-    done
-
-    # Unpack all source archives.
-    for i in $srcs; do
-        unpackFile $i
-    done
-
-    # Find the source directory.
-    if test -n "$setSourceRoot"; then
-        eval "$setSourceRoot"
-    else
-        sourceRoot=
-        for i in *; do
-            if test -d "$i"; then
-                case $dirsBefore in
-                    *\ $i\ *)
-                        ;;
-                    *)
-                        if test -n "$sourceRoot"; then
-                            echo "unpacker produced multiple directories"
-                            exit 1
-                        fi
-                        sourceRoot=$i
-                        ;;
-                esac
-            fi
-        done
-    fi
-
-    if test -z "$sourceRoot"; then
-        echo "unpacker appears to have produced no directories"
-        exit 1
-    fi
-
-    echo "source root is $sourceRoot"
-
-    # By default, add write permission to the sources.  This is often
-    # necessary when sources have been copied from other store
-    # locations.
-    if test "dontMakeSourcesWritable" != 1; then
-        chmod -R +w $sourceRoot
-    fi
-
-    eval "$postUnpack"
-}
-
-
-unpackPhase() {
-    sourceRoot=. # don't change to user dir homeless shelter if custom unpackSource does'nt set sourceRoot
-    header "unpacking sources"
-    startLog "unpack"
-    unpackW
-    stopLog
-    stopNest
-    cd $sourceRoot
-}
-
-
-patchW() {
-    if test -n "$patchPhase"; then
-        eval "$patchPhase"
-        return
-    fi
-
-    if test -z "$patchFlags"; then
-        patchFlags="-p1"
-    fi
-
-    for i in $patches; do
-        header "applying patch $i" 3
-        local uncompress=cat
-        case $i in
-            *.gz)
-                uncompress=gunzip
-                ;;
-            *.bz2)
-                uncompress=bunzip2
-                ;;
-        esac
-        $uncompress < $i | patch $patchFlags || fail
-        stopNest
-    done
-}
-
-
-patchPhase() {
-    if test -z "$patchPhase" -a -z "$patches"; then return; fi
-    header "patching sources"
-    startLog "patch"
-    patchW
-    stopLog
-    stopNest
-}
-
-
-fixLibtool() {
-    sed 's^eval sys_lib_.*search_path=.*^^' < $1 > $1.tmp
-    mv $1.tmp $1
-}
-
-
-configureW() {
-    if test -n "$configurePhase"; then
-        eval "$configurePhase"
-        return
-    fi
-
-    eval "$preConfigure"
-
-    if test -z "$configureScript"; then
-        configureScript=./configure
-        if ! test -x $configureScript; then
-            echo "no configure script, doing nothing"
-            return
-        fi
-    fi
-
-    if test -z "$dontFixLibtool"; then
-        for i in $(find . -name "ltmain.sh"); do
-            echo "fixing libtool script $i"
-            fixLibtool $i
-        done
-    fi
-
-    if test -z "$dontAddPrefix"; then
-        configureFlags="${prefixKey:---prefix=}$prefix $configureFlags"
-    fi
-
-    echo "configure flags: $configureFlags ${configureFlagsArray[@]}"
-    $configureScript $configureFlags"${configureFlagsArray[@]}" || fail
-
-    eval "$postConfigure"
-}
-
-
-configurePhase() {
-    header "configuring"
-    startLog "configure"
-    configureW
-    stopLog
-    stopNest
-}
-
-
-buildW() {
-    if test -n "$buildPhase"; then
-        eval "$buildPhase"
-        return
-    fi
-
-    eval "$preBuild"
-
-    echo "make flags: $makeFlags ${makeFlagsArray[@]} $buildFlags ${buildFlagsArray[@]}"
-    make \
-        $makeFlags "${makeFlagsArray[@]}" \
-        $buildFlags "${buildFlagsArray[@]}" || fail
-
-    eval "$postBuild"
-}
-
-
-buildPhase() {
-    if test "$dontBuild" = 1; then
-        return
-    fi
-    header "building"
-    startLog "build"
-    buildW
-    stopLog
-    stopNest
-}
-
-
-checkW() {
-    if test -n "$checkPhase"; then
-        eval "$checkPhase"
-        return
-    fi
-
-    if test -z "$checkTarget"; then
-        checkTarget="check"
-    fi
-
-    echo "check flags: $makeFlags ${makeFlagsArray[@]} $checkFlags ${checkFlagsArray[@]}"
-    make \
-        $makeFlags "${makeFlagsArray[@]}" \
-        $checkFlags "${checkFlagsArray[@]}" $checkTarget || fail
-}
-
-
-checkPhase() {
-    if test "$doCheck" != 1; then
-        return
-    fi
-    header "checking"
-    startLog "check"
-    checkW
-    stopLog
-    stopNest
-}
-
-
-patchELF() {
-    # Patch all ELF executables and shared libraries.
-    header "patching ELF executables and libraries"
-    find "$prefix" \( \
-        \( -type f -a -name "*.so*" \) -o \
-        \( -type f -a -perm +0100 \) \
-        \) -print -exec patchelf --shrink-rpath {} \;
-    stopNest
-}
-
-
-installW() {
-    if test -n "$installPhase"; then
-        eval "$installPhase"
-        return
-    fi
-
-    eval "$preInstall"
-
-    ensureDir "$prefix"
-
-    if test -z "$installCommand"; then
-        if test -z "$installTargets"; then
-            installTargets=install
-        fi
-        echo "install flags: $installTargets $makeFlags ${makeFlagsArray[@]} $installFlags ${installFlagsArray[@]}"
-        make $installTargets \
-            $makeFlags "${makeFlagsArray[@]}" \
-            $installFlags "${installFlagsArray[@]}" || fail
-    else
-        eval "$installCommand"
-    fi
-
-    eval "$postInstall"
-}
-
-
-installPhase() {
-    if test "$dontInstall" = 1; then
-        return
-    fi
-    header "installing"
-    startLog "install"
-    installW
-    stopLog
-    stopNest
-}
-
-
-# The fixup phase performs generic, package-independent, Nix-related
-# stuff, like running patchelf and setting the
-# propagated-build-inputs.  It should rarely be overriden.
-fixupW() {
-    if test -n "$fixupPhase"; then
-        eval "$fixupPhase"
-        return
-    fi
-
-    eval "$preFixup"
-
- 	forceShare=${forceShare:=man doc info}
- 	if test -n "$forceShare"; then
- 		for d in $forceShare; do
- 			if test -d "$prefix/$d"; then
- 				if test -d "$prefix/share/$d"; then
- 					echo "Both $d/ and share/$d/ exists!"
- 				else
-					echo Fixing location of $d/ subdirectory
- 					ensureDir $prefix/share
-					if test -w $prefix/share; then
-	 					mv -v $prefix/$d $prefix/share
- 						ln -sv share/$d $prefix
-					fi
- 				fi
-			else
-				echo "No $d/ subdirectory, skipping."
- 			fi
- 		done;
- 	fi
-
-
-# TODO : strip _only_ ELF executables, and return || fail here...
-    if test -z "$dontStrip"; then
-		echo "Stripping debuging symbols from files in"
-		stripDirs "${stripDebugList:-lib}" -S
-		echo "Stripping all symbols from files in"
-		stripDirs "${stripAllList:-bin sbin}" -s
-    fi
-
-    if test "$havePatchELF" = 1 -a -z "$dontPatchELF"; then
-        patchELF "$prefix"
-    fi
-
-    if test -n "$propagatedBuildInputs"; then
-        ensureDir "$out/nix-support"
-        echo "$propagatedBuildInputs" > "$out/nix-support/propagated-build-inputs"
-    fi
-
-	if test -n "$setupHook"; then
-		ensureDir "$out/nix-support"
-		substituteAll "$setupHook" "$out/nix-support/setup-hook"
-	fi
-
-    eval "$postFixup"
-}
-
-
-fixupPhase() {
-    if test "$dontFixup" = 1; then
-        return
-    fi
-    header "post-installation fixup"
-    startLog "fixup"
-    fixupW
-    stopLog
-    stopNest
-}
-
-
-distW() {
-    if test -n "$distPhase"; then
-        eval "$distPhase"
-        return
-    fi
-
-    eval "$preDist"
-
-    if test -z "$distTarget"; then
-        distTarget="dist"
-    fi
-
-    echo "dist flags: $distFlags ${distFlagsArray[@]}"
-    make $distFlags "${distFlagsArray[@]}" $distTarget || fail
-
-    if test "$dontCopyDist" != 1; then
-        ensureDir "$out/tarballs"
-
-        if test -z "$tarballs"; then
-            tarballs="*.tar.gz"
-        fi
-
-        # Note: don't quote $tarballs, since we explicitly permit
-        # wildcards in there.
-        cp -pvd $tarballs $out/tarballs
-    fi
-
-    eval "$postDist"
-}
-
-
-distPhase() {
-    if test "$doDist" != 1; then
-        return
-    fi
-    header "creating distribution"
-    startLog "dist"
-    distW
-    stopLog
-    stopNest
-}
-
-
-genericBuild() {
-    header "building $out"
-
-    if test -n "$buildCommand"; then
-        eval "$buildCommand"
-        return
-    fi
-
-    if test -z "$phases"; then
-        phases="unpackPhase patchPhase configurePhase buildPhase checkPhase \
-            installPhase fixupPhase distPhase";
-    fi
-
-    for i in $phases; do
-        dumpVars
-        eval "$i"
-    done
-
-    stopNest
-}
-
-
-dumpVars
diff --git a/pkgs/stdenv/generic/setup-new.sh b/pkgs/stdenv/generic/setup-new.sh
deleted file mode 100644
index 68812e42871..00000000000
--- a/pkgs/stdenv/generic/setup-new.sh
+++ /dev/null
@@ -1,830 +0,0 @@
-set -e
-
-test -z $NIX_GCC && NIX_GCC=@gcc@
-
-
-# Set up the initial path.
-PATH=
-for i in $NIX_GCC @initialPath@; do
-    PATH=$PATH${PATH:+:}$i/bin
-done
-
-if test "$NIX_DEBUG" = "1"; then
-    echo "Initial path: $PATH"
-fi
-
-
-# Execute the pre-hook.
-export SHELL=@shell@
-if test -z "$shell"; then
-    export shell=@shell@
-fi
-param1=@param1@
-param2=@param2@
-param3=@param3@
-param4=@param4@
-param5=@param5@
-if test -n "@preHook@"; then
-    source @preHook@
-fi
-
-
-# Check that the pre-hook initialised SHELL.
-if test -z "$SHELL"; then echo "SHELL not set"; exit 1; fi
-
-
-# Hack: run gcc's setup hook.
-envHooks=()
-if test -f $NIX_GCC/nix-support/setup-hook; then
-    source $NIX_GCC/nix-support/setup-hook
-fi
-
-    
-# Ensure that the given directories exists.
-ensureDir() {
-    local dir
-    for dir in "$@"; do
-        if ! test -x "$dir"; then mkdir -p "$dir"; fi
-    done
-}
-
-
-# Called when some build action fails.  If $succeedOnFailure is set,
-# create the file `$out/nix-support/failed' to signal failure, and
-# exit normally.  Otherwise, exit with failure.
-fail() {
-    exitCode=$?
-    if test "$succeedOnFailure" = 1; then
-        ensureDir "$out/nix-support"
-        touch "$out/nix-support/failed"
-        exit 0
-    else
-        exit $?
-    fi
-}
-
-
-# Allow the caller to augment buildInputs (it's not always possible to
-# do this before the call to setup.sh, since the PATH is empty at that
-# point; here we have a basic Unix environment).
-eval "$addInputsHook"
-
-
-# Recursively find all build inputs.
-findInputs()
-{
-    local pkg=$1
-
-    case $pkgs in
-        *\ $pkg\ *)
-            return 0
-            ;;
-    esac
-    
-    pkgs="$pkgs $pkg "
-
-    if test -f $pkg/nix-support/setup-hook; then
-        source $pkg/nix-support/setup-hook
-    fi
-    
-    if test -f $pkg/nix-support/propagated-build-inputs; then
-        for i in $(cat $pkg/nix-support/propagated-build-inputs); do
-            findInputs $i
-        done
-    fi
-}
-
-pkgs=""
-if test -n "$buildinputs"; then
-    buildInputs="$buildinputs" # compatibility
-fi
-for i in $buildInputs $propagatedBuildInputs; do
-    findInputs $i
-done
-
-
-# Set the relevant environment variables to point to the build inputs
-# found above.
-addToEnv()
-{
-    local pkg=$1
-
-    if test "$ignoreFailedInputs" != "1" -a -e $1/nix-support/failed; then
-        echo "failed input $1" >&2
-        fail
-    fi
-
-    if test -d $1/bin; then
-        export _PATH=$_PATH${_PATH:+:}$1/bin
-    fi
-
-    for i in "${envHooks[@]}"; do
-        $i $pkg
-    done
-}
-
-for i in $pkgs; do
-    addToEnv $i
-done
-
-
-# Add the output as an rpath.
-if test "$NIX_NO_SELF_RPATH" != "1"; then
-    export NIX_LDFLAGS="-rpath $out/lib $NIX_LDFLAGS"
-fi
-
-
-# Strip debug information by default.
-if test -z "$NIX_STRIP_DEBUG"; then
-    export NIX_STRIP_DEBUG=1
-    export NIX_CFLAGS_STRIP="-g0 -Wl,--strip-debug"
-fi
-
-
-# Do we know where the store is?  This is required for purity checking.
-if test -z "$NIX_STORE"; then
-    echo "Error: you have an old version of Nix that does not set the" \
-        "NIX_STORE variable.  Please upgrade." >&2
-    exit 1
-fi
-
-
-# We also need to know the root of the build directory for purity checking.
-if test -z "$NIX_BUILD_TOP"; then
-    echo "Error: you have an old version of Nix that does not set the" \
-        "NIX_BUILD_TOP variable.  Please upgrade." >&2
-    exit 1
-fi
-
-
-# Set the TZ (timezone) environment variable, otherwise commands like
-# `date' will complain (e.g., `Tue Mar 9 10:01:47 Local time zone must
-# be set--see zic manual page 2004').
-export TZ=UTC
-
-
-# Set the prefix.  This is generally $out, but it can be overriden,
-# for instance if we just want to perform a test build/install to a
-# temporary location and write a build report to $out.
-if test -z "$prefix"; then
-    prefix="$out";
-fi
-
-if test "$useTempPrefix" = "1"; then
-    prefix="$NIX_BUILD_TOP/tmp_prefix";
-fi
-
-
-# Execute the post-hook.
-if test -n "@postHook@"; then
-    source @postHook@
-fi
-
-PATH=$_PATH${_PATH:+:}$PATH
-if test "$NIX_DEBUG" = "1"; then
-    echo "Final path: $PATH"
-fi
-
-
-######################################################################
-# Textual substitution functions.
-
-
-# Some disgusting hackery to escape replacements in Sed substitutions.
-# We should really have a tool that replaces literal values by other
-# literal values, without any need for escaping.
-escapeSed() {
-    local s="$1"
-    # The `tr' hack is to escape newlines.  Sed handles newlines very
-    # badly, so we just replace newlines with the magic character 0xff
-    # (377 octal).  So don't use that character in replacements :-P
-    echo -n "$1" | tr '\012' '\377' | sed -e 's^\\^\\\\^g' -e 's^\xff^\\n^g' -e 's/\^/\\^/g' -e 's/&/\\&/g'
-}
-
-
-substitute() {
-    local input="$1"
-    local output="$2"
-
-    local -a params=("$@")
-
-    local sedScript=$NIX_BUILD_TOP/.sedargs
-    rm -f $sedScript
-    touch $sedScript
-
-    local n p pattern replacement varName
-    
-    for ((n = 2; n < ${#params[*]}; n += 1)); do
-        p=${params[$n]}
-
-        if test "$p" = "--replace"; then
-            pattern="${params[$((n + 1))]}"
-            replacement="${params[$((n + 2))]}"
-            n=$((n + 2))
-        fi
-
-        if test "$p" = "--subst-var"; then
-            varName="${params[$((n + 1))]}"
-            pattern="@$varName@"
-            replacement="${!varName}"
-            n=$((n + 1))
-        fi
-
-        if test "$p" = "--subst-var-by"; then
-            pattern="@${params[$((n + 1))]}@"
-            replacement="${params[$((n + 2))]}"
-            n=$((n + 2))
-        fi
-
-        replacement="$(escapeSed "$replacement")"
-
-        echo "s^$pattern^$replacement^g" >> $sedScript
-    done
-
-    sed -f $sedScript < "$input" > "$output".tmp
-    if test -x "$output"; then
-        chmod +x "$output".tmp
-    fi
-    mv -f "$output".tmp "$output"
-}
-
-
-substituteInPlace() {
-    local fileName="$1"
-    shift
-    substitute "$fileName" "$fileName" "$@"
-}
-
-
-substituteAll() {
-    local input="$1"
-    local output="$2"
-    
-    # Select all environment variables that start with a lowercase character.
-    for envVar in $(env | sed "s/^[^a-z].*//" | sed "s/^\([^=]*\)=.*/\1/"); do
-        if test "$NIX_DEBUG" = "1"; then
-            echo "$envVar -> ${!envVar}"
-        fi
-        args="$args --subst-var $envVar"
-    done
-
-    substitute "$input" "$output" $args
-}  
-
-
-######################################################################
-# What follows is the generic builder.
-
-
-nestingLevel=0
-
-startNest() {
-    nestingLevel=$(($nestingLevel + 1))
-    echo -en "\e[$1p"
-}
-
-stopNest() {
-    nestingLevel=$(($nestingLevel - 1))
-    echo -en "\e[q"
-}
-
-header() {
-    startNest "$2"
-    echo "$1"
-}
-
-# Make sure that even when we exit abnormally, the original nesting
-# level is properly restored.
-closeNest() {
-    while test $nestingLevel -gt 0; do
-        stopNest
-    done
-}
-
-trap "closeNest" EXIT
-
-
-# This function is useful for debugging broken Nix builds.  It dumps
-# all environment variables to a file `env-vars' in the build
-# directory.  If the build fails and the `-K' option is used, you can
-# then go to the build directory and source in `env-vars' to reproduce
-# the environment used for building.
-dumpVars() {
-    if test "$noDumpEnvVars" != "1"; then
-        export > $NIX_BUILD_TOP/env-vars
-    fi
-}
-
-
-# Redirect stdout/stderr to a named pipe connected to a `tee' process
-# that writes the specified file (and also to our original stdout).
-# The original stdout is saved in descriptor 3.
-startLog() {
-    local logFile=${logNr}_$1
-    logNr=$((logNr + 1))
-    if test "$logPhases" = 1; then
-        ensureDir $logDir
-
-        exec 3>&1
-
-        if test "$dontLogThroughTee" != 1; then
-            # This required named pipes (fifos).
-            logFifo=$NIX_BUILD_TOP/log_fifo
-            test -p $logFifo || mkfifo $logFifo
-            startLogWrite "$logDir/$logFile" "$logFifo"
-            exec > $logFifo 2>&1
-        else
-            exec > $logDir/$logFile 2>&1
-        fi
-    fi
-}
-
-# Factored into a separate function so that it can be overriden.
-startLogWrite() {
-    tee "$1" < "$2" &
-    logWriterPid=$!
-}
-
-
-if test -z "$logDir"; then
-    logDir=$out/log
-fi
-
-logNr=0
-
-# Restore the original stdout/stderr.
-stopLog() {
-    if test "$logPhases" = 1; then
-        exec >&3 2>&1
-
-        # Wait until the tee process has died.  Otherwise output from
-        # different phases may be mixed up.
-        if test -n "$logWriterPid"; then
-            wait $logWriterPid
-            logWriterPid=
-            rm $logFifo
-        fi
-    fi
-}
-
-
-# Utility function: return the base name of the given path, with the
-# prefix `HASH-' removed, if present.
-stripHash() {
-    strippedName=$(basename $1);
-    if echo "$strippedName" | grep -q '^[a-z0-9]\{32\}-'; then
-        strippedName=$(echo "$strippedName" | cut -c34-)
-    fi
-}
-
-
-unpackFile() {
-    local file=$1
-    local cmd
-
-    header "unpacking source archive $file" 3
-
-    case $file in
-        *.tar)
-            tar xvf $file || fail
-            ;;
-        *.tar.gz | *.tgz | *.tar.Z)
-            gunzip < $file | tar xvf - || fail
-            ;;
-        *.tar.bz2 | *.tbz2)
-            bunzip2 < $file | tar xvf - || fail
-            ;;
-        *.zip)
-            unzip $file || fail
-            ;;
-        *)
-            if test -d "$file"; then
-                stripHash $file
-                cp -prvd $file $strippedName || fail
-            else
-                if test -n "$findUnpacker"; then
-                    $findUnpacker $1;
-                fi
-                if test -z "$unpackCmd"; then
-                    echo "source archive $file has unknown type"
-                    exit 1
-                fi
-                eval "$unpackCmd" || fail
-            fi
-            ;;
-    esac
-
-    stopNest
-}
-
-
-unpackW() {
-    if test -n "$unpackPhase"; then
-        eval "$unpackPhase"
-        return
-    fi
-
-    if test -z "$srcs"; then
-        if test -z "$src"; then
-            echo 'variable $src or $srcs should point to the source'
-            exit 1
-        fi
-        srcs="$src"
-    fi
-
-    # To determine the source directory created by unpacking the
-    # source archives, we record the contents of the current
-    # directory, then look below which directory got added.  Yeah,
-    # it's rather hacky.
-    local dirsBefore=""
-    for i in *; do
-        if test -d "$i"; then
-            dirsBefore="$dirsBefore $i "
-        fi
-    done
-
-    # Unpack all source archives.
-    for i in $srcs; do
-        unpackFile $i
-    done
-
-    # Find the source directory.
-    if test -n "$setSourceRoot"; then
-        eval "$setSourceRoot"
-    else
-        sourceRoot=
-        for i in *; do
-            if test -d "$i"; then
-                case $dirsBefore in
-                    *\ $i\ *)
-                        ;;
-                    *)
-                        if test -n "$sourceRoot"; then
-                            echo "unpacker produced multiple directories"
-                            exit 1
-                        fi
-                        sourceRoot=$i
-                        ;;
-                esac
-            fi
-        done
-    fi
-
-    if test -z "$sourceRoot"; then
-        echo "unpacker appears to have produced no directories"
-        exit 1
-    fi
-
-    echo "source root is $sourceRoot"
-
-    # By default, add write permission to the sources.  This is often
-    # necessary when sources have been copied from other store
-    # locations.
-    if test "dontMakeSourcesWritable" != 1; then
-        chmod -R +w $sourceRoot
-    fi
-
-    eval "$postUnpack"
-}
-
-
-unpackPhase() {
-    header "unpacking sources"
-    startLog "unpack"
-    unpackW
-    stopLog
-    stopNest
-}
-
-
-patchW() {
-    if test -n "$patchPhase"; then
-        eval "$patchPhase"
-        return
-    fi
-
-    if test -z "$patchFlags"; then
-        patchFlags="-p1"
-    fi
-
-    for i in $patches; do
-        header "applying patch $i" 3
-        local uncompress=cat
-        case $i in
-            *.gz)
-                uncompress=gunzip
-                ;;
-            *.bz2)
-                uncompress=bunzip2
-                ;;
-        esac
-        $uncompress < $i | patch $patchFlags || fail
-        stopNest
-    done
-}
-
-
-patchPhase() {
-    if test -z "$patchPhase" -a -z "$patches"; then return; fi
-    header "patching sources"
-    startLog "patch"
-    patchW
-    stopLog
-    stopNest
-}
-
-
-fixLibtool() {
-    sed 's^eval sys_lib_.*search_path=.*^^' < $1 > $1.tmp
-    mv $1.tmp $1
-}
-
-
-configureW() {
-    if test -n "$configurePhase"; then
-        eval "$configurePhase"
-        return
-    fi
-
-    eval "$preConfigure"
-
-    if test -z "$configureScript"; then
-        configureScript=./configure
-        if ! test -x $configureScript; then
-            echo "no configure script, doing nothing"
-            return
-        fi
-    fi
-
-    if test -z "$dontFixLibtool"; then
-        for i in $(find . -name "ltmain.sh"); do
-            echo "fixing libtool script $i"
-            fixLibtool $i
-        done
-    fi
-
-    if test -z "$dontAddPrefix"; then
-        configureFlags="--prefix=$prefix $configureFlags"
-    fi
-
-    echo "configure flags: $configureFlags ${configureFlagsArray[@]}"
-    $configureScript $configureFlags"${configureFlagsArray[@]}" || fail
-
-    eval "$postConfigure"
-}
-
-
-configurePhase() {
-    header "configuring"
-    startLog "configure"
-    configureW
-    stopLog
-    stopNest
-}
-
-
-buildW() {
-    if test -n "$buildPhase"; then
-        eval "$buildPhase"
-        return
-    fi
-
-    eval "$preBuild"
-    
-    echo "make flags: $makeFlags ${makeFlagsArray[@]} $buildFlags ${buildFlagsArray[@]}"
-    make \
-        $makeFlags "${makeFlagsArray[@]}" \
-        $buildFlags "${buildFlagsArray[@]}" || fail
-
-    eval "$postBuild"
-}
-
-
-buildPhase() {
-    if test "$dontBuild" = 1; then
-        return
-    fi
-    header "building"
-    startLog "build"
-    buildW
-    stopLog
-    stopNest
-}
-
-
-checkW() {
-    if test -n "$checkPhase"; then
-        eval "$checkPhase"
-        return
-    fi
-
-    if test -z "$checkTarget"; then
-        checkTarget="check"
-    fi
-
-    echo "check flags: $makeFlags ${makeFlagsArray[@]} $checkFlags ${checkFlagsArray[@]}"
-    make \
-        $makeFlags "${makeFlagsArray[@]}" \
-        $checkFlags "${checkFlagsArray[@]}" $checkTarget || fail
-}
-
-
-checkPhase() {
-    if test "$doCheck" != 1; then
-        return
-    fi
-    header "checking"
-    startLog "check"
-    checkW
-    stopLog
-    stopNest
-}
-
-
-patchELF() {
-    # Patch all ELF executables and shared libraries.
-    header "patching ELF executables and libraries"
-    find "$prefix" \( \
-        \( -type f -a -name "*.so*" \) -o \
-        \( -type f -a -perm +0100 \) \
-        \) -print -exec patchelf --shrink-rpath {} \;
-    stopNest
-}
-
-
-installW() {
-    if test -n "$installPhase"; then
-        eval "$installPhase"
-        return
-    fi
-
-    eval "$preInstall"
-
-    ensureDir "$prefix"
-
-    if test -z "$installCommand"; then
-        if test -z "$installTargets"; then
-            installTargets=install
-        fi
-        echo "install flags: $installTargets $makeFlags ${makeFlagsArray[@]} $installFlags ${installFlagsArray[@]}"
-        make $installTargets \
-            $makeFlags "${makeFlagsArray[@]}" \
-            $installFlags "${installFlagsArray[@]}" || fail
-    else
-        eval "$installCommand"
-    fi
-
-    eval "$postInstall"
-}
-
-
-installPhase() {
-    if test "$dontInstall" = 1; then
-        return
-    fi
-    header "installing"
-    startLog "install"
-    installW
-    stopLog
-    stopNest
-}
-
-
-# The fixup phase performs generic, package-independent, Nix-related
-# stuff, like running patchelf and setting the
-# propagated-build-inputs.  It should rarely be overriden.
-fixupW() {
-    if test -n "$fixupPhase"; then
-        eval "$fixupPhase"
-        return
-    fi
-
-    eval "$preFixup"
-
-# TODO : strip _only_ ELF executables, and return || fail here...
-    if test -z "$dontStrip"; then
-		test -d "$prefix/lib" && stripDebug="$prefix/lib"
-
-		if test -n "$stripDebug"; then
-			find "$stripDebug" -type f -print0 |
-			xargs -0 strip --strip-debug --verbose || true
-		fi
-
-		test -d "$prefix/bin" && stripAll="$prefix/bin"
-		test -d "$prefix/sbin" && stripAll="${stripAll} $prefix/sbin"
-		if test -n "$stripAll"; then
-			find "$prefix/bin" "$prefix/sbin" -type f -print0 |
-			xargs -0 strip --strip-all --verbose || true
-		fi
-    fi
-
-	if test -z "$dontFixupShare"; then
-		for dir in doc info man; do
-			if test -d "$prefix/$dir"; then
-				if test -d "$prefix/share/$dir"; then
-					echo Both "$prefix/$dir" and "$prefix/share/$dir" exists!
-					fail
-				else
-					echo Fixing location of $dir/ subdirectory
-					ensureDir "$prefix/share"
-					mv -v "$prefix/$dir" "$prefix/share"
-					ln -sv "share/$dir" "$prefix"
-				fi
-			fi
-		done
-	fi
-
-    if test "$havePatchELF" = 1 -a -z "$dontPatchELF"; then
-        patchELF "$prefix"
-    fi
-
-    if test -n "$propagatedBuildInputs"; then
-        ensureDir "$out/nix-support"
-        echo "$propagatedBuildInputs" > "$out/nix-support/propagated-build-inputs"
-    fi
-
-    eval "$postFixup"
-}
-
-
-fixupPhase() {
-    if test "$dontFixup" = 1; then
-        return
-    fi
-    header "post-installation fixup"
-    startLog "fixup"
-    fixupW
-    stopLog
-    stopNest
-}
-
-
-distW() {
-    if test -n "$distPhase"; then
-        eval "$distPhase"
-        return
-    fi
-
-    eval "$preDist"
-    
-    if test -z "$distTarget"; then
-        distTarget="dist"
-    fi
-
-    echo "dist flags: $distFlags ${distFlagsArray[@]}"
-    make $distFlags "${distFlagsArray[@]}" $distTarget || fail
-
-    if test "$dontCopyDist" != 1; then
-        ensureDir "$out/tarballs"
-
-        if test -z "$tarballs"; then
-            tarballs="*.tar.gz"
-        fi
-
-        # Note: don't quote $tarballs, since we explicitly permit
-        # wildcards in there.
-        cp -pvd $tarballs $out/tarballs
-    fi
-
-    eval "$postDist"
-}
-
-
-distPhase() {
-    if test "$doDist" != 1; then
-        return
-    fi
-    header "creating distribution"
-    startLog "dist"
-    distW
-    stopLog
-    stopNest
-}
-
-
-genericBuild() {
-    header "building $out"
-
-    if test -n "$buildCommand"; then
-        eval "$buildCommand"
-        return
-    fi
-
-    unpackPhase
-    cd $sourceRoot
-
-    if test -z "$phases"; then
-        phases="patchPhase configurePhase buildPhase checkPhase \
-            installPhase fixupPhase distPhase";
-    fi
-
-    for i in $phases; do
-        dumpVars
-        eval "$i"
-    done
-    
-    stopNest
-}
-
-
-dumpVars
diff --git a/pkgs/stdenv/generic/setup-sh-defs.nix b/pkgs/stdenv/generic/setup-sh-defs.nix
deleted file mode 100644
index 9f080307178..00000000000
--- a/pkgs/stdenv/generic/setup-sh-defs.nix
+++ /dev/null
@@ -1,902 +0,0 @@
-with (import ../../lib/strings-with-deps.nix (import ../../lib/default-unstable.nix)); 
-
-rec {
-	setStrictMode = noDepEntry "set -e;";
-	setNixGcc = noDepEntry "test -z \$NIX_GCC && NIX_GCC=@gcc@;";
-
-	setPathDelimiter = noDepEntry "
-if [ -z ${system##*cygwin*} ]; then
-  PATH_DELIMITER=;
-else
-  PATH_DELIMITER=;
-fi
-" ;
-
-	
-	initPath = noDepEntry "# Set up the initial path.
-PATH=
-for i in \$NIX_GCC @initialPath@; do
-    PATH=\$PATH\${PATH:+:}\$i/bin
-done
-
-if test \"\$NIX_DEBUG\" = \"1\"; then
-    echo \"Initial path: \$PATH\"
-fi
-";
-
-	execPreHook = FullDepEntry "# Execute the pre-hook.
-export SHELL=@shell@
-if test -z \"\$shell\"; then
-    export shell=@shell@
-fi
-param1=@param1@
-param2=@param2@
-param3=@param3@
-param4=@param4@
-param5=@param5@
-if test -n \"@preHook@\"; then
-    source @preHook@
-fi
-" [];
-
-	checkShellEnv = FullDepEntry "# Check that the pre-hook initialised SHELL.
-if test -z \"\$SHELL\"; then echo \"SHELL not set\"; exit 1; fi
-" [];
-
-	gccSetupHook = FullDepEntry "# Hack: run gcc's setup hook.
-envHooks=()
-if test -f \$NIX_GCC/nix-support/setup-hook; then
-    source \$NIX_GCC/nix-support/setup-hook
-fi
-" [setNixGcc];
-
-    
-	defEnsureDir = FullDepEntry "# Ensure that the given directories exists.
-ensureDir() {
-    local dir
-    for dir in \"\$@\"; do
-        if ! test -x \"\$dir\"; then mkdir -p \"\$dir\"; fi
-    done
-}
-" [];
-
-	defInstallBin = FullDepEntry "
-
-installBin() {
-  ensureDir $out/bin
-  cp "$@" $out/bin
-}
-
-" [];
-
-	defAssertEnvExists = FullDepEntry "
-assertEnvExists(){
-  if test -z "${!1}"; then
-      msg=${2:-error: assertion failed: env var $1 is required}
-      echo $msg >&2; exit 1
-  fi
-}
-" [];
-
-	defFail = FullDepEntry "# Called when some build action fails.  If \$succeedOnFailure is set,
-# create the file `\$out/nix-support/failed' to signal failure, and
-# exit normally.  Otherwise, exit with failure.
-fail() {
-    exitCode=\$?
-    if test \"\$succeedOnFailure\" = 1; then
-        ensureDir \"\$out/nix-support\"
-        touch \"\$out/nix-support/failed\"
-        exit 0
-    else
-        exit \$?
-    fi
-}
-" [];
-
-	runAddInputsHook = FullDepEntry "# Allow the caller to augment buildInputs (it's not always possible to
-# do this before the call to setup.sh, since the PATH is empty at that
-# point; here we have a basic Unix environment).
-eval \"\$addInputsHook\"
-" [defFail];
-
-	defFindInputs = FullDepEntry "# Recursively find all build inputs.
-findInputs()
-{
-    local pkg=\$1
-
-    case \$pkgs in
-        *\ \$pkg\ *)
-            return 0
-            ;;
-    esac
-    
-    pkgs=\"\$pkgs \$pkg \"
-
-    if test -f \$pkg/nix-support/setup-hook; then
-        source \$pkg/nix-support/setup-hook
-    fi
-    
-    if test -f \$pkg/nix-support/propagated-build-inputs; then
-        for i in \$(cat \$pkg/nix-support/propagated-build-inputs); do
-            findInputs \$i
-        done
-    fi
-}
-" [];
-
-	getInputs = FullDepEntry "pkgs=\"\"
-if test -n \"\$buildinputs\"; then
-    buildInputs=\"\$buildinputs\" # compatibility
-fi
-for i in \$buildInputs \$propagatedBuildInputs; do
-    findInputs \$i
-done
-" [defFindInputs];
-
-	defAddToEnv = FullDepEntry "# Set the relevant environment variables to point to the build inputs
-# found above.
-addToEnv()
-{
-    local pkg=\$1
-
-    if test \"\$ignoreFailedInputs\" != \"1\" -a -e \$1/nix-support/failed; then
-        echo \"failed input \$1\" >&2
-        fail
-    fi
-
-    if test -d \$1/bin; then
-        export _PATH=\$_PATH\${_PATH:+:}\$1/bin
-    fi
-
-    for i in \"\${envHooks[@]}\"; do
-        \$i \$pkg
-    done
-}
-" [defFail];
-
-	preparePackageEnv = FullDepEntry "for i in \$pkgs; do
-    addToEnv \$i
-done
-" [getInputs defAddToEnv];
-
-	putOutInRpath = FullDepEntry "# Add the output as an rpath.
-if test \"\$NIX_NO_SELF_RPATH\" != \"1\"; then
-    export NIX_LDFLAGS=\"-rpath \$out/lib \$NIX_LDFLAGS\"
-fi
-" [initPath];
-
-	setupStripping = FullDepEntry "# Strip debug information by default.
-if test -z \"\$NIX_STRIP_DEBUG\"; then
-    export NIX_STRIP_DEBUG=1
-    export NIX_CFLAGS_STRIP=\"-g0 -Wl,--strip-debug\"
-fi
-" [initPath];
-
-	checkNixEnv = FullDepEntry "# Do we know where the store is?  This is required for purity checking.
-if test -z \"\$NIX_STORE\"; then
-    echo \"Error: you have an old version of Nix that does not set the\" \
-        \"NIX_STORE variable.  Please upgrade.\" >&2
-    exit 1
-fi
-
-
-# We also need to know the root of the build directory for purity checking.
-if test -z \"\$NIX_BUILD_TOP\"; then
-    echo \"Error: you have an old version of Nix that does not set the\" \
-        \"NIX_BUILD_TOP variable.  Please upgrade.\" >&2
-    exit 1
-fi
-" [initPath];
-
-	setTZ = noDepEntry "# Set the TZ (timezone) environment variable, otherwise commands like
-# `date' will complain (e.g., `Tue Mar 9 10:01:47 Local time zone must
-# be set--see zic manual page 2004').
-export TZ=UTC
-" ;
-
-	setPrefix = FullDepEntry "# Set the prefix.  This is generally \$out, but it can be overriden,
-# for instance if we just want to perform a test build/install to a
-# temporary location and write a build report to \$out.
-if test -z \"\$prefix\"; then
-    prefix=\"\$out\";
-fi
-
-if test \"\$useTempPrefix\" = \"1\"; then
-    prefix=\"\$NIX_BUILD_TOP/tmp_prefix\";
-fi
-" [checkNixEnv];
-
-	runPostHook = FullDepEntry "# Execute the post-hook.
-if test -n \"@postHook@\"; then
-    source @postHook@
-fi
-" [setTZ setPrefix execPreHook gccSetupHook preparePackageEnv];
-
-	finalSetPath = FullDepEntry "PATH=\$_PATH\${_PATH:+:}\$PATH
-if test \"\$NIX_DEBUG\" = \"1\"; then
-    echo \"Final path: \$PATH\"
-fi
-" [runPostHook];
-
-	defSubstitute = FullDepEntry "######################################################################
-# Textual substitution functions.
-
-
-# Some disgusting hackery to escape replacements in Sed substitutions.
-# We should really have a tool that replaces literal values by other
-# literal values, without any need for escaping.
-escapeSed() {
-    local s=\"\$1\"
-    # The `tr' hack is to escape newlines.  Sed handles newlines very
-    # badly, so we just replace newlines with the magic character 0xff
-    # (377 octal).  So don't use that character in replacements :-P
-    echo -n \"\$1\" | tr '\012' '\377' | sed -e 's^\\^\\\\^g' -e 's^\xff^\\n^g' -e 's/\^/\\^/g' -e 's/&/\\&/g'
-}
-
-
-substitute() {
-    local input=\"\$1\"
-    local output=\"\$2\"
-
-    local -a params=(\"\$@\")
-
-    local sedScript=\$NIX_BUILD_TOP/.sedargs
-    rm -f \$sedScript
-    touch \$sedScript
-
-    local n p pattern replacement varName
-    
-    for ((n = 2; n < \${#params[*]}; n += 1)); do
-        p=\${params[\$n]}
-
-        if test \"\$p\" = \"--replace\"; then
-            pattern=\"\${params[\$((n + 1))]}\"
-            replacement=\"\${params[\$((n + 2))]}\"
-            n=\$((n + 2))
-        fi
-
-        if test \"\$p\" = \"--subst-var\"; then
-            varName=\"\${params[\$((n + 1))]}\"
-            pattern=\"@\$varName@\"
-            replacement=\"\${!varName}\"
-            n=\$((n + 1))
-        fi
-
-        if test \"\$p\" = \"--subst-var-by\"; then
-            pattern=\"@\${params[\$((n + 1))]}@\"
-            replacement=\"\${params[\$((n + 2))]}\"
-            n=\$((n + 2))
-        fi
-
-        replacement=\"\$(escapeSed \"\$replacement\")\"
-
-        echo \"s^\$pattern^\$replacement^g\" >> \$sedScript
-    done
-
-    sed -f \$sedScript < \"\$input\" > \"\$output\".tmp
-    if test -x \"\$output\"; then
-        chmod +x \"\$output\".tmp
-    fi
-    mv -f \"\$output\".tmp \"\$output\"
-}
-
-
-substituteInPlace() {
-    local fileName=\"\$1\"
-    shift
-    substitute \"\$fileName\" \"\$fileName\" \"\$@\"
-}
-
-
-substituteAll() {
-    local input=\"\$1\"
-    local output=\"\$2\"
-    
-    # Select all environment variables that start with a lowercase character.
-    for envVar in \$(env | sed \"s/^[^a-z].*//\" | sed \"s/^\([^=]*\)=.*/\1/\"); do
-        if test \"\$NIX_DEBUG\" = \"1\"; then
-            echo \"\$envVar -> \${!envVar}\"
-        fi
-        args=\"\$args --subst-var \$envVar\"
-    done
-
-    substitute \"\$input\" \"\$output\" \$args
-}  
-" [initPath];
-
-	defNest = NoDepEntry "######################################################################
-# What follows is the generic builder.
-
-
-nestingLevel=0
-
-startNest() {
-    nestingLevel=\$((\$nestingLevel + 1))
-    echo -en \"\e[\$1p\"
-}
-
-stopNest() {
-    nestingLevel=\$((\$nestingLevel - 1))
-    echo -en \"\e[q\"
-}
-
-header() {
-    startNest \"\$2\"
-    echo \"\$1\"
-}
-
-# Make sure that even when we exit abnormally, the original nesting
-# level is properly restored.
-closeNest() {
-    while test \$nestingLevel -gt 0; do
-        stopNest
-    done
-}
-
-trap \"closeNest\" EXIT
-" ;
-
-
-	defDumpVars = FullDepEntry "# This function is useful for debugging broken Nix builds.  It dumps
-# all environment variables to a file `env-vars' in the build
-# directory.  If the build fails and the `-K' option is used, you can
-# then go to the build directory and source in `env-vars' to reproduce
-# the environment used for building.
-dumpVars() {
-    if test \"\$noDumpEnvVars\" != \"1\"; then
-        export > \$NIX_BUILD_TOP/env-vars
-    fi
-}
-" [checkNixEnv];
-
-
-	defStartStopLog = FullDepEntry  "# Redirect stdout/stderr to a named pipe connected to a `tee' process
-# that writes the specified file (and also to our original stdout).
-# The original stdout is saved in descriptor 3.
-startLog() {
-    local logFile=\${logNr}_\$1
-    logNr=\$((logNr + 1))
-    if test \"\$logPhases\" = 1; then
-        ensureDir \$logDir
-
-        exec 3>&1
-
-        if test \"\$dontLogThroughTee\" != 1; then
-            # This required named pipes (fifos).
-            logFifo=\$NIX_BUILD_TOP/log_fifo
-            test -p \$logFifo || mkfifo \$logFifo
-            startLogWrite \"\$logDir/\$logFile\" \"\$logFifo\"
-            exec > \$logFifo 2>&1
-        else
-            exec > \$logDir/\$logFile 2>&1
-        fi
-    fi
-}
-
-# Factored into a separate function so that it can be overriden.
-startLogWrite() {
-    tee \"\$1\" < \"\$2\" &
-    logWriterPid=\$!
-}
-
-# Restore the original stdout/stderr.
-stopLog() {
-    if test \"\$logPhases\" = 1; then
-        exec >&3 2>&1
-
-        # Wait until the tee process has died.  Otherwise output from
-        # different phases may be mixed up.
-        if test -n \"\$logWriterPid\"; then
-            wait \$logWriterPid
-            logWriterPid=
-            rm \$logFifo
-        fi
-    fi
-}
-
-
-" [setLogVars checkNixEnv ];
-
-
-	setLogVars = FullDepEntry "if test -z \"\$logDir\"; then
-    logDir=\$out/log
-fi
-
-logNr=0
-" [initPath];
-
-	defStripHash = FullDepEntry "# Utility function: return the base name of the given path, with the
-# prefix `HASH-' removed, if present.
-stripHash() {
-    strippedName=\$(basename \$1);
-    if echo \"\$strippedName\" | grep -q '^[a-z0-9]\{32\}-'; then
-        strippedName=\$(echo \"\$strippedName\" | cut -c34-)
-    fi
-}
-" [initPath];
-
-	defUnpack = FullDepEntry "
-unpackFile() {
-    local file=\$1
-    local cmd
-
-    header \"unpacking source archive \$file\" 3
-
-    case \$file in
-        *.tar)
-            tar xvf \$file || fail
-            ;;
-        *.tar.gz | *.tgz | *.tar.Z)
-            gunzip < \$file | tar xvf - || fail
-            ;;
-        *.tar.bz2 | *.tbz2)
-            bunzip2 < \$file | tar xvf - || fail
-            ;;
-        *.zip)
-            unzip \$file || fail
-            ;;
-        *)
-            if test -d \"\$file\"; then
-                stripHash \$file
-                cp -prvd \$file \$strippedName || fail
-            else
-                if test -n \"\$findUnpacker\"; then
-                    \$findUnpacker \$1;
-                fi
-                if test -z \"\$unpackCmd\"; then
-                    echo \"source archive \$file has unknown type\"
-                    exit 1
-                fi
-                eval \"\$unpackCmd\" || fail
-            fi
-            ;;
-    esac
-
-    stopNest
-}
-" [preparePackageEnv];
-
-	defUnpackW = FullDepEntry "
-unpackW() {
-    if test -n \"\$unpackPhase\"; then
-        eval \"\$unpackPhase\"
-        return
-    fi
-
-    if test -z \"\$srcs\"; then
-        if test -z \"\$src\"; then
-            echo 'variable \$src or \$srcs should point to the source'
-            exit 1
-        fi
-        srcs=\"\$src\"
-    fi
-
-    # To determine the source directory created by unpacking the
-    # source archives, we record the contents of the current
-    # directory, then look below which directory got added.  Yeah,
-    # it's rather hacky.
-    local dirsBefore=\"\"
-    for i in *; do
-        if test -d \"\$i\"; then
-            dirsBefore=\"\$dirsBefore \$i \"
-        fi
-    done
-
-    # Unpack all source archives.
-    for i in \$srcs; do
-        unpackFile \$i
-    done
-
-    # Find the source directory.
-    if test -n \"\$setSourceRoot\"; then
-        eval \"\$setSourceRoot\"
-    else
-        sourceRoot=
-        for i in *; do
-            if test -d \"\$i\"; then
-                case \$dirsBefore in
-                    *\ \$i\ *)
-                        ;;
-                    *)
-                        if test -n \"\$sourceRoot\"; then
-                            echo \"unpacker produced multiple directories\"
-                            exit 1
-                        fi
-                        sourceRoot=\$i
-                        ;;
-                esac
-            fi
-        done
-    fi
-
-    if test -z \"\$sourceRoot\"; then
-        echo \"unpacker appears to have produced no directories\"
-        exit 1
-    fi
-
-    echo \"source root is \$sourceRoot\"
-
-    # By default, add write permission to the sources.  This is often
-    # necessary when sources have been copied from other store
-    # locations.
-    if test \"dontMakeSourcesWritable\" != 1; then
-        chmod -R +w \$sourceRoot
-    fi
-
-    eval \"\$postUnpack\"
-}
-" [defUnpack];
-
-
-
-defUnpackPhase = FullDepEntry "
-unpackPhase() {
-    sourceRoot=. # don't change to user dir homeless shelter if custom unpackSource does'nt set sourceRoot
-    header \"unpacking sources\"
-    startLog \"unpack\"
-    unpackW
-    stopLog
-    stopNest
-    cd \$sourceRoot
-}
-" [unpackW];
-
-
-	defPatchW = FullDepEntry "
-patchW() {
-    if test -n \"\$patchPhase\"; then
-        eval \"\$patchPhase\"
-        return
-    fi
-
-    if test -z \"\$patchFlags\"; then
-        patchFlags=\"-p1\"
-    fi
-
-    for i in \$patches; do
-        header \"applying patch \$i\" 3
-        local uncompress=cat
-        case \$i in
-            *.gz)
-                uncompress=gunzip
-                ;;
-            *.bz2)
-                uncompress=bunzip2
-                ;;
-        esac
-        \$uncompress < \$i | patch \$patchFlags || fail
-        stopNest
-    done
-}
-" [getInputs]
-
-	defPatchPhase = FullDepEntry "
-patchPhase() {
-    if test -z \"\$patchPhase\" -a -z \"\$patches\"; then return; fi
-    header \"patching sources\"
-    startLog \"patch\"
-    patchW
-    stopLog
-    stopNest
-}
-" [defPatchW];
-
-	defFixLibTool = FullDepEntry "fixLibtool() {
-    sed 's^eval sys_lib_.*search_path=.*^^' < \$1 > \$1.tmp
-    mv \$1.tmp \$1
-}
-" [initPath];
-
-	defConfigureW = FullDepEntry "
-configureW() {
-    if test -n \"\$configurePhase\"; then
-        eval \"\$configurePhase\"
-        return
-    fi
-
-    eval \"\$preConfigure\"
-
-    if test -z \"\$configureScript\"; then
-        configureScript=./configure
-        if ! test -x \$configureScript; then
-            echo \"no configure script, doing nothing\"
-            return
-        fi
-    fi
-
-    if test -z \"\$dontFixLibtool\"; then
-        for i in \$(find . -name \"ltmain.sh\"); do
-            echo \"fixing libtool script \$i\"
-            fixLibtool \$i
-        done
-    fi
-
-    if test -z \"\$dontAddPrefix\"; then
-        configureFlags=\"--prefix=\$prefix \$configureFlags\"
-    fi
-
-    echo \"configure flags: \$configureFlags \${configureFlagsArray[@]}\"
-    \$configureScript \$configureFlags\"\${configureFlagsArray[@]}\" || fail
-
-    eval \"\$postConfigure\"
-}
-" [initPath];
-
-
-	defConfigurePhase = FullDepEntry "
-configurePhase() {
-    header \"configuring\"
-    startLog \"configure\"
-    configureW
-    stopLog
-    stopNest
-}
-" [defConfigureW];
-
-	defBuildW = FullDepEntry "
-buildW() {
-    if test -n \"\$buildPhase\"; then
-        eval \"\$buildPhase\"
-        return
-    fi
-
-    eval \"\$preBuild\"
-    
-    echo \"make flags: \$makeFlags \${makeFlagsArray[@]} \$buildFlags \${buildFlagsArray[@]}\"
-    make \
-        \$makeFlags \"\${makeFlagsArray[@]}\" \
-        \$buildFlags \"\${buildFlagsArray[@]}\" || fail
-
-    eval \"\$postBuild\"
-}
-" [initPath];
-
-	defBuildPhase = FullDepEntry "
-buildPhase() {
-    if test \"\$dontBuild\" = 1; then
-        return
-    fi
-    header \"building\"
-    startLog \"build\"
-    buildW
-    stopLog
-    stopNest
-}
-" [defBuildW];
-
-
-	defCheckW = FullDepEntry "
-checkW() {
-    if test -n \"\$checkPhase\"; then
-        eval \"\$checkPhase\"
-        return
-    fi
-
-    if test -z \"\$checkTarget\"; then
-        checkTarget=\"check\"
-    fi
-
-    echo \"check flags: \$makeFlags \${makeFlagsArray[@]} \$checkFlags \${checkFlagsArray[@]}\"
-    make \
-        \$makeFlags \"\${makeFlagsArray[@]}\" \
-        \$checkFlags \"\${checkFlagsArray[@]}\" \$checkTarget || fail
-}
-" [initPath];
-
-
-	defCheckPhase = FullDepEntry "
-checkPhase() {
-    if test \"\$doCheck\" != 1; then
-        return
-    fi
-    header \"checking\"
-    startLog \"check\"
-    checkW
-    stopLog
-    stopNest
-}
-" [checkPhase];
-
-
-	defPatchElf = FullDepEntry "
-patchELF() {
-    # Patch all ELF executables and shared libraries.
-    header \"patching ELF executables and libraries\"
-    find \"\$prefix\" \( \
-        \( -type f -a -name \"*.so*\" \) -o \
-        \( -type f -a -perm +0100 \) \
-        \) -print -exec patchelf --shrink-rpath {} \;
-    stopNest
-}
-" [initPath defNest];
-
-
-	defInstallW = FullDepEntry "
-installW() {
-    if test -n \"\$installPhase\"; then
-        eval \"\$installPhase\"
-        return
-    fi
-
-    eval \"\$preInstall\"
-
-    ensureDir \"\$prefix\"
-
-    if test -z \"\$installCommand\"; then
-        if test -z \"\$installTargets\"; then
-            installTargets=install
-        fi
-        echo \"install flags: \$installTargets \$makeFlags \${makeFlagsArray[@]} \$installFlags \${installFlagsArray[@]}\"
-        make \$installTargets \
-            \$makeFlags \"\${makeFlagsArray[@]}\" \
-            \$installFlags \"\${installFlagsArray[@]}\" || fail
-    else
-        eval \"\$installCommand\"
-    fi
-
-    eval \"\$postInstall\"
-}
-" [initPath];
-
-	
-	defInstallPhase = FullDepEntry "
-installPhase() {
-    if test \"\$dontInstall\" = 1; then
-        return
-    fi
-    header \"installing\"
-    startLog \"install\"
-    installW
-    stopLog
-    stopNest
-}
-" [defInstallW defNest defStartStopLog];
-
-
-	defFixupW = FullDepEntry "
-
-# The fixup phase performs generic, package-independent, Nix-related
-# stuff, like running patchelf and setting the
-# propagated-build-inputs.  It should rarely be overriden.
-fixupW() {
-    if test -n "$fixupPhase"; then
-        eval "$fixupPhase"
-        return
-    fi
-
-    eval "$preFixup"
-
- 	forceShare=${forceShare:=man doc info}
- 	if test -n "$forceShare"; then
- 		for d in $forceShare; do
- 			if test -d "$prefix/$d"; then
- 				if test -d "$prefix/share/$d"; then
- 					echo "Both $d/ and share/$d/ exists!"
- 				else
-					echo Fixing location of $dir/ subdirectory
- 					ensureDir $prefix/share
-					if test -w $prefix/share; then
-	 					mv -v $prefix/$d $prefix/share
- 						ln -sv share/$d $prefix
-					fi
- 				fi
-			else
-				echo "No $d/ subdirectory, skipping."
- 			fi
- 		done;
- 	fi
-
-
-# TODO : strip _only_ ELF executables, and return || fail here...
-    if test -z "$dontStrip"; then
-		echo "Stripping debuging symbols from files in"
-		stripDirs "${stripDebugList:-lib}" -S
-		echo "Stripping all symbols from files in"
-		stripDirs "${stripAllList:-bin sbin}" -s
-    fi
-
-    if test "$havePatchELF" = 1 -a -z "$dontPatchELF"; then
-        patchELF "$prefix"
-    fi
-
-    if test -n "$propagatedBuildInputs"; then
-        ensureDir "$out/nix-support"
-        echo "$propagatedBuildInputs" > "$out/nix-support/propagated-build-inputs"
-    fi
-
-	if test -n "$setupHook"; then
-		ensureDir "$out/nix-support"
-		substituteAll "$setupHook" "$out/nix-support/setup-hook"
-	fi
-
-    eval "$postFixup"
-}
-" [defPatchElf initPath];
-
-
-	defFixupPhase = FullDepEntry "
-fixupPhase() {
-    if test \"\$dontFixup\" = 1; then
-        return
-    fi
-    header \"post-installation fixup\"
-    startLog \"fixup\"
-    fixupW
-    stopLog
-    stopNest
-}
-" [defFixupW defNest defStartStopLog];
-
-
-	defDistW = FullDepEntry "
-distW() {
-    if test -n \"\$distPhase\"; then
-        eval \"\$distPhase\"
-        return
-    fi
-
-    eval \"\$preDist\"
-    
-    if test -z \"\$distTarget\"; then
-        distTarget=\"dist\"
-    fi
-
-    echo \"dist flags: \$distFlags \${distFlagsArray[@]}\"
-    make \$distFlags \"\${distFlagsArray[@]}\" \$distTarget || fail
-
-    if test \"\$dontCopyDist\" != 1; then
-        ensureDir \"\$out/tarballs\"
-
-        if test -z \"\$tarballs\"; then
-            tarballs=\"*.tar.gz\"
-        fi
-
-        # Note: don't quote \$tarballs, since we explicitly permit
-        # wildcards in there.
-        cp -pvd \$tarballs \$out/tarballs
-    fi
-
-    eval \"\$postDist\"
-}
-" [initPath ];
-
-
-	defDistPhase = FullDepEntry "
-distPhase() {
-    if test \"\$doDist\" != 1; then
-        return
-    fi
-    header \"creating distribution\"
-    startLog \"dist\"
-    distW
-    stopLog
-    stopNest
-}
-" [defDistW defNest defStartStopLog];
-
-	defGenericBuild = FullDepEntry "
-genericBuild() {
-    header \"building \$out\"
-
-    if test -n \"\$buildCommand\"; then
-        eval \"\$buildCommand\"
-        return
-    fi
-
-    if test -z \"\$phases\"; then
-        phases=\"unpackPhase patchPhase configurePhase buildPhase checkPhase \
-            installPhase fixupPhase distPhase\";
-    fi
-
-    for i in \$phases; do
-        dumpVars
-        eval \"\$i\"
-    done
-    
-    stopNest
-}
-" [defUnpackPhase defBuildPhase defInstallPhase];
-
-doDumpVars = FullDepEntry "
-dumpVars
-" [defDumpVars];
diff --git a/pkgs/stdenv/generic/setup.sh b/pkgs/stdenv/generic/setup.sh
index b6814aa410f..395de988e4c 100644
--- a/pkgs/stdenv/generic/setup.sh
+++ b/pkgs/stdenv/generic/setup.sh
@@ -1,3 +1,31 @@
+######################################################################
+# Helper functions that might be useful in setup hooks.
+
+
+addToSearchPathWithCustomDelimiter() {
+    local delimiter=$1
+    local varName=$2
+    local needDir=$3
+    local addDir=${4:-$needDir}
+    local prefix=$5
+    if [ -d $prefix$needDir ]; then
+        if [ -z ${!varName} ]; then
+            eval export ${varName}=${prefix}$addDir
+        else
+            eval export ${varName}=${!varName}${delimiter}${prefix}$addDir
+        fi
+    fi
+}
+
+addToSearchPath()
+{
+    addToSearchPathWithCustomDelimiter "${PATH_DELIMITER}" "$@"
+}
+
+
+######################################################################
+# Initialisation.
+
 set -e
 
 test -z $NIX_GCC && NIX_GCC=@gcc@
@@ -10,12 +38,13 @@ for i in $NIX_GCC @initialPath@; do
 done
 
 if test "$NIX_DEBUG" = "1"; then
-    echo "Initial path: $PATH"
+    echo "initial path: $PATH"
 fi
 
 
 # Execute the pre-hook.
 export SHELL=@shell@
+PATH_DELIMITER=':'
 if test -z "$shell"; then
     export shell=@shell@
 fi
@@ -24,9 +53,8 @@ param2=@param2@
 param3=@param3@
 param4=@param4@
 param5=@param5@
-if test -n "@preHook@"; then
-    source @preHook@
-fi
+if test -n "@preHook@"; then source @preHook@; fi
+eval "$preHook"
 
 
 # Check that the pre-hook initialised SHELL.
@@ -39,7 +67,7 @@ if test -f $NIX_GCC/nix-support/setup-hook; then
     source $NIX_GCC/nix-support/setup-hook
 fi
 
-    
+
 # Ensure that the given directories exists.
 ensureDir() {
     local dir
@@ -48,6 +76,17 @@ ensureDir() {
     done
 }
 
+installBin() {
+  ensureDir $out/bin
+  cp "$@" $out/bin
+}
+
+assertEnvExists(){
+  if test -z "${!1}"; then
+      msg=${2:-error: assertion failed: env var $1 is required}
+      echo $msg >&2; exit 1
+  fi
+}
 
 # Called when some build action fails.  If $succeedOnFailure is set,
 # create the file `$out/nix-support/failed' to signal failure, and
@@ -80,13 +119,13 @@ findInputs()
             return 0
             ;;
     esac
-    
+
     pkgs="$pkgs $pkg "
 
     if test -f $pkg/nix-support/setup-hook; then
         source $pkg/nix-support/setup-hook
     fi
-    
+
     if test -f $pkg/nix-support/propagated-build-inputs; then
         for i in $(cat $pkg/nix-support/propagated-build-inputs); do
             findInputs $i
@@ -141,20 +180,15 @@ if test -z "$NIX_STRIP_DEBUG"; then
 fi
 
 
-# Do we know where the store is?  This is required for purity checking.
-if test -z "$NIX_STORE"; then
-    echo "Error: you have an old version of Nix that does not set the" \
-        "NIX_STORE variable.  Please upgrade." >&2
-    exit 1
-fi
-
+assertEnvExists NIX_STORE \
+    "Error: you have an old version of Nix that does not set the
+     NIX_STORE variable. This is required for purity checking.
+     Please upgrade."
 
-# We also need to know the root of the build directory for purity checking.
-if test -z "$NIX_BUILD_TOP"; then
-    echo "Error: you have an old version of Nix that does not set the" \
-        "NIX_BUILD_TOP variable.  Please upgrade." >&2
-    exit 1
-fi
+assertEnvExists NIX_BUILD_TOP \
+    "Error: you have an old version of Nix that does not set the
+     NIX_BUILD_TOP variable. This is required for purity checking.
+     Please upgrade."
 
 
 # Set the TZ (timezone) environment variable, otherwise commands like
@@ -175,18 +209,36 @@ if test "$useTempPrefix" = "1"; then
 fi
 
 
-# Execute the post-hook.
-if test -n "@postHook@"; then
-    source @postHook@
-fi
-
 PATH=$_PATH${_PATH:+:}$PATH
 if test "$NIX_DEBUG" = "1"; then
-    echo "Final path: $PATH"
+    echo "final path: $PATH"
 fi
 
 
 ######################################################################
+# Misc. helper functions.
+
+
+stripDirs() {
+    local dirs="$1"
+    local stripFlags="$2"
+    local dirsNew=
+
+    for d in ${dirs}; do
+        if test -d "$prefix/$d"; then
+            dirsNew="${dirsNew} $prefix/$d "
+        fi
+    done
+    dirs=${dirsNew}
+
+    if test -n "${dirs}"; then
+        echo $dirs
+        find $dirs -type f -print0 | xargs -0 strip $stripFlags || true
+    fi
+}
+
+
+######################################################################
 # Textual substitution functions.
 
 
@@ -195,40 +247,44 @@ substitute() {
     local output="$2"
 
     local -a params=("$@")
+    local -a args=()
 
     local sedScript=$NIX_BUILD_TOP/.sedargs
     rm -f $sedScript
     touch $sedScript
 
     local n p pattern replacement varName
-    
+
     for ((n = 2; n < ${#params[*]}; n += 1)); do
         p=${params[$n]}
 
         if test "$p" = "--replace"; then
-            pattern=${params[$((n + 1))]}
-            replacement=${params[$((n + 2))]}
+            pattern="${params[$((n + 1))]}"
+            replacement="${params[$((n + 2))]}"
             n=$((n + 2))
-            echo "s^$pattern^$replacement^g" >> $sedScript
-            sedArgs=("${sedArgs[@]}" "-e" )
         fi
 
         if test "$p" = "--subst-var"; then
-            varName=${params[$((n + 1))]}
+            varName="${params[$((n + 1))]}"
+            pattern="@$varName@"
+            replacement="${!varName}"
             n=$((n + 1))
-            echo "s^@${varName}@^${!varName}^g" >> $sedScript
         fi
 
         if test "$p" = "--subst-var-by"; then
-            varName=${params[$((n + 1))]}
-            replacement=${params[$((n + 2))]}
+            pattern="@${params[$((n + 1))]}@"
+            replacement="${params[$((n + 2))]}"
             n=$((n + 2))
-            echo "s^@${varName}@^$replacement^g" >> $sedScript
         fi
 
+        if test ${#args[@]} != 0; then
+            args[${#args[@]}]="-a"
+        fi
+        args[${#args[@]}]="$pattern"
+        args[${#args[@]}]="$replacement"
     done
 
-    sed -f $sedScript < "$input" > "$output".tmp
+    replace-literal -e -s "${args[@]}" < "$input" > "$output".tmp
     if test -x "$output"; then
         chmod +x "$output".tmp
     fi
@@ -246,7 +302,7 @@ substituteInPlace() {
 substituteAll() {
     local input="$1"
     local output="$2"
-    
+
     # Select all environment variables that start with a lowercase character.
     for envVar in $(env | sed "s/^[^a-z].*//" | sed "s/^\([^=]*\)=.*/\1/"); do
         if test "$NIX_DEBUG" = "1"; then
@@ -256,7 +312,7 @@ substituteAll() {
     done
 
     substitute "$input" "$output" $args
-}  
+}
 
 
 ######################################################################
@@ -366,20 +422,20 @@ stripHash() {
 
 
 unpackFile() {
-    local file=$1
+    local file="$1"
     local cmd
 
     header "unpacking source archive $file" 3
 
-    case $file in
+    case "$file" in
         *.tar)
             tar xvf $file || fail
             ;;
         *.tar.gz | *.tgz | *.tar.Z)
-            gunzip < $file | tar xvf - || fail
+            gzip -d < $file | tar xvf - || fail
             ;;
         *.tar.bz2 | *.tbz2)
-            bunzip2 < $file | tar xvf - || fail
+            bzip2 -d < $file | tar xvf - || fail
             ;;
         *.zip)
             unzip $file || fail
@@ -405,7 +461,7 @@ unpackFile() {
 }
 
 
-unpackW() {
+unpackPhase() {
     if test -n "$unpackPhase"; then
         eval "$unpackPhase"
         return
@@ -475,21 +531,14 @@ unpackW() {
 }
 
 
-unpackPhase() {
-    header "unpacking sources"
-    startLog "unpack"
-    unpackW
-    stopLog
-    stopNest
-}
-
-
-patchW() {
+patchPhase() {
     if test -n "$patchPhase"; then
         eval "$patchPhase"
         return
     fi
 
+    if test -z "$patchPhase" -a -z "$patches"; then return; fi
+    
     if test -z "$patchFlags"; then
         patchFlags="-p1"
     fi
@@ -499,10 +548,10 @@ patchW() {
         local uncompress=cat
         case $i in
             *.gz)
-                uncompress=gunzip
+                uncompress="gzip -d"
                 ;;
             *.bz2)
-                uncompress=bunzip2
+                uncompress="bzip2 -d"
                 ;;
         esac
         $uncompress < $i | patch $patchFlags || fail
@@ -511,23 +560,13 @@ patchW() {
 }
 
 
-patchPhase() {
-    if test -z "$patchPhase" -a -z "$patches"; then return; fi
-    header "patching sources"
-    startLog "patch"
-    patchW
-    stopLog
-    stopNest
-}
-
-
 fixLibtool() {
     sed 's^eval sys_lib_.*search_path=.*^^' < $1 > $1.tmp
     mv $1.tmp $1
 }
 
 
-configureW() {
+configurePhase() {
     if test -n "$configurePhase"; then
         eval "$configurePhase"
         return
@@ -551,7 +590,14 @@ configureW() {
     fi
 
     if test -z "$dontAddPrefix"; then
-        configureFlags="--prefix=$prefix $configureFlags"
+        configureFlags="${prefixKey:---prefix=}$prefix $configureFlags"
+    fi
+
+    # Add --disable-dependency-tracking to speed up some builds.
+    if test -z "$dontAddDisableDepTrack"; then
+        if grep -q dependency-tracking $configureScript; then
+            configureFlags="--disable-dependency-tracking ${prefixKey:---prefix=}$prefix $configureFlags"
+        fi
     fi
 
     echo "configure flags: $configureFlags ${configureFlagsArray[@]}"
@@ -561,25 +607,21 @@ configureW() {
 }
 
 
-configurePhase() {
-    header "configuring"
-    startLog "configure"
-    configureW
-    stopLog
-    stopNest
-}
-
-
-buildW() {
+buildPhase() {
     if test -n "$buildPhase"; then
         eval "$buildPhase"
         return
     fi
 
     eval "$preBuild"
-    
+
+    if ! test -n "$makefile" -o -e "Makefile" -o -e "makefile" -o -e "GNUmakefile"; then
+        echo "no Makefile, doing nothing"
+        return
+    fi
+
     echo "make flags: $makeFlags ${makeFlagsArray[@]} $buildFlags ${buildFlagsArray[@]}"
-    make \
+    make ${makefile:+-f $makefile} \
         $makeFlags "${makeFlagsArray[@]}" \
         $buildFlags "${buildFlagsArray[@]}" || fail
 
@@ -587,19 +629,7 @@ buildW() {
 }
 
 
-buildPhase() {
-    if test "$dontBuild" = 1; then
-        return
-    fi
-    header "building"
-    startLog "build"
-    buildW
-    stopLog
-    stopNest
-}
-
-
-checkW() {
+checkPhase() {
     if test -n "$checkPhase"; then
         eval "$checkPhase"
         return
@@ -610,24 +640,12 @@ checkW() {
     fi
 
     echo "check flags: $makeFlags ${makeFlagsArray[@]} $checkFlags ${checkFlagsArray[@]}"
-    make \
+    make ${makefile:+-f $makefile} \
         $makeFlags "${makeFlagsArray[@]}" \
         $checkFlags "${checkFlagsArray[@]}" $checkTarget || fail
 }
 
 
-checkPhase() {
-    if test "$doCheck" != 1; then
-        return
-    fi
-    header "checking"
-    startLog "check"
-    checkW
-    stopLog
-    stopNest
-}
-
-
 patchELF() {
     # Patch all ELF executables and shared libraries.
     header "patching ELF executables and libraries"
@@ -639,7 +657,7 @@ patchELF() {
 }
 
 
-installW() {
+installPhase() {
     if test -n "$installPhase"; then
         eval "$installPhase"
         return
@@ -654,7 +672,7 @@ installW() {
             installTargets=install
         fi
         echo "install flags: $installTargets $makeFlags ${makeFlagsArray[@]} $installFlags ${installFlagsArray[@]}"
-        make $installTargets \
+        make ${makefile:+-f $makefile} $installTargets \
             $makeFlags "${makeFlagsArray[@]}" \
             $installFlags "${installFlagsArray[@]}" || fail
     else
@@ -665,22 +683,10 @@ installW() {
 }
 
 
-installPhase() {
-    if test "$dontInstall" = 1; then
-        return
-    fi
-    header "installing"
-    startLog "install"
-    installW
-    stopLog
-    stopNest
-}
-
-
 # The fixup phase performs generic, package-independent, Nix-related
 # stuff, like running patchelf and setting the
 # propagated-build-inputs.  It should rarely be overriden.
-fixupW() {
+fixupPhase() {
     if test -n "$fixupPhase"; then
         eval "$fixupPhase"
         return
@@ -688,9 +694,33 @@ fixupW() {
 
     eval "$preFixup"
 
-    if test -z "$dontStrip" -a "$NIX_STRIP_DEBUG" = 1; then
-        find "$prefix" -name "*.a" -exec echo stripping {} \; \
-            -exec strip -S {} \; || fail
+    # Put man/doc/info under $out/share.
+    forceShare=${forceShare:=man doc info}
+    if test -n "$forceShare"; then
+        for d in $forceShare; do
+            if test -d "$prefix/$d"; then
+                if test -d "$prefix/share/$d"; then
+                    echo "both $d/ and share/$d/ exists!"
+                else
+                    echo "fixing location of $d/ subdirectory"
+                    ensureDir $prefix/share
+                    if test -w $prefix/share; then
+                        mv -v $prefix/$d $prefix/share
+                        ln -sv share/$d $prefix
+                    fi
+                fi
+            fi
+        done;
+    fi
+
+    # TODO: strip _only_ ELF executables, and return || fail here...
+    if test -z "$dontStrip"; then
+        stripDebugList=${stripDebugList:-lib}
+        echo "stripping debuging symbols from files in $stripDebugList"
+        stripDirs "$stripDebugList" -S
+        stripAllList=${stripAllList:-bin sbin}
+        echo "stripping all symbols from files in $stripAllList"
+        stripDirs "$stripAllList" -s
     fi
 
     if test "$havePatchELF" = 1 -a -z "$dontPatchELF"; then
@@ -702,36 +732,29 @@ fixupW() {
         echo "$propagatedBuildInputs" > "$out/nix-support/propagated-build-inputs"
     fi
 
-    eval "$postFixup"
-}
-
-
-fixupPhase() {
-    if test "$dontFixup" = 1; then
-        return
+    if test -n "$setupHook"; then
+        ensureDir "$out/nix-support"
+        substituteAll "$setupHook" "$out/nix-support/setup-hook"
     fi
-    header "post-installation fixup"
-    startLog "fixup"
-    fixupW
-    stopLog
-    stopNest
+
+    eval "$postFixup"
 }
 
 
-distW() {
+distPhase() {
     if test -n "$distPhase"; then
         eval "$distPhase"
         return
     fi
 
     eval "$preDist"
-    
+
     if test -z "$distTarget"; then
         distTarget="dist"
     fi
 
     echo "dist flags: $distFlags ${distFlagsArray[@]}"
-    make $distFlags "${distFlagsArray[@]}" $distTarget || fail
+    make ${makefile:+-f $makefile} $distFlags "${distFlagsArray[@]}" $distTarget || fail
 
     if test "$dontCopyDist" != 1; then
         ensureDir "$out/tarballs"
@@ -749,15 +772,18 @@ distW() {
 }
 
 
-distPhase() {
-    if test "$doDist" != 1; then
-        return
-    fi
-    header "creating distribution"
-    startLog "dist"
-    distW
-    stopLog
-    stopNest
+showPhaseHeader() {
+    local phase="$1"
+    case $phase in
+        unpackPhase) header "unpacking sources";;
+        patchPhase) header "patching sources";;
+        configurePhase) header "configuring";;
+        buildPhase) header "building";;
+        checkPhase) header "running tests";;
+        installPhase) header "installing";;
+        fixupPhase) header "post-installation fixup";;
+        *) header "$phase";;
+    esac
 }
 
 
@@ -769,21 +795,41 @@ genericBuild() {
         return
     fi
 
-    unpackPhase
-    cd $sourceRoot
-
     if test -z "$phases"; then
-        phases="patchPhase configurePhase buildPhase checkPhase \
-            installPhase fixupPhase distPhase";
-    fi
-
-    for i in $phases; do
+        phases="unpackPhase patchPhase configurePhase buildPhase checkPhase \
+            installPhase fixupPhase distPhase $extraPhases";
+    fi
+
+    for curPhase in $phases; do
+        if test "$curPhase" = buildPhase -a -n "$dontBuild"; then continue; fi
+        if test "$curPhase" = checkPhase -a -z "$doCheck"; then continue; fi
+        if test "$curPhase" = installPhase -a -n "$dontInstall"; then continue; fi
+        if test "$curPhase" = fixupPhase -a -n "$dontFixup"; then continue; fi
+        if test "$curPhase" = distPhase -a -z "$doDist"; then continue; fi
+        
+        showPhaseHeader "$curPhase"
+        startLog "$curPhase"
         dumpVars
-        eval "$i"
+        
+        # Evaluate the variable named $curPhase if it exists, otherwise the
+        # function named $curPhase.
+        eval "${!curPhase:-$curPhase}"
+
+        if test "$curPhase" = unpackPhase; then
+            cd "${sourceRoot:-.}"
+        fi
+        
+        stopLog
+        stopNest
     done
-    
+
     stopNest
 }
 
 
+# Execute the post-hook.
+if test -n "@postHook@"; then source @postHook@; fi
+eval "$postHook"
+
+
 dumpVars
diff --git a/pkgs/stdenv/linux/bootstrap/i686/bunzip2 b/pkgs/stdenv/linux/bootstrap/i686/bunzip2
deleted file mode 100755
index 3f3f810e77e..00000000000
--- a/pkgs/stdenv/linux/bootstrap/i686/bunzip2
+++ /dev/null
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/i686/bzip2 b/pkgs/stdenv/linux/bootstrap/i686/bzip2
new file mode 100755
index 00000000000..ea45149fa4d
--- /dev/null
+++ b/pkgs/stdenv/linux/bootstrap/i686/bzip2
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/i686/cp b/pkgs/stdenv/linux/bootstrap/i686/cp
index 06de68ad9a8..55142a9e0b8 100755
--- a/pkgs/stdenv/linux/bootstrap/i686/cp
+++ b/pkgs/stdenv/linux/bootstrap/i686/cp
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/i686/curl.bz2 b/pkgs/stdenv/linux/bootstrap/i686/curl.bz2
index 8db4439e4b8..b7434ff5b9e 100755
--- a/pkgs/stdenv/linux/bootstrap/i686/curl.bz2
+++ b/pkgs/stdenv/linux/bootstrap/i686/curl.bz2
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/i686/default.nix b/pkgs/stdenv/linux/bootstrap/i686/default.nix
index d48cbc9a5c5..db5c581453b 100644
--- a/pkgs/stdenv/linux/bootstrap/i686/default.nix
+++ b/pkgs/stdenv/linux/bootstrap/i686/default.nix
@@ -1,27 +1,27 @@
 {
   bash = ./bash;
-  bunzip2 = ./bunzip2;
+  bzip2 = ./bzip2;
   cp = ./cp;
   curl = ./curl.bz2;
   tar = ./tar.bz2;
 
-  staticToolsURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/i686/r6881/static-tools.tar.bz2;
-    sha1 = "c366d9ee0d969e68311fdb37abc91b46fb13b585";
-  };
-
   binutilsURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/i686/r6881/binutils.tar.bz2;
-    sha1 = "fa77c29ef4f13ddf43bba3f4f020ceafa6604ccc";
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/i686/r9803/binutils.tar.bz2;
+    sha1 = "73532561c2f98d0df641fbd778bc92cea298762a";
   };
 
   gccURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/i686/r6881/gcc.tar.bz2;
-    sha1 = "ea7171fc2f70880e8a6c2480b3d3fed7409b7a4e";
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/i686/r9803/gcc.tar.bz2;
+    sha1 = "522dc2e22dc42f640b0290638382d45bd43a7d55";
   };
 
   glibcURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/i686/r6881/glibc.tar.bz2;
-    sha1 = "728e0a9e66e01cf2815eca8cc638e5ed140a36cd";
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/i686/r9803/glibc.tar.bz2;
+    sha1 = "b9ae1e43e9977476ef53f8c1c9cd1cff5526ff40";
+  };
+
+  staticToolsURL = {
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/i686/r9803/static-tools.tar.bz2;
+    sha1 = "ebe826e848736a82bcdd9a195dd510b533ecc997";
   };
 }
diff --git a/pkgs/stdenv/linux/bootstrap/i686/tar.bz2 b/pkgs/stdenv/linux/bootstrap/i686/tar.bz2
index 189bcce24eb..b6241bf3d23 100755
--- a/pkgs/stdenv/linux/bootstrap/i686/tar.bz2
+++ b/pkgs/stdenv/linux/bootstrap/i686/tar.bz2
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/powerpc/bunzip2 b/pkgs/stdenv/linux/bootstrap/powerpc/bunzip2
deleted file mode 100755
index 730214a404b..00000000000
--- a/pkgs/stdenv/linux/bootstrap/powerpc/bunzip2
+++ /dev/null
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/powerpc/bzip2 b/pkgs/stdenv/linux/bootstrap/powerpc/bzip2
new file mode 100755
index 00000000000..a9eb626e1ca
--- /dev/null
+++ b/pkgs/stdenv/linux/bootstrap/powerpc/bzip2
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/powerpc/cp b/pkgs/stdenv/linux/bootstrap/powerpc/cp
index 4477d7eb6e0..972a653851c 100755
--- a/pkgs/stdenv/linux/bootstrap/powerpc/cp
+++ b/pkgs/stdenv/linux/bootstrap/powerpc/cp
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/powerpc/curl.bz2 b/pkgs/stdenv/linux/bootstrap/powerpc/curl.bz2
index 90f0fa69ab2..4f0d64341e8 100755
--- a/pkgs/stdenv/linux/bootstrap/powerpc/curl.bz2
+++ b/pkgs/stdenv/linux/bootstrap/powerpc/curl.bz2
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/powerpc/default.nix b/pkgs/stdenv/linux/bootstrap/powerpc/default.nix
index 1cb29ee4a62..a354cc01d85 100644
--- a/pkgs/stdenv/linux/bootstrap/powerpc/default.nix
+++ b/pkgs/stdenv/linux/bootstrap/powerpc/default.nix
@@ -1,27 +1,27 @@
 {
   bash = ./bash;
-  bunzip2 = ./bunzip2;
+  bzip2 = ./bzip2;
   cp = ./cp;
   curl = ./curl.bz2;
   tar = ./tar.bz2;
 
   staticToolsURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/powerpc/r6888/static-tools.tar.bz2;
-    sha1 = "82acee6c1a895f3a45fdbf921d49be6c996abc5b";
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/powerpc/r9828/static-tools.tar.bz2;
+    sha1 = "e4d1680e3dfa752e49a996a31140db53b10061cb";
   };
 
   binutilsURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/powerpc/r6888/binutils.tar.bz2;
-    sha1 = "bc4f9fc931b0d139d0b16e548b1605d5181c74c0";
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/powerpc/r9828/binutils.tar.bz2;
+    sha1 = "2609f4d9277a60fcd178395d3d49911190e08f36";
   };
 
   gccURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/powerpc/r6888/gcc.tar.bz2;
-    sha1 = "ade3225a3135b0e3415cc8cb9e1bec61a742e200";
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/powerpc/r9828/gcc.tar.bz2;
+    sha1 = "71d79d736bfef6252208fe6239e528a591becbed";
   };
 
   glibcURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/powerpc/r6888/glibc.tar.bz2;
-    sha1 = "e28476443e02b9c2e7881ced27c23cb039421cda";
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/powerpc/r9828/glibc.tar.bz2;
+    sha1 = "bf0245e16235800c8aa9c6a5de6565583a66e46d";
   };
 }
diff --git a/pkgs/stdenv/linux/bootstrap/powerpc/tar.bz2 b/pkgs/stdenv/linux/bootstrap/powerpc/tar.bz2
index 999bca557e2..c014e9cc044 100755
--- a/pkgs/stdenv/linux/bootstrap/powerpc/tar.bz2
+++ b/pkgs/stdenv/linux/bootstrap/powerpc/tar.bz2
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/x86_64/bunzip2 b/pkgs/stdenv/linux/bootstrap/x86_64/bunzip2
deleted file mode 100755
index 9ca924e2bc4..00000000000
--- a/pkgs/stdenv/linux/bootstrap/x86_64/bunzip2
+++ /dev/null
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/x86_64/bzip2 b/pkgs/stdenv/linux/bootstrap/x86_64/bzip2
new file mode 100755
index 00000000000..dd2cce8952c
--- /dev/null
+++ b/pkgs/stdenv/linux/bootstrap/x86_64/bzip2
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/x86_64/cp b/pkgs/stdenv/linux/bootstrap/x86_64/cp
index b563278f9a6..397b1e89809 100755
--- a/pkgs/stdenv/linux/bootstrap/x86_64/cp
+++ b/pkgs/stdenv/linux/bootstrap/x86_64/cp
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/x86_64/curl.bz2 b/pkgs/stdenv/linux/bootstrap/x86_64/curl.bz2
index a4051323193..8e40942bcfe 100755
--- a/pkgs/stdenv/linux/bootstrap/x86_64/curl.bz2
+++ b/pkgs/stdenv/linux/bootstrap/x86_64/curl.bz2
Binary files differdiff --git a/pkgs/stdenv/linux/bootstrap/x86_64/default.nix b/pkgs/stdenv/linux/bootstrap/x86_64/default.nix
index f43fa42682b..0608fc4002e 100644
--- a/pkgs/stdenv/linux/bootstrap/x86_64/default.nix
+++ b/pkgs/stdenv/linux/bootstrap/x86_64/default.nix
@@ -1,27 +1,27 @@
 {
   bash = ./bash;
-  bunzip2 = ./bunzip2;
+  bzip2 = ./bzip2;
   cp = ./cp;
   curl = ./curl.bz2;
   tar = ./tar.bz2;
 
-  staticToolsURL = {
-    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/x86_64/r6905/static-tools.tar.bz2;
-    sha1 = "5467de09c91f0a9bf511a9d476547e10b9f067fb";
-  };
-
   binutilsURL = {
     url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/x86_64/r6905/binutils.tar.bz2;
-    sha1 = "739623c8be225224ed57a76c5f483d5e373fdae8";
+    sha1 = "9ac95e34c96c19cd0b925af46c97c9979becaaca";
   };
 
   gccURL = {
     url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/x86_64/r6905/gcc.tar.bz2;
-    sha1 = "b4bb2b2863d7b368c7c32e789d6877e5b5a97637";
+    sha1 = "e8cb32425c8f55833ca081bd74668a029bdf1755";
   };
 
   glibcURL = {
     url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/x86_64/r6905/glibc.tar.bz2;
-    sha1 = "f0a5e1a224931f59267975a51d4e9c20e6cb3ae8";
+    sha1 = "74b1698a4595ce4b4f43a33b3ceca1e4459e494e";
+  };
+
+  staticToolsURL = {
+    url = http://nix.cs.uu.nl/dist/tarballs/stdenv-linux/x86_64/r6905/static-tools.tar.bz2;
+    sha1 = "4da3af92c9bcd8fc43b31934d8429412e209741b";
   };
 }
diff --git a/pkgs/stdenv/linux/bootstrap/x86_64/tar.bz2 b/pkgs/stdenv/linux/bootstrap/x86_64/tar.bz2
index c28307335dd..94b2bacdb9d 100755
--- a/pkgs/stdenv/linux/bootstrap/x86_64/tar.bz2
+++ b/pkgs/stdenv/linux/bootstrap/x86_64/tar.bz2
Binary files differdiff --git a/pkgs/stdenv/linux/default.nix b/pkgs/stdenv/linux/default.nix
index f926469a403..6a183457f08 100644
--- a/pkgs/stdenv/linux/default.nix
+++ b/pkgs/stdenv/linux/default.nix
@@ -27,7 +27,7 @@ rec {
     inherit system;
     name = "curl";
     builder = bootstrapTools.bash;
-    inherit (bootstrapTools) bunzip2 cp curl;
+    inherit (bootstrapTools) bzip2 cp curl;
     args = [ ./scripts/unpack-curl.sh ];
   };
 
@@ -45,7 +45,7 @@ rec {
   downloadAndUnpack = pkgname: {url, sha1}: derivation {
     name = pkgname;
     builder = bootstrapTools.bash;
-    inherit (bootstrapTools) bunzip2 tar cp;
+    inherit (bootstrapTools) bzip2 tar cp;
     args = [ ./scripts/unpack.sh ];
     tarball = download {inherit url sha1 pkgname;};
     inherit system;
diff --git a/pkgs/stdenv/linux/make-bootstrap-tools.nix b/pkgs/stdenv/linux/make-bootstrap-tools.nix
index db7c3d72e11..6358855464b 100644
--- a/pkgs/stdenv/linux/make-bootstrap-tools.nix
+++ b/pkgs/stdenv/linux/make-bootstrap-tools.nix
@@ -1,6 +1,8 @@
+{system ? builtins.currentSystem}:
+
 let
 
-  pkgs = import ../../top-level/all-packages.nix {};
+  pkgs = import ../../top-level/all-packages.nix {inherit system;};
 
   
   # Have to do removeAttrs to prevent all-packages from copying
@@ -37,22 +39,23 @@ let
 
     gnutar =
       # Tar seems to be broken on dietlibc on x86_64.
-      if pkgs.stdenv.system != "x86_64-linux"
+      if system != "x86_64-linux"
       then pkgsDiet.gnutar151 # 1.16 is broken
       else pkgsStatic.gnutar;
 
     gawk = 
       # Dietlibc only provides sufficient math functions (fmod, sin,
       # cos, etc.) on i686.  On other platforms, use Glibc.
-      if pkgs.stdenv.system == "i686-linux"
+      if system == "i686-linux"
       then pkgsDiet.gawk
       else pkgsStatic.gawk;
       
-    gcc = import ../../development/compilers/gcc-4.1 {
+    gcc = import ../../development/compilers/gcc-4.2 {
       inherit (pkgs) fetchurl stdenv;
       noSysDirs = true;
       langCC = false;
       staticCompiler = true;
+      profiledCompiler = true;
     };
   
     curl = pkgsDiet.realCurl;
diff --git a/pkgs/stdenv/linux/make-bootstrap-tools.sh b/pkgs/stdenv/linux/make-bootstrap-tools.sh
index 49bb5afe477..cadc2129b31 100644
--- a/pkgs/stdenv/linux/make-bootstrap-tools.sh
+++ b/pkgs/stdenv/linux/make-bootstrap-tools.sh
@@ -24,7 +24,7 @@ nukeRefs() {
 # necessary for the absolute first stage of the bootstrap.
 cp $bash/bin/bash $out/in-nixpkgs
 nukeRefs $out/in-nixpkgs/bash
-cp $bzip2/bin/bunzip2 $out/in-nixpkgs
+cp $bzip2/bin/bzip2 $out/in-nixpkgs
 cp $coreutils/bin/cp $out/in-nixpkgs
 cp $gnutar/bin/tar $out/in-nixpkgs
 nukeRefs $out/in-nixpkgs/tar
@@ -51,8 +51,7 @@ cp $gawk/bin/gawk tools/bin
 ln -s gawk tools/bin/awk
 cp $gnutar/bin/* tools/bin
 cp $gzip/bin/gzip tools/bin
-ln -s gzip tools/bin/gunzip
-cp $bzip2/bin/bunzip2 tools/bin
+cp $bzip2/bin/bzip2 tools/bin
 cp $gnumake/bin/* tools/bin
 cp $patch/bin/* tools/bin
 cp $patchelf/bin/* tools/bin
@@ -62,6 +61,8 @@ nukeRefs tools/bin/sed
 nukeRefs tools/bin/gawk
 nukeRefs tools/bin/tar
 nukeRefs tools/bin/grep
+nukeRefs tools/bin/fgrep
+nukeRefs tools/bin/egrep
 nukeRefs tools/bin/patchelf
 nukeRefs tools/bin/make
 
@@ -87,7 +88,6 @@ cp -prd $gcc/libexec gcc
 chmod -R +w gcc
 nukeRefs gcc/libexec/gcc/*/*/cc1
 nukeRefs gcc/libexec/gcc/*/*/collect2
-rm -f gcc/lib/libmud* gcc/lib/libiberty* gcc/lib/libssp*
 if test -e gcc/lib/libgcc_s.so.1; then
     nukeRefs gcc/lib/libgcc_s.so.1
 fi
@@ -96,11 +96,15 @@ if test -e $gcc/lib64; then
     chmod -R +w gcc/lib64
     nukeRefs gcc/lib64/libgcc_s.so.1
 fi
+rm -f gcc/lib*/libmud* gcc/lib*/libiberty* gcc/lib*/libssp* gcc/lib*/libgomp*
 rm -rf gcc/lib/gcc/*/*/install-tools
 rm -rf gcc/lib/gcc/*/*/include/root
 rm -rf gcc/lib/gcc/*/*/include/linux
-if test -e gcc/lib/gcc/powerpc-unknown-linux-gnu/4.1.1/include/bits/mathdef.h; then
-    nukeRefs gcc/lib/gcc/powerpc-unknown-linux-gnu/4.1.1/include/bits/mathdef.h
+if test "$system" = "powerpc-linux"; then
+    nukeRefs gcc/lib/gcc/powerpc-unknown-linux-gnu/*/include/bits/mathdef.h
+    # Dangling symlink "sound", probably produced by fixinclude.
+    # Should investigate why it's there in the first place.
+    rm -f gcc/lib/gcc/powerpc-unknown-linux-gnu/*/include/sound
 fi
 
 
@@ -116,12 +120,20 @@ chmod -R +w glibc
 rm glibc/include/linux
 cp -prd $(readlink $glibc/include/linux) glibc/include
 rm glibc/include/asm
-ln -s $(readlink $(readlink $glibc/include/asm)) glibc/include/asm
+if test -L "$(readlink $glibc/include/asm)"; then
+    ln -s $(readlink $(readlink $glibc/include/asm)) glibc/include/asm
+else
+    cp -prd "$(readlink $glibc/include/asm)" glibc/include
+fi
 for i in glibc/include/asm-*; do
     target=$(readlink $i)
     rm $i
     cp -prd $target glibc/include
 done
+if test "$system" = "powerpc-linux"; then
+    # Hopefully we won't need these.
+    rm -f glibc/include/mtd glibc/include/rdma glibc/include/sound glibc/include/video
+fi
 
 
 # Strip executables even further.
diff --git a/pkgs/stdenv/linux/scripts/unpack-curl.sh b/pkgs/stdenv/linux/scripts/unpack-curl.sh
index 147edcebe04..3023f865c94 100644
--- a/pkgs/stdenv/linux/scripts/unpack-curl.sh
+++ b/pkgs/stdenv/linux/scripts/unpack-curl.sh
@@ -7,5 +7,5 @@ $cp -prvd . $out
 $cp -prvd . $out/bin
 
 $cp $curl curl.bz2
-$bunzip2 -d curl.bz2
+$bzip2 -d curl.bz2
 $cp curl $out/bin
diff --git a/pkgs/stdenv/linux/scripts/unpack.sh b/pkgs/stdenv/linux/scripts/unpack.sh
index ef3eaf6349c..eb916cbc48d 100644
--- a/pkgs/stdenv/linux/scripts/unpack.sh
+++ b/pkgs/stdenv/linux/scripts/unpack.sh
@@ -1,8 +1,8 @@
 set -e
 
 $cp $tar .tar.bz2
-$bunzip2 .tar.bz2
+$bzip2 -d .tar.bz2
 
-$bunzip2 -d < $tarball | ./.tar xvf -
+$bzip2 -d < $tarball | ./.tar xvf -
 
 $cp -prd * $out
diff --git a/pkgs/test/openftd/default.nix b/pkgs/test/openftd/default.nix
new file mode 100644
index 00000000000..34cff9ac93f
--- /dev/null
+++ b/pkgs/test/openftd/default.nix
@@ -0,0 +1,49 @@
+/*
+
+Systeemvereisten
+
+* libz >= 1.1.4
+* glib >= 2.2.0
+* gtk >= 2.2.0
+
+Glib 2 is een 'dependancy' van gtk2. Als je gtk2 op je systeem hebt staan dan heb je ongetwijfeld ook glib2 op je systeem. Zie: www.gtk.org voor meer informatie omtrent Glib/gtk2
+Alhoewel FTD4Linux gtk 2.2 als minimumvereiste heeft raden we toch aan om gtk 2.4 te gebruiken. Dit vanwege een bug in gtk versies 2.2.2 t/m 2.2.4.
+
+* libxml2 >= 2.2.5
+* libxslt >= 1.0.5
+
+* mozilla (gecompileerd met gtk2 support)
+Mozilla is de opensource browser die is voortgekomen uit het vrijgeven van de netscape navigator source code. Als je mozilla reeds op je systeem hebt staan zou je even moeten nagaan of deze tegen gtk2 is gelinkt. Dit kun je doen met behulp van het programma ldd.
+ldd /usr/X11R6/lib/mozilla-gtk2/libgtkembedmoz.so | grep gtk
+/usr/X11R6/lib/mozilla-gtk2/libgtkembedmoz.so:
+libgtk-x11-2.0.so.200 => /usr/X11R6/lib/libgtk-x11-2.0.so.200 (0x282c3000)
+In de output van het ldd programma kun je zien of er inderdaad wordt gelink tegen gtk2. (libgtk-x11-2.0.so.200).
+Heb je geen mozilla, maar heb je wel de firebird/firefox variant geinstalleerd staan dan kun je ook met de mozilla compatible onderdelen van firebird/firefox aan de gang. Je hebt hier echter wel de header (development) bestanden bij nodig. Controleer dus even of jouw firebird/firefox installatie hiermee is geleverd. (gtkembedmoz/gtkmozembed.h) Een 'locate gtkmozembed.h' zou hier snel genoeg uitsluitsel over moeten geven.
+
+* OpenSSL
+* LibCURL
+
+*/
+
+{ stdenv, fetchurl
+, zlib, libxml2, libxslt, firefox, openssl, curl
+, glib, gtk, libgnomeui, libgtkhtml
+, pkgconfig, dbus_glib, realCurl, pcre, libsexy, gtkspell, libnotify
+}:
+ 
+stdenv.mkDerivation {
+  name = "openftd-0.98.6";
+  #builder = ./builder.sh;
+
+  src = fetchurl {
+    url = http://speeldoos.eweka.nl/~paul/openftd/openftd-1.0.1.tar.bz2;
+    sha256 = "e0710865f852fdf209949788a1ced65e9ecf82b4eaa0992a7a1dde1511a3b6e7";
+  };
+
+  buildInputs = [
+    zlib libxml2 libxslt firefox openssl curl
+    glib gtk pkgconfig dbus_glib realCurl pcre libsexy libgnomeui gtkspell libnotify libgtkhtml
+  ];
+
+  configureFlags="--with-libcurl-libraries=${curl}/lib --with-libcurl-headers=${curl}/include --with-pcre_libraries=${pcre}/lib --with-pcre_headers=${pcre}/include";  
+}
diff --git a/pkgs/tools/X11/xlaunch/default.nix b/pkgs/tools/X11/xlaunch/default.nix
new file mode 100644
index 00000000000..89c94ffd515
--- /dev/null
+++ b/pkgs/tools/X11/xlaunch/default.nix
@@ -0,0 +1,48 @@
+args: with args;
+stdenv.mkDerivation {
+	name = "xlaunch";
+	inherit xorgserver;
+	buildCommand = "
+		cat << EOF > realizeuid.c
+		#include <sys/types.h>
+		#include <unistd.h>
+		#include <stdio.h>
+		int main(int argc, char ** argv, char ** envp)
+		{
+			uid_t a,b,c;
+			int i;
+			char *nargv[10000];
+			char arg1 [10];
+			nargv[0]=argv[0];
+			for (i=1; i<=argc; i++){
+				nargv[i+1]=argv[i];
+			}
+			nargv[1]=arg1;
+			getresuid (&a,&b,&c);
+			snprintf(arg1,8,\"%d\",a);
+			setresuid(c,c,c);
+			execve(\"\$out/libexec/xlaunch\", nargv, envp);
+		}
+EOF
+		mkdir -p \$out/bin
+		mkdir -p \$out/libexec
+		gcc realizeuid.c -o \$out/bin/xlaunch
+		echo '#! ${stdenv.shell}
+			USER=\$(egrep '\\''^[-a-z0-9A-Z_]*:[^:]*:'\\''\$1'\\'':'\\'' /etc/passwd | sed -e '\\''s/:.*//'\\'' )
+			shift
+			case \"\$1\" in 
+				:*) export _display=\"\$1\"; 
+				shift
+			esac
+			_display=\${_display:-:0}
+			_display=\${_display#:}
+			echo Using :\$_display
+			XCMD=\"\$(egrep \"^env\" /etc/event.d/xserver | sed -e \"s/env/ export /\" | sed -e '\\''s/#.*//'\\'' ; echo export _XARGS_=\\\$\\( grep xserver_arguments \\\$SLIM_CFGFILE \\| sed -e s/xserver_arguments// \\| sed -e s/:0/:\${_display}/ \\| sed -e s/vt7/vt\$((7+_display))/ \\) ; echo ${xorgserver}/bin/X \\\$_XARGS_ )\" 
+			echo \"\$XCMD\" 
+			echo \"\$XCMD\" | bash &
+			while ! test -e /tmp/.X11-unix/X\$_display &>/dev/null ; do sleep 0.5; done
+			su -l \${USER:-identityless-shelter} -c \"DISPLAY=:\$_display \$*\";
+		' >\$out/libexec/xlaunch
+		chmod a+x \$out/libexec/xlaunch
+	";
+}
diff --git a/pkgs/tools/X11/xmacro/default.nix b/pkgs/tools/X11/xmacro/default.nix
index c1f039a9215..4cceb720e19 100644
--- a/pkgs/tools/X11/xmacro/default.nix
+++ b/pkgs/tools/X11/xmacro/default.nix
@@ -1,8 +1,8 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "xmacro";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = mirror://sourceforge/xmacro/xmacro-pre0.3-20000911.tar.gz;
     md5 = "d2956b82f3d5380e58a75ccc721fb746";
   };
@@ -11,6 +11,5 @@ args.stdenv.mkDerivation {
 
   preInstall="echo -e 'install:\n	mkdir \${out}/bin;\n	cp xmacrorec xmacrorec2 xmacroplay \${out}/bin;' >>Makefile; ";
 
-  buildInputs = (with args; 
-	[libX11 libXtst xextproto libXi inputproto]);
+  buildInputs = [libX11 libXtst xextproto libXi inputproto];
 }
diff --git a/pkgs/tools/archivers/cabextract/default.nix b/pkgs/tools/archivers/cabextract/default.nix
index e7f9a5a5da0..a87c02c7d04 100644
--- a/pkgs/tools/archivers/cabextract/default.nix
+++ b/pkgs/tools/archivers/cabextract/default.nix
@@ -3,7 +3,7 @@
 stdenv.mkDerivation {
   name = "cabextract-1.2";
   src = fetchurl {
-    url = http://www.kyz.uklinux.net/downloads/cabextract-1.2.tar.gz;
-    md5 = "dc421a690648b503265c82ade84e143e";
+    url = http://www.cabextract.org.uk/cabextract-1.2.tar.gz;
+    sha256 = "1sr5f7qicj5q2h5m4wbmfcaaqxg5zkl5vkxlhyc11spwfh58d75f";
   };
 }
diff --git a/pkgs/tools/archivers/cpio/default.nix b/pkgs/tools/archivers/cpio/default.nix
index 225bc557350..cb9ee9e7f06 100644
--- a/pkgs/tools/archivers/cpio/default.nix
+++ b/pkgs/tools/archivers/cpio/default.nix
@@ -1,10 +1,9 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "cpio-2.7";
+  name = "cpio-2.9";
   src = fetchurl {
-    url = http://ftp.gnu.org/gnu/cpio/cpio-2.7.tar.bz2;
-    md5 = "69ad6cb3d288aafe5f969f68d9fd0fb7";
+    url = mirror://gnu/cpio/cpio-2.9.tar.bz2;
+    sha256 = "01s7f9hg8kgpis96j99hgkiqgdy53pm7qi7bhm3fzx58jfk5z6mv";
   };
-  patches = [./symlink.patch ./gnulib-futimens.patch];
 }
diff --git a/pkgs/tools/archivers/cpio/gnulib-futimens.patch b/pkgs/tools/archivers/cpio/gnulib-futimens.patch
deleted file mode 100644
index 11703d5706d..00000000000
--- a/pkgs/tools/archivers/cpio/gnulib-futimens.patch
+++ /dev/null
@@ -1,30 +0,0 @@
-now hat glibc-2.6  declares futimens.
-http://lists.gnu.org/archive/html/bug-gnulib/2007-05/msg00089.html
-
-diff -ru cpio-2.7.orig/lib/utimens.c cpio-2.7/lib/utimens.c
---- cpio-2.7.orig/lib/utimens.c	2007-05-20 21:23:57.000000000 +0900
-+++ cpio-2.7/lib/utimens.c	2007-05-21 08:40:22.000000000 +0900
-@@ -73,7 +73,7 @@
-    Return 0 on success, -1 (setting errno) on failure.  */
- 
- int
--futimens (int fd ATTRIBUTE_UNUSED,
-+gl_futimens (int fd ATTRIBUTE_UNUSED,
- 	  char const *file, struct timespec const timespec[2])
- {
-   /* There's currently no interface to set file timestamps with
-@@ -166,5 +166,5 @@
- int
- utimens (char const *file, struct timespec const timespec[2])
- {
--  return futimens (-1, file, timespec);
-+  return gl_futimens (-1, file, timespec);
- }
-diff -ru cpio-2.7.orig/lib/utimens.h cpio-2.7/lib/utimens.h
---- cpio-2.7.orig/lib/utimens.h	2007-05-20 21:23:57.000000000 +0900
-+++ cpio-2.7/lib/utimens.h	2007-05-21 08:39:57.000000000 +0900
-@@ -1,3 +1,3 @@
- #include "timespec.h"
--int futimens (int, char const *, struct timespec const [2]);
-+int gl_futimens (int, char const *, struct timespec const [2]);
- int utimens (char const *, struct timespec const [2]);
diff --git a/pkgs/tools/archivers/cpio/symlink.patch b/pkgs/tools/archivers/cpio/symlink.patch
deleted file mode 100644
index 89f82daa522..00000000000
--- a/pkgs/tools/archivers/cpio/symlink.patch
+++ /dev/null
@@ -1,13 +0,0 @@
-http://lists.gnu.org/archive/html/bug-cpio/2006-11/msg00003.html
-
-diff -Ndpru cpio-2.7/src/copyout.c cpio-2.7.fixed/src/copyout.c
---- cpio-2.7/src/copyout.c      2006-09-27 02:19:44.000000000 -0600
-+++ cpio-2.7.fixed/src/copyout.c        2006-11-12 18:58:25.000000000 -0700
-@@ -806,6 +806,7 @@ process_copy_out ()
-		    free (link_name);
-		    continue;
-		  }
-+               link_name[link_size] = '\0';
-		cpio_safer_name_suffix (link_name, false,
-					!no_abs_paths_flag, true);
-		link_size = strlen (link_name);
diff --git a/pkgs/tools/archivers/gnutar/default.nix b/pkgs/tools/archivers/gnutar/default.nix
index c8d77071123..7242f32f71c 100644
--- a/pkgs/tools/archivers/gnutar/default.nix
+++ b/pkgs/tools/archivers/gnutar/default.nix
@@ -1,10 +1,17 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "gnutar-1.16.1";
+  name = "gnutar-1.19";
+  
   src = fetchurl {
-    url = mirror://gnu/tar/tar-1.16.1.tar.bz2;
-    md5 = "d51593461c5ef1f7e37134f22338bb9e";
+    url = mirror://gnu/tar/tar-1.19.tar.bz2;
+    sha256 = "1d4wh27wlgryz3ld6gp6fn56knh7dmny93bmgixy07kvlxnx9466";
+  };
+  
+  patches = [./implausible.patch];
+
+  meta = {
+    homepage = http://www.gnu.org/software/grep/;
+    description = "GNU implementation of the tar archiver";
   };
-  patches = [./implausible.patch ./gnulib-futimens.patch];
 }
diff --git a/pkgs/tools/archivers/gnutar/gnulib-futimens.patch b/pkgs/tools/archivers/gnutar/gnulib-futimens.patch
deleted file mode 100644
index 00cdf9322e6..00000000000
--- a/pkgs/tools/archivers/gnutar/gnulib-futimens.patch
+++ /dev/null
@@ -1,42 +0,0 @@
-now hat glibc-2.6  declares futimens.
-http://lists.gnu.org/archive/html/bug-gnulib/2007-05/msg00089.html
-
-diff -ru cpio-2.7.orig/lib/utimens.c cpio-2.7/lib/utimens.c
---- cpio-2.7.orig/lib/utimens.c	2007-05-20 21:23:57.000000000 +0900
-+++ cpio-2.7/lib/utimens.c	2007-05-21 08:40:22.000000000 +0900
-@@ -73,7 +73,7 @@
-    Return 0 on success, -1 (setting errno) on failure.  */
- 
- int
--futimens (int fd ATTRIBUTE_UNUSED,
-+gl_futimens (int fd ATTRIBUTE_UNUSED,
- 	  char const *file, struct timespec const timespec[2])
- {
-   /* There's currently no interface to set file timestamps with
-@@ -166,5 +166,5 @@
- int
- utimens (char const *file, struct timespec const timespec[2])
- {
--  return futimens (-1, file, timespec);
-+  return gl_futimens (-1, file, timespec);
- }
-diff -ru cpio-2.7.orig/lib/utimens.h cpio-2.7/lib/utimens.h
---- cpio-2.7.orig/lib/utimens.h	2007-05-20 21:23:57.000000000 +0900
-+++ cpio-2.7/lib/utimens.h	2007-05-21 08:39:57.000000000 +0900
-@@ -1,3 +1,3 @@
- #include "timespec.h"
--int futimens (int, char const *, struct timespec const [2]);
-+int gl_futimens (int, char const *, struct timespec const [2]);
- int utimens (char const *, struct timespec const [2]);
-diff -ur tar-1.16.1.orig/src/misc.c tar-1.16.1/src/misc.c
---- tar-1.16.1.orig/src/misc.c	2007-05-21 08:57:02.000000000 +0900
-+++ tar-1.16.1/src/misc.c	2007-05-21 08:57:16.000000000 +0900
-@@ -518,7 +518,7 @@
-     }
- #endif
- 
--  return futimens (fd, file, timespec);
-+  return gl_futimens (fd, file, timespec);
- }
- 
- /* A description of a working directory.  */
diff --git a/pkgs/tools/archivers/p7zip/default.nix b/pkgs/tools/archivers/p7zip/default.nix
index c9d97033500..00bc47878f4 100644
--- a/pkgs/tools/archivers/p7zip/default.nix
+++ b/pkgs/tools/archivers/p7zip/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "p7zip-4.53";
+  name = "p7zip-4.57";
   
   src = fetchurl {
-    url = mirror://sourceforge/p7zip/p7zip_4.53_src_all.tar.bz2;
-    sha256 = "0pbgvpq852qnzq4isgc13p4nnp416xhy5vmn1rcwm8fk43l5rbqd";
+    url = mirror://sourceforge/p7zip/p7zip_4.57_src_all.tar.bz2;
+    sha256 = "0lsvw1bh6dzpxn8kyl7s79w2drpfxaa1c79khqm56gfmdlw27s80";
   };
   
   preConfigure = "
diff --git a/pkgs/tools/archivers/sharutils/4.6.3.nix b/pkgs/tools/archivers/sharutils/4.6.3.nix
new file mode 100644
index 00000000000..830c2a072b6
--- /dev/null
+++ b/pkgs/tools/archivers/sharutils/4.6.3.nix
@@ -0,0 +1,13 @@
+args: with args;
+stdenv.mkDerivation rec {
+  name = "sharutils-" + version;
+
+  src = fetchurl {
+    url = "mirror://gnu/sharutils/REL-${version}/${name}.tar.bz2";
+    sha256 = "1sirrzas8llcsd8gnh56pns39wa1f803vff1kmy5islfi1p9vqk8";
+  };
+
+  meta = {
+    homepage = http://www.gnu.org/software/sharutils;
+  };
+}
diff --git a/pkgs/tools/archivers/unzip/default.nix b/pkgs/tools/archivers/unzip/default.nix
index e19e564a421..a690a8e7163 100644
--- a/pkgs/tools/archivers/unzip/default.nix
+++ b/pkgs/tools/archivers/unzip/default.nix
@@ -7,4 +7,8 @@ stdenv.mkDerivation {
     url = http://nix.cs.uu.nl/dist/tarballs/unzip552.tar.gz;
     md5 = "9d23919999d6eac9217d1f41472034a9";
   };
+
+  meta = {
+	  homepage = http://www.info-zip.org;
+  };
 }
diff --git a/pkgs/tools/archivers/zip/default.nix b/pkgs/tools/archivers/zip/default.nix
index 51a1b618e02..9498bf089ff 100644
--- a/pkgs/tools/archivers/zip/default.nix
+++ b/pkgs/tools/archivers/zip/default.nix
@@ -2,7 +2,11 @@
   name = "zip-2.32";
   builder = ./builder.sh;
   src = fetchurl {
-    url = http://ftp.info-zip.org/pub/infozip/src/zip232.tar.gz;
+    url = ftp://ftp.info-zip.org/pub/infozip/src/zip232.tgz;
     md5 = "8a4da4460386e324debe97f3b7fe4d96";
   };
+
+  meta = {
+    homepage = http://www.info-zip.org;
+  };
 }
diff --git a/pkgs/tools/backup/rdiff-backup/default.nix b/pkgs/tools/backup/rdiff-backup/default.nix
index 43fd17a6178..8cd660adc8c 100644
--- a/pkgs/tools/backup/rdiff-backup/default.nix
+++ b/pkgs/tools/backup/rdiff-backup/default.nix
@@ -1,8 +1,8 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "rdiff-backup-1.1.14";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://savannah.nongnu.org/download/rdiff-backup/rdiff-backup-1.1.14.tar.gz;
     sha256 = "0sh2kz90z47yfa9786dyn3q9ba1xcmjvd65rykvm7mg5apnrg27h";
   };
@@ -14,7 +14,7 @@ args.stdenv.mkDerivation {
     
   ";
 
-  buildInputs = (with args; [python librsync gnused ]);
+  buildInputs = [python librsync gnused ];
 
   meta = {
       description = "backup system trying to combine best a mirror and an incremental backup system";
diff --git a/pkgs/tools/compression/bzip2/default.nix b/pkgs/tools/compression/bzip2/default.nix
index 1a5dd61803a..9ed3e941bf6 100644
--- a/pkgs/tools/compression/bzip2/default.nix
+++ b/pkgs/tools/compression/bzip2/default.nix
@@ -11,4 +11,7 @@ stdenv.mkDerivation {
 
   sharedLibrary =
     !stdenv.isDarwin && !(stdenv ? isDietLibC) && stdenv.system != "i686-cygwin";
+  meta = {
+    homepage = http://www.bzip.org;
+  };
 }
diff --git a/pkgs/tools/compression/gzip/default.nix b/pkgs/tools/compression/gzip/default.nix
index 58d6e8b9707..0a2afd05372 100644
--- a/pkgs/tools/compression/gzip/default.nix
+++ b/pkgs/tools/compression/gzip/default.nix
@@ -2,9 +2,16 @@
 
 stdenv.mkDerivation {
   name = "gzip-1.3.12";
+  
   src = fetchurl {
     url = http://ftp.gnu.org/gnu/gzip/gzip-1.3.12.tar.gz;
     sha256 = "1bw7sm68xjlnlzgcx66hnw80ac1qqyvhw0vw27zilgbzbzh5nmiz";
   };
-	patches = [./gnulib-futimens.patch];
+
+  meta = {
+    homepage = http://www.gzip.org/;
+    description = "The gzip compression program";
+  };
+  
+  patches = [./gnulib-futimens.patch];
 }
diff --git a/pkgs/tools/compression/lzma/default.nix b/pkgs/tools/compression/lzma/default.nix
new file mode 100644
index 00000000000..67ef9c3add1
--- /dev/null
+++ b/pkgs/tools/compression/lzma/default.nix
@@ -0,0 +1,18 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "lzma-4.32.5";
+  
+  src = fetchurl {
+    url = http://tukaani.org/lzma/lzma-4.32.5.tar.gz;
+    sha256 = "1mqy1biy46gqky6n3gyr2l395hwckh0xyi96waz5p5x8mgp372ch";
+  };
+
+  CFLAGS = "-O3";
+  CXXFLAGS = "-O3";
+
+  meta = {
+    homepage = http://tukaani.org/lzma/;
+    description = "The LZMA compression program";
+  };
+}
diff --git a/pkgs/tools/compression/zdelta/default.nix b/pkgs/tools/compression/zdelta/default.nix
index 8bd6d8a0e16..a07deac4148 100644
--- a/pkgs/tools/compression/zdelta/default.nix
+++ b/pkgs/tools/compression/zdelta/default.nix
@@ -1,10 +1,14 @@
 {stdenv, fetchurl}:
 
-stdenv.mkDerivation {
+stdenv.mkDerivation rec {
   name = "zdelta-2.1";
   builder = ./builder.sh;
   src = fetchurl {
-    url = http://cis.poly.edu/zdelta/downloads/zdelta-2.1.tar.gz;
+    url = "${meta.homepage}/downloads/${name}.tar.gz";
     md5 = "c69583a64f42f69a39e297d0d27d77e5";
   };
+
+  meta = {
+	  homepage = http://cis.poly.edu/zdelta;
+  };
 }
diff --git a/pkgs/tools/graphics/exif/default.nix b/pkgs/tools/graphics/exif/default.nix
index aa4d82468c3..94bf2e2cb0d 100644
--- a/pkgs/tools/graphics/exif/default.nix
+++ b/pkgs/tools/graphics/exif/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl, pkgconfig, libexif, popt}:
 
 stdenv.mkDerivation {
-  name = "exif-0.6.9";
+  name = "exif-0.6.15";
 
   src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/exif-0.6.9.tar.gz;
-    md5 = "555029098386fa677c461eb249d852d7";
+    url = mirror://sourceforge/libexif/exif-0.6.15.tar.bz2;
+    sha256 = "19kxl72l1iqq747k58rir7v4ld1676j3dmjdc1pik9hjlgdb1yj1";
   };
 
   buildInputs = [pkgconfig libexif popt];
diff --git a/pkgs/tools/graphics/graphviz/default.nix b/pkgs/tools/graphics/graphviz/default.nix
index b424672ed41..abde6da66d6 100644
--- a/pkgs/tools/graphics/graphviz/default.nix
+++ b/pkgs/tools/graphics/graphviz/default.nix
@@ -3,11 +3,11 @@
 assert libpng != null && libjpeg != null && expat != null;
 
 stdenv.mkDerivation {
-  name = "graphviz-2.12";
+  name = "graphviz-2.16.1";
 
   src = fetchurl {
-    url = http://www.graphviz.org/pub/graphviz/ARCHIVE/graphviz-2.12.tar.gz;
-    md5 = "e5547bc0ec47943c72f5c3e2b5dff58f";
+    url = http://www.graphviz.org/pub/graphviz/ARCHIVE/graphviz-2.16.1.tar.gz;
+    sha256 = "1lan1hyar0xbqvnkcmlcvv02g8zfpk94gk04y4sik5irpa2s3h9j";
   };
 
   buildInputs = [x11 libpng libjpeg expat libXaw yacc libtool];
@@ -19,5 +19,10 @@ stdenv.mkDerivation {
       "--with-expatincludedir=${expat}/include"
       "--with-expatlibdir=${expat}/lib"
     ]
-    ++ (if x11 == null then ["--without-x"] else []);
+    ++ stdenv.lib.optional (x11 == null) "--without-x";
+
+  meta = {
+    description = "A program for visualising graphs";
+    homepage = http://www.graphviz.org/;
+  };
 }
diff --git a/pkgs/tools/hddtemp/default.nix b/pkgs/tools/hddtemp/default.nix
new file mode 100644
index 00000000000..9f285a6cd51
--- /dev/null
+++ b/pkgs/tools/hddtemp/default.nix
@@ -0,0 +1,25 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "hddtemp-0.3-beta15";
+
+  db = fetchurl{
+              url = http://download.savannah.nongnu.org/releases/hddtemp/hddtemp.db;
+              sha256 = "1fr6qgns6qv7cr40lic5yqwkkc7yjmmgx8j0z6d93csg3smzhhya";
+       };
+  src = fetchurl {
+            url = http://download.savannah.nongnu.org/releases/hddtemp/hddtemp-0.3-beta15.tar.bz2;
+            sha256 = "0nzgg4nl8zm9023wp4dg007z6x3ir60rwbcapr9ks2al81c431b1";
+  };
+
+  configurePhase = "
+    ensureDir \$out/nix-support
+    cp \$db \$out/nix-support/hddtemp.db
+    ./configure --prefix=\$out --with-db-path=\$out/nix-support/hddtemp.db
+  "; 
+
+  meta = { 
+      description = "shows the harddisk temperature";
+      homepage = https://savannah.nongnu.org/projects/hddtemp/;
+      license = "GPL2";
+  };
+}
diff --git a/pkgs/tools/misc/coreutils/default.nix b/pkgs/tools/misc/coreutils/default.nix
index 770a1dbfbc9..8292c56f0ea 100644
--- a/pkgs/tools/misc/coreutils/default.nix
+++ b/pkgs/tools/misc/coreutils/default.nix
@@ -1,10 +1,15 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "coreutils-6.9";
+  name = "coreutils-6.10";
+  
   src = fetchurl {
-    url = mirror://gnu/coreutils/coreutils-6.9.tar.bz2;
-    sha256 = "1c4p2kiy4m024qcl1przvphy8vhivf8jvclq6bjm1pjps5d8khl9";
+    url = mirror://gnu/coreutils/coreutils-6.10.tar.gz;
+    sha256 = "0zpbxfl16sq45s53fxw43i9i8lrdcc845714c1j5f84zi13ka08x";
+  };
+
+  meta = {
+    homepage = http://www.gnu.org/software/coreutils/;
+    description = "The basic file, shell and text manipulation utilities of the GNU operating system";
   };
-  patches = [ ./gnulib-futimens.patch ] ;
 }
diff --git a/pkgs/tools/misc/dosfstools/2.11deb.nix b/pkgs/tools/misc/dosfstools/2.11deb.nix
new file mode 100644
index 00000000000..13f327dcff5
--- /dev/null
+++ b/pkgs/tools/misc/dosfstools/2.11deb.nix
@@ -0,0 +1,33 @@
+args : with args; with builderDefs {src="";} null;
+    let patch = 
+        fetchurl {
+          url = http://ftp.de.debian.org/debian/pool/main/d/dosfstools/dosfstools_2.11-2.3.diff.gz;
+          sha256 = "0bzjhpgg4ih6c76ax8byis9vxgkr2c7bbbshqrkfq8j7ar48n5ld";
+        };	
+      localDefs = builderDefs (rec {
+        src = /* put a fetchurl here */
+          fetchurl {
+            url = http://ftp.de.debian.org/debian/pool/main/d/dosfstools/dosfstools_2.11.orig.tar.gz;
+            sha256 = "1154k0y04npblgac81p4pcmglilk1ldrqll4hvbrwgcb7096vb0f";
+          };
+	preBuild = FullDepEntry (''
+	  gunzip < ${patch} | patch -Np1
+	'')["minInit" "doUnpack"];
+
+        buildInputs = [];
+        configureFlags = [];
+	makeFlags = " PREFIX=$out ";
+    }) null; /* null is a terminator for sumArgs */
+    in with localDefs;
+stdenv.mkDerivation rec {
+    name = "dosfstools-"+version;
+    builder = writeScript (name + "-builder")
+        (textClosure localDefs 
+            [preBuild "doMakeInstall" doForceShare doPropagate]);
+    meta = {
+        description = "
+        Dosfstools - utilities for vfat file system.
+";
+	homepage = "http://sixpak.org/dosfstools/dosfstools-2.8vb2.tar.gz";
+    };
+}
diff --git a/pkgs/tools/misc/file/default.nix b/pkgs/tools/misc/file/default.nix
index d7e31e9cf32..cf4919d3c8f 100644
--- a/pkgs/tools/misc/file/default.nix
+++ b/pkgs/tools/misc/file/default.nix
@@ -1,9 +1,14 @@
 {stdenv, fetchurl}:
  
 stdenv.mkDerivation {
-  name = "file-4.17";
+  name = "file-4.23";
   src = fetchurl {
-    url = ftp://ftp.astron.com/pub/file/file-4.17.tar.gz;
-    md5 = "50919c65e0181423d66bb25d7fe7b0fd";
+    url = ftp://ftp.astron.com/pub/file/file-4.23.tar.gz;
+    sha256 = "0iyiyzcs88k6r881l11zrg86ys3rnwjyh1bgx7hnfyjv8zk9db9g";
+  };
+
+  meta = {
+    description = "A program that shows the type of files";
+    homepage = ftp://ftp.astron.com/pub/file;
   };
 }
diff --git a/pkgs/tools/misc/findutils/default.nix b/pkgs/tools/misc/findutils/default.nix
index 812b0c78e2c..acfbf90d946 100644
--- a/pkgs/tools/misc/findutils/default.nix
+++ b/pkgs/tools/misc/findutils/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, coreutils}:
 
 stdenv.mkDerivation {
-  name = "findutils-4.2.30";
+  name = "findutils-4.2.32";
   src = fetchurl {
-    url = mirror://gnu/findutils/findutils-4.2.30.tar.gz;
-    sha256 = "1x1s0h1gf4hxh6xi6vq336sz8zsh4hvnsslc7607z41l82xrqjrl";
+    url = mirror://gnu/findutils/findutils-4.2.32.tar.gz;
+    sha256 = "05sj0154kl4mbqg7dcabiaa16snjv2ppfwwhcvl2zyn2yc28igc7";
   };
   buildInputs = [coreutils];
 
@@ -12,4 +12,9 @@ stdenv.mkDerivation {
     # Note: the dietlibc patch is just to get findutils to compile.
     # The locate command probably won't work though.
     ++ stdenv.lib.optional (stdenv ? isDietLibC) ./dietlibc-hack.patch;
+
+  meta = {
+    homepage = http://www.gnu.org/software/findutils/;
+    description = "The basic directory searching utilities of the GNU operating system";
+  };
 }
diff --git a/pkgs/tools/misc/grub/default.nix b/pkgs/tools/misc/grub/default.nix
index 0a406f72b46..9f021a66955 100644
--- a/pkgs/tools/misc/grub/default.nix
+++ b/pkgs/tools/misc/grub/default.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl}:
+{stdenv, fetchurl, autoconf, automake}:
 
 if stdenv.system == "x86_64-linux" then
   abort "Grub doesn't build on x86_64-linux.  You should use the build for i686-linux instead."
@@ -6,8 +6,30 @@ else
 
 stdenv.mkDerivation {
   name = "grub-0.97";
+  
   src = fetchurl {
     url = ftp://alpha.gnu.org/gnu/grub/grub-0.97.tar.gz;
     md5 = "cd3f3eb54446be6003156158d51f4884";
   };
+
+  # Lots of patches from Gentoo, in particular splash screen support
+  # (not the fancy SUSE gfxmenu stuff though).  Also a fix for boot
+  # failures on systems with more than 2 GiB RAM.
+  gentooPatches = fetchurl {
+    url = mirror://gentoo/distfiles/grub-0.97-patches-1.4.tar.bz2;
+    sha256 = "1nki5q1b61ahxcmnw6mq7b8ghcysri4lj7q6dx8iqixrvrpxj399";
+  };
+
+  # Autoconf/automake required for the splashimage patch.
+  buildInputs = [autoconf automake];
+
+  preConfigure = ''
+    unpackFile $gentooPatches
+    rm patch/400_all_grub-0.97-reiser4-20050808-gentoo.patch
+    for i in patch/*.patch; do
+      echo "applying patch $i"
+      patch -p1 < $i || patch -p0 < $i
+    done
+    autoreconf
+  '';
 }
diff --git a/pkgs/tools/misc/less/default.nix b/pkgs/tools/misc/less/default.nix
index ad7fe970d31..f4a7bc0cf5d 100644
--- a/pkgs/tools/misc/less/default.nix
+++ b/pkgs/tools/misc/less/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl, ncurses}:
  
 stdenv.mkDerivation {
-  name = "less-394";
+  name = "less-418";
  
   src = fetchurl {
-    url = http://www.greenwoodsoftware.com/less/less-394.tar.gz;
-    md5 = "a9f072ccefa0d315b325f3e9cdbd4b97";
+    url = http://www.greenwoodsoftware.com/less/less-418.tar.gz;
+    sha256 = "1d03n4wx8y1gmf2m8yawzg6ixmfrixcai5l14p9pj8q13gbgqcpm";
   };
  
   buildInputs = [ncurses];
diff --git a/pkgs/tools/misc/man-db/default.nix b/pkgs/tools/misc/man-db/default.nix
new file mode 100644
index 00000000000..54367e671ea
--- /dev/null
+++ b/pkgs/tools/misc/man-db/default.nix
@@ -0,0 +1,32 @@
+{stdenv, fetchurl, db4, groff}:
+ 
+stdenv.mkDerivation {
+  name = "man-db-2.5.1";
+  
+  src = fetchurl {
+    url = http://download.savannah.nongnu.org/releases/man-db/man-db-2.5.1.tar.gz;
+    sha256 = "178w1fk23ffh8vabj29cn0yyg5ps7bwy1zrrrcsw8aypbh3sfjy3";
+  };
+  
+  buildInputs = [db4 groff];
+  
+  configureFlags = ''
+    --disable-setuid
+    --with-nroff=${groff}/bin/nroff
+    --with-tbl=${groff}/bin/tbl
+    --with-eqn=${groff}/bin/eqn
+    --with-neqn=${groff}/bin/neqn
+  '';
+
+  troff = "${groff}/bin/troff";
+  
+  patches = [
+    # Search in "share/man" relative to each path in $PATH (in addition to "man").
+    ./share.patch
+  ];
+
+  meta = {
+    homepage = http://www.nongnu.org/man-db/;
+    description = "An implementation of the standard Unix documentation system accessed using the man command";
+  };
+}
diff --git a/pkgs/tools/misc/man-db/share.patch b/pkgs/tools/misc/man-db/share.patch
new file mode 100644
index 00000000000..95582a50269
--- /dev/null
+++ b/pkgs/tools/misc/man-db/share.patch
@@ -0,0 +1,110 @@
+diff -rc man-db-2.5.1-orig/src/manp.c man-db-2.5.1/src/manp.c
+*** man-db-2.5.1-orig/src/manp.c	2008-01-07 03:23:11.000000000 +0100
+--- man-db-2.5.1/src/manp.c	2008-02-07 14:20:20.000000000 +0100
+***************
+*** 96,102 ****
+  
+  static void mkcatdirs (const char *mandir, const char *catdir);
+  static inline char *get_manpath_from_path (const char *path);
+! static inline char *has_mandir (const char *p);
+  static inline char *fsstnd (const char *path);
+  static char *def_path (int flag);
+  static void add_dir_to_list (char **lp, const char *dir);
+--- 96,102 ----
+  
+  static void mkcatdirs (const char *mandir, const char *catdir);
+  static inline char *get_manpath_from_path (const char *path);
+! static inline char *has_mandir (const char *p, const char *mandir);
+  static inline char *fsstnd (const char *path);
+  static char *def_path (int flag);
+  static void add_dir_to_list (char **lp, const char *dir);
+***************
+*** 928,934 ****
+  		} else {
+  			debug ("is not in the config file\n");
+  
+! 		 	t = has_mandir (p);
+  		 	if (t) {
+  				debug ("but does have a ../man or man "
+  				       "subdirectory\n");
+--- 928,934 ----
+  		} else {
+  			debug ("is not in the config file\n");
+  
+! 		 	t = has_mandir (p, "man");
+  		 	if (t) {
+  				debug ("but does have a ../man or man "
+  				       "subdirectory\n");
+***************
+*** 938,943 ****
+--- 938,952 ----
+  		 	} else
+  				debug ("and doesn't have ../man or man "
+  				       "subdirectories\n");
++  
++  		 	t = has_mandir (p, "share/man");
++  		 	if (t) {
++                                 debug ("but does have a ../share/man or share/man subdirectory\n");
++  	
++  				add_dir_to_list (tmplist, t);
++  				free (t);
++  		 	} else
++  				debug ("and doesn't have ../share/man or share/man subdirectories\n");
+  		}
+  	}
+  
+***************
+*** 1013,1019 ****
+  
+  /* path does not exist in config file: check to see if path/../man or 
+     path/man exist.  If so return it, if not return NULL. */
+! static inline char *has_mandir (const char *path)
+  {
+  	char *newpath = NULL;
+  
+--- 1022,1028 ----
+  
+  /* path does not exist in config file: check to see if path/../man or 
+     path/man exist.  If so return it, if not return NULL. */
+! static inline char *has_mandir (const char *path, const char *mandir)
+  {
+  	char *newpath = NULL;
+  
+***************
+*** 1023,1031 ****
+  	char *subdir = strrchr (path, '/');
+  	if (subdir) {
+  		const int prefix_len = subdir + 1 - path;
+! 		newpath = xmalloc (prefix_len + sizeof ("man") + 1);
+  		strncpy (newpath, path, prefix_len);
+! 		strcpy (newpath + prefix_len, "man");
+  
+  		if (is_directory (newpath) == 1)
+  			return newpath;
+--- 1032,1040 ----
+  	char *subdir = strrchr (path, '/');
+  	if (subdir) {
+  		const int prefix_len = subdir + 1 - path;
+! 		newpath = xmalloc (prefix_len + strlen (mandir) + 2);
+  		strncpy (newpath, path, prefix_len);
+! 		strcpy (newpath + prefix_len, mandir);
+  
+  		if (is_directory (newpath) == 1)
+  			return newpath;
+***************
+*** 1033,1039 ****
+  			*newpath = '\0';
+  	}
+  
+! 	newpath = appendstr (newpath, path, "/man", NULL);
+  
+  	if (is_directory (newpath) == 1)
+  		return newpath;
+--- 1042,1048 ----
+  			*newpath = '\0';
+  	}
+  
+! 	newpath = appendstr (newpath, path, "/", mandir, NULL);
+  
+  	if (is_directory (newpath) == 1)
+  		return newpath;
diff --git a/pkgs/tools/misc/man/default.nix b/pkgs/tools/misc/man/default.nix
index deb0f83ad8a..490aa4606ab 100644
--- a/pkgs/tools/misc/man/default.nix
+++ b/pkgs/tools/misc/man/default.nix
@@ -1,15 +1,26 @@
-{stdenv, fetchurl, db4, groff}:
+{stdenv, fetchurl, groff, less}:
  
 stdenv.mkDerivation {
-  name = "man-2.4.3";
+  name = "man-1.6f";
+  
   src = fetchurl {
-    url = http://savannah.nongnu.org/download/man-db/man-db-2.4.3.tar.gz;
-    md5 = "30814a47f209f43b152659ba51fc7937";
+    url = http://primates.ximian.com/~flucifredi/man/man-1.6f.tar.gz;
+    sha256 = "0v2z6ywhy8kd2fa3ywkqayhjdivbaqn6qvhx93a1ldw135z8q84z";
   };
-  buildInputs = [db4 groff];
-  configureFlags = "--disable-setuid";
+  
+  buildInputs = [groff less];
+
+  preBuild = ''
+    makeFlagsArray=(bindir=$out/bin sbindir=$out/sbin libdir=$out/lib mandir=$out/share/man)
+  '';
+
   patches = [
     # Search in "share/man" relative to each path in $PATH (in addition to "man").
     ./share.patch
   ];
+
+  meta = {
+    homepage = http://primates.ximian.com/~flucifredi/man/;
+    description = "Tool to read online Unix documentation";
+  };
 }
diff --git a/pkgs/tools/misc/man/share.patch b/pkgs/tools/misc/man/share.patch
index 3367f4ceb61..837786e28eb 100644
--- a/pkgs/tools/misc/man/share.patch
+++ b/pkgs/tools/misc/man/share.patch
@@ -1,113 +1,116 @@
-diff -rc man-db-2.4.3/src/manp.c man-db-2.4.3-new/src/manp.c
-*** man-db-2.4.3/src/manp.c	Mon Nov  8 10:06:03 2004
---- man-db-2.4.3-new/src/manp.c	Tue Jan  9 17:08:31 2007
+diff -rc man-1.6f-orig/src/manpath.c man-1.6f/src/manpath.c
+*** man-1.6f-orig/src/manpath.c	2006-08-03 23:18:33.000000000 +0200
+--- man-1.6f/src/manpath.c	2008-02-07 15:31:43.000000000 +0100
 ***************
-*** 101,107 ****
-  
-  static void mkcatdirs (const char *mandir, const char *catdir);
-  static __inline__ char *get_manpath (char *path);
-! static __inline__ char *has_mandir (const char *p);
-  static __inline__ char *fsstnd (const char *path);
-  static char *def_path (int flag);
-  static void add_dir_to_list (char **lp, const char *dir);
---- 101,107 ----
-  
-  static void mkcatdirs (const char *mandir, const char *catdir);
-  static __inline__ char *get_manpath (char *path);
-! static __inline__ char *has_mandir (const char *p, const char *mandir);
-  static __inline__ char *fsstnd (const char *path);
-  static char *def_path (int flag);
-  static void add_dir_to_list (char **lp, const char *dir);
-***************
-*** 885,891 ****
-  			if (debug)
-  				fputs ("is not in the config file\n", stderr);
-  
-! 		 	t = has_mandir (p);
-  		 	if (t) {
-  				if (debug)
-  					fprintf (stderr, "but does have a ../man or man subdirectory\n");
---- 885,891 ----
-  			if (debug)
-  				fputs ("is not in the config file\n", stderr);
-  
-! 		 	t = has_mandir (p, "man");
-  		 	if (t) {
-  				if (debug)
-  					fprintf (stderr, "but does have a ../man or man subdirectory\n");
-***************
-*** 895,900 ****
---- 895,911 ----
-  		 	} else
-  				if (debug)
-  					fprintf (stderr, "and doesn't have ../man or man subdirectories\n");
-+ 
-+ 		 	t = has_mandir (p, "share/man");
-+ 		 	if (t) {
-+ 				if (debug)
-+ 					fprintf (stderr, "but does have a ../share/man or share/man subdirectory\n");
-+ 	
-+ 				add_dir_to_list (tmplist, t);
-+ 				free (t);
-+ 		 	}
-+ 				if (debug)
-+ 					fprintf (stderr, "and doesn't have ../share/man or share/man subdirectories\n");
-  		}
-  	}
+*** 109,121 ****
+   * or ../man or ../man1 or ../man8 subdirectories. 
+   */
+  static char *
+! find_man_subdir (char *p) {
+       int len;
+       char *t, *sp;
   
-***************
-*** 973,979 ****
+       len = strlen (p);
   
-  /* path does not exist in config file: check to see if path/../man or 
-     path/man exist.  If so return it, if not return NULL. */
-! static __inline__ char *has_mandir (const char *path)
-  {
-  	char *newpath = NULL;
+!      t = my_malloc ((unsigned) len + 20);
   
---- 984,990 ----
+       memcpy (t, p, len);
+       strcpy (t + len, "/man");
+--- 109,121 ----
+   * or ../man or ../man1 or ../man8 subdirectories. 
+   */
+  static char *
+! find_man_subdir (char *p, char * maybe_share) {
+       int len;
+       char *t, *sp;
   
-  /* path does not exist in config file: check to see if path/../man or 
-     path/man exist.  If so return it, if not return NULL. */
-! static __inline__ char *has_mandir (const char *path, const char *mandir)
-  {
-  	char *newpath = NULL;
+       len = strlen (p);
   
+!      t = my_malloc ((unsigned) len + 30);
+  
+       memcpy (t, p, len);
+       strcpy (t + len, "/man");
 ***************
-*** 983,991 ****
-  	char *subdir = strrchr (path, '/');
-  	if (subdir) {
-  		const int prefix_len = subdir + 1 - path;
-! 		newpath = xmalloc (prefix_len + sizeof ("man") + 1);
-  		strncpy (newpath, path, prefix_len);
-! 		strcpy (newpath + prefix_len, "man");
-  
-  		if (is_directory (newpath) == 1)
-  			return newpath;
---- 994,1002 ----
-  	char *subdir = strrchr (path, '/');
-  	if (subdir) {
-  		const int prefix_len = subdir + 1 - path;
-! 		newpath = xmalloc (prefix_len + strlen (mandir) + 2);
-  		strncpy (newpath, path, prefix_len);
-! 		strcpy (newpath + prefix_len, mandir);
-  
-  		if (is_directory (newpath) == 1)
-  			return newpath;
-***************
-*** 993,999 ****
-  			*newpath = '\0';
-  	}
+*** 139,159 ****
+       }
+  
+       /* look for the situation with packagedir/bin and packagedir/man */
+!      strcpy (t + len, "/man");
+  
+       if (is_directory (t) == 1)
+  	  return t;
+  
+       /* look for the situation with pkg/bin and pkg/man1 or pkg/man8 */
+       /* (looking for all man[1-9] would probably be a waste of stats) */
+!      strcpy (t + len, "/man1");
+  
+       if (is_directory (t) == 1) {
+  	  t[len] = 0;
+  	  return t;
+       }
   
-! 	newpath = strappend (newpath, path, "/man", NULL);
+!      strcpy (t + len, "/man8");
   
-  	if (is_directory (newpath) == 1)
-  		return newpath;
---- 1004,1010 ----
-  			*newpath = '\0';
-  	}
+       if (is_directory (t) == 1) {
+  	  t[len] = 0;
+--- 139,159 ----
+       }
   
-! 	newpath = strappend (newpath, path, "/", mandir, NULL);
+       /* look for the situation with packagedir/bin and packagedir/man */
+!      sprintf (t + len, "%s/man", maybe_share);
+  
+       if (is_directory (t) == 1)
+  	  return t;
+  
+       /* look for the situation with pkg/bin and pkg/man1 or pkg/man8 */
+       /* (looking for all man[1-9] would probably be a waste of stats) */
+!      sprintf (t + len, "%s/man1", maybe_share);
+  
+       if (is_directory (t) == 1) {
+  	  t[len] = 0;
+  	  return t;
+       }
+  
+!      sprintf (t + len, "%s/man8", maybe_share);
+  
+       if (is_directory (t) == 1) {
+  	  t[len] = 0;
+***************
+*** 341,347 ****
+          if (debug)
+              gripe (IS_NOT_IN_CONFIG);
+            
+!         t = find_man_subdir (dir);
+          if (t != NULL) {
+              if (debug)
+                  gripe (MAN_NEARBY);
+--- 341,347 ----
+          if (debug)
+              gripe (IS_NOT_IN_CONFIG);
+            
+!         t = find_man_subdir (dir, "");
+          if (t != NULL) {
+              if (debug)
+                  gripe (MAN_NEARBY);
+***************
+*** 352,357 ****
+--- 352,370 ----
+              if (debug)
+                  gripe (NO_MAN_NEARBY);
+          }
++ 
++         t = find_man_subdir (dir, "/share");
++         if (t != NULL) {
++             if (debug)
++                 gripe (MAN_NEARBY);
++               
++             add_to_mandirlist (t, perrs);
++             free (t);
++         } else {
++             if (debug)
++                 gripe (NO_MAN_NEARBY);
++         }
++ 
+      }
+  }
   
-  	if (is_directory (newpath) == 1)
-  		return newpath;
-Only in man-db-2.4.3-new/src: manp.c~
diff --git a/pkgs/tools/misc/mc/default.nix b/pkgs/tools/misc/mc/default.nix
new file mode 100644
index 00000000000..8f03756a2d3
--- /dev/null
+++ b/pkgs/tools/misc/mc/default.nix
@@ -0,0 +1,20 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "mc-4.6.1";
+  src = fetchurl {
+    url = "http://www.ibiblio.org/pub/Linux/utils/file/managers/mc/${name}.tar.gz";
+    sha256 = "0zly25mwdn84s0wqx9mzyqi177mm828716nv1n6a4a5cm8yv0sh8";
+  };
+  buildInputs = [pkgconfig glib ncurses libX11 shebangfix perl zip];
+  configureFlags = "--with-screen=ncurses";
+  makeFlags = "UNZIP=unzip";
+  postInstall = ''
+    find $out -iname "*.pl" | xargs shebangfix;
+  '';
+  meta = {
+    description = "File Manager and User Shell for the GNU Project";
+    homepage = http://www.ibiblio.org/mc;
+  };
+}
+
diff --git a/pkgs/tools/misc/memtest86/default.nix b/pkgs/tools/misc/memtest86/default.nix
new file mode 100644
index 00000000000..32f2094b44c
--- /dev/null
+++ b/pkgs/tools/misc/memtest86/default.nix
@@ -0,0 +1,26 @@
+{stdenv, fetchurl}:
+
+stdenv.mkDerivation {
+  name = "memtest86+-1.70";
+  
+  src = fetchurl {
+    url = http://www.memtest.org/download/1.70/memtest86+-1.70.tar.gz;
+    sha256 = "1swj4hc764qwb3j80kvvb4qg5maq9dp8pxzy9jkk187jf92j8vfw";
+  };
+
+  preBuild = ''
+    # Really dirty hack to get Memtest to build without needing a Glibc
+    # with 32-bit libraries and headers.
+    if test "$system" = x86_64-linux; then
+        mkdir gnu
+        touch gnu/stubs-32.h
+    fi
+  '';
+  
+  NIX_CFLAGS_COMPILE = "-I.";
+  
+  installPhase = ''
+    ensureDir $out
+    cp memtest.bin $out/
+  '';
+}
diff --git a/pkgs/tools/misc/mssys/default.nix b/pkgs/tools/misc/mssys/default.nix
new file mode 100644
index 00000000000..a9d32205cea
--- /dev/null
+++ b/pkgs/tools/misc/mssys/default.nix
@@ -0,0 +1,22 @@
+{stdenv, fetchurl, gettext}:
+
+stdenv.mkDerivation {
+  name = "ms-sys-2.1.3";
+  
+  src = fetchurl {
+    url = mirror://sourceforge/ms-sys/ms-sys-2.1.3.tgz;
+    md5 = "6fad0a69ac89440ad4f696dbbbf11497";
+  };
+
+  buildInputs = [gettext];
+
+  preBuild = ''
+    makeFlags=(PREFIX=$out)
+  '';
+
+  meta = {
+    homepage = http://ms-sys.sourceforge.net/;
+    license = "GPL";
+    description = "A program for writing Microsoft compatible boot records";
+  };
+}
diff --git a/pkgs/tools/misc/psmisc/default.nix b/pkgs/tools/misc/psmisc/default.nix
new file mode 100644
index 00000000000..64985a8638c
--- /dev/null
+++ b/pkgs/tools/misc/psmisc/default.nix
@@ -0,0 +1,15 @@
+{stdenv, fetchurl, ncurses}:
+
+stdenv.mkDerivation {
+  name = "psmisc-22.6";
+  src = fetchurl {
+    url = mirror://sourceforge/psmisc/psmisc-22.6.tar.gz;
+    sha256 = "0qlx4rdcj3igk67gzmdbyy6f54h4c5ya17gw0pkxdcwlgj4q2g51";
+  };
+  buildInputs = [ncurses];
+
+  meta = {
+    homepage = http://psmisc.sourceforge.net/;
+    description = "A set of small useful utilities that use the proc filesystem (such as fuser, killall and pstree)";
+  };
+}
diff --git a/pkgs/tools/misc/relfs/cvs.2007.12.01.nix b/pkgs/tools/misc/relfs/cvs.2007.12.01.nix
new file mode 100644
index 00000000000..83beb68151f
--- /dev/null
+++ b/pkgs/tools/misc/relfs/cvs.2007.12.01.nix
@@ -0,0 +1,51 @@
+args : with args;
+	let localDefs = builderDefs {
+	src = /* put a fetchurl here */
+	if args ? src then args.src else fetchcvs {
+		url = ":pserver:anonymous@relfs.cvs.sourceforge.net:/cvsroot/relfs";
+		module = "relfs";
+		date = "2007-12-01";
+		sha256 = "ef8e2ebfda6e43240051a7af9417092b2af50ece8b5c6c3fbd908ba91c4fe068";
+	};
+		
+		buildInputs = [ocaml fuse postgresql pcre
+			e2fsprogs gnomevfs pkgconfig GConf];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+let build = FullDepEntry ("
+	cd deps 
+	sed -e 's/^CPP/#&/ ; s/^# CPP=gcc/CPP=gcc/' -i Makefile.camlidl
+	make 
+	cd ../src
+	sed -e 's/NULL\\|FALSE/0/g' -i Mimetype_lib.c
+	sed -e 's@/usr/local/@'\$out/'@' -i Makefile
+	sed -e '/install:/a\\\tmkdir -p '\$out'/share' -i Makefile
+	make
+	mkdir -p \$out/bin
+	echo '
+		createuser -A -D \$1
+		dropdb relfs_\$1 ; 
+		rm -rf /tmp/relfs-\$1-tmp;  
+		mkdir /tmp/relfs-\$1-tmp;  
+		USER=\$1 relfs -f -s /tmp/relfs-raskin-tmp  & 
+		sleep 1 && 
+		kill -15 \${!};
+		rm -rf /tmp/relfs-\$1-tmp ; 
+		psql -d relfs_\$1 <<< \"ALTER DATABASE relfs_raskin OWNER TO raskin; 
+			ALTER TABLE obj OWNER TO \$1; 
+			ALTER TABLE obj_mimetype OWNER TO \$1; 
+			ALTER TABLE membership OWNER TO \$1;\"' > \$out/bin/relfs_grant;
+	chmod a+x \$out/bin/relfs_grant;
+") [minInit doUnpack addInputs];
+in
+stdenv.mkDerivation rec {
+	name = "relfs-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [build doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	Relational FS over FUSE.
+";
+	};
+}
diff --git a/pkgs/tools/misc/rlwrap/0.28.nix b/pkgs/tools/misc/rlwrap/0.28.nix
new file mode 100644
index 00000000000..695c077ce67
--- /dev/null
+++ b/pkgs/tools/misc/rlwrap/0.28.nix
@@ -0,0 +1,23 @@
+args : with args; with builderDefs {src="";} null;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = ftp://ftp.chg.ru/mirrors/ftp.freebsd.org/pub/FreeBSD/ports/distfiles/rlwrap-0.28.tar.gz;
+			sha256 = "07jzhcqzb8jsmsscc28dk4md7swnhn3vyai5fpxwdj6a1kbn4y3p";
+		};
+
+		buildInputs = [readline ];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "rlwrap-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs 
+			[doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Readline wrapper for console programs.
+";
+	};
+}
diff --git a/pkgs/tools/misc/shebangfix/default.nix b/pkgs/tools/misc/shebangfix/default.nix
new file mode 100644
index 00000000000..ca4a0004d19
--- /dev/null
+++ b/pkgs/tools/misc/shebangfix/default.nix
@@ -0,0 +1,21 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "shebangfix-0.0";
+
+  buildInputs = [perl];
+
+  file = ./shebangfix.pl;
+
+  phases = "buildPhase";
+
+  buildPhase = ''
+    ensureDir $out/bin
+    s=$out/bin/shebangfix
+    cp $file $s
+    chmod +wx $s
+    ls -l $s
+    perl $s $s
+  '';
+
+  meta = { description = "replaces the #!executable with $#!correctpath/executable "; };
+}
diff --git a/pkgs/tools/misc/shebangfix/shebangfix.pl b/pkgs/tools/misc/shebangfix/shebangfix.pl
new file mode 100644
index 00000000000..53573f8d36d
--- /dev/null
+++ b/pkgs/tools/misc/shebangfix/shebangfix.pl
@@ -0,0 +1,35 @@
+#!/bin/perl
+use warnings;
+use strict;
+
+#usage PATH=< : separated path list> perl <this script>  file1 file2
+
+print "TODO fix space trouble. This script won't work if your paths contain spaces";
+
+sub findInPath{
+  my $file = shift(@_);
+  foreach (split(/:/, $ENV{'PATH'})){
+    my $f =  "$_/$file";
+    if (-x "$f"){
+      return $f;
+    }
+  }
+  print "unable to find $file in on of ".$ENV{'PATH'};
+  exit 1
+}
+
+foreach (@ARGV)
+{
+  my $file = $_;
+  open(FILE, $file);
+  my $content = do { local $/; <FILE> };
+
+  close(FILE); 
+
+  (my $name = $content) =~ /^#![^ ]*\/([^ \n\r]*)/;
+  my $fullpath =  ($1 eq 'sh') ? "/bin/sh" : findInPath($1);
+  $content =~ s/^#![^ \n\r]*/#!$fullpath/;
+  open(FILE, ">$file");
+  print FILE $content;
+  close($file);
+}
diff --git a/pkgs/tools/misc/wv/default.nix b/pkgs/tools/misc/wv/default.nix
index 141bf91bee0..9fe71248e8d 100644
--- a/pkgs/tools/misc/wv/default.nix
+++ b/pkgs/tools/misc/wv/default.nix
@@ -1,15 +1,14 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "wv-1.2.4";
 
-  src = args.
-	fetchurl {
+  src = fetchurl {
 		url = mirror://sourceforge/wvware/wv-1.2.4.tar.gz;
 		sha256 = "1mn2ax6qjy3pvixlnvbkn6ymy6y4l2wxrr4brjaczm121s8hjcb7";
 	};
 
-  buildInputs =(with args; [zlib imagemagick libpng glib
-	pkgconfig libgsf libxml2]);
+  buildInputs = [zlib imagemagick libpng glib
+	pkgconfig libgsf libxml2 bzip2];
 
   meta = {
     description = "
diff --git a/pkgs/tools/misc/xclip/default.nix b/pkgs/tools/misc/xclip/default.nix
index 305e38da464..fbf148721ca 100644
--- a/pkgs/tools/misc/xclip/default.nix
+++ b/pkgs/tools/misc/xclip/default.nix
@@ -1,15 +1,15 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "xclip-0.08";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://people.debian.org/~kims/xclip/xclip-0.08.tar.gz;
     sha256 = "0py6ijw7ln892gzxxm2w47nn97nb6psb8g6clkpz86gg706yjxpf";
   };
 
   patchPhase = "sed -i s=/usr/X11R6/bin=/bin=  Makefile";
 
-  buildInputs =(with args; [x11 libXmu]);
+  buildInputs = [x11 libXmu];
 
   installPhase="make install DESTDIR=\$out";
 
diff --git a/pkgs/tools/networking/bsd-finger/default.nix b/pkgs/tools/networking/bsd-finger/default.nix
new file mode 100644
index 00000000000..d627235494b
--- /dev/null
+++ b/pkgs/tools/networking/bsd-finger/default.nix
@@ -0,0 +1,17 @@
+args: with args;
+stdenv.mkDerivation rec {
+	name = "bsd-finger-0.17";
+
+	src = fetchurl {
+		url = "ftp://ftp.metalab.unc.edu/pub/linux/system/network/finger/${name}.tar.gz";
+		sha256 = "1yhkiv0in588il7f84k2xiy78g9lv12ll0y7047gazhiimk5v244";
+	};
+
+	NIX_CFLAGS_COMPILE="-D_GNU_SOURCE";
+
+	patches = [./ubuntu-0.17-9.patch];
+
+	preBuild = "cd finger";
+
+	preInstall = '' ensureDir $out/man/man1 $out/bin '';
+}
diff --git a/pkgs/tools/networking/bsd-finger/ubuntu-0.17-9.patch b/pkgs/tools/networking/bsd-finger/ubuntu-0.17-9.patch
new file mode 100644
index 00000000000..24decb60281
--- /dev/null
+++ b/pkgs/tools/networking/bsd-finger/ubuntu-0.17-9.patch
@@ -0,0 +1,261 @@
+--- bsd-finger-0.17.orig/finger/finger.1
++++ bsd-finger-0.17/finger/finger.1
+@@ -169,16 +169,14 @@
+ must be able to see the
+ .Pa .nofinger
+ file. This generally means that the home directory containing the file
+-must have the other-users-execute bit set (o+w). See
++must have the other-users-execute bit set (o+x). See
+ .Xr chmod 1 .
+ If you use this feature for privacy, please test it with ``finger
+ @localhost'' before relying on it, just in case.
+ .It ~/.plan
+ .It ~/.project
+-.It ~/.pgp
++.It ~/.pgpkey
+ These files are printed as part of a long-format request. The
+-.Pa .project
+-file is limited to one line; the
+ .Pa .plan
+ file may be arbitrarily long.
+ .El
+--- bsd-finger-0.17.orig/finger/finger.c
++++ bsd-finger-0.17/finger/finger.c
+@@ -77,7 +77,7 @@
+ #include "../version.h"
+ 
+ static void loginlist(void);
+-static void userlist(int argc, char *argv[]);
++static int userlist(int argc, char *argv[]);
+ 
+ int lflag, pplan;
+ static int sflag, mflag;
+@@ -92,6 +92,7 @@
+ 
+ int main(int argc, char *argv[]) {
+ 	int ch;
++	int err = 0;
+ 	struct sockaddr_in sin;
+ 	socklen_t slen = sizeof(sin);
+ 
+@@ -159,7 +160,7 @@
+ 		}
+ 	} 
+ 	else {
+-		userlist(argc, argv);
++		err = userlist(argc, argv);
+ 		/*
+ 		 * Assign explicit "large" format if names given and -s not
+ 		 * explicitly stated.  Force the -l AFTER we get names so any
+@@ -172,7 +173,7 @@
+ 		if (lflag) lflag_print();
+ 		else sflag_print();
+ 	}
+-	return 0;
++	return err;
+ }
+ 
+ /* Returns 1 if .nofinger is found and enable_nofinger is set. */
+@@ -181,10 +182,16 @@
+ check_nofinger(struct passwd *pw)
+ {
+ 	if (enable_nofinger) {
+-		char path[PATH_MAX];
+ 		struct stat tripe;
+-		snprintf(path, sizeof(path), "%s/.nofinger", pw->pw_dir);
+-		if (stat(path, &tripe)==0) {
++		int ret;
++		char *path;
++		if (asprintf(&path, "%s/.nofinger", pw->pw_dir) < 0) {
++			eprintf("finger: Out of space.\n");
++			exit(1);
++		}
++		ret = stat(path, &tripe);
++		free(path);
++		if (!ret) {
+ 			return 1;
+ 		}
+ 	}
+@@ -264,10 +271,11 @@
+ 
+ }
+ 
+-static void
++static int
+ userlist(int argc, char *argv[])
+ {
+ 	int i;
++	int err = 0;
+ 	PERSON *pn;
+ 	PERSON *nethead, **nettail;
+ 	struct utmp *uptr;
+@@ -297,13 +305,13 @@
+ 
+ 	/* handle network requests */
+ 	for (pn = nethead; pn; pn = pn->next) {
+-		netfinger(pn->name);
++		err |= netfinger(pn->name);
+ 		if (pn->next || entries)
+ 			xputc('\n');
+ 	}
+ 
+ 	if (entries == 0)
+-		return;
++		return err;
+ 
+ 	/*
+ 	 * Scan thru the list of users currently logged in, saving
+@@ -331,4 +339,6 @@
+ 		enter_lastlog(pn);
+ 	}
+ 	endutent();
++
++	return err;
+ }
+--- bsd-finger-0.17.orig/finger/finger.h
++++ bsd-finger-0.17/finger/finger.h
+@@ -92,7 +92,7 @@
+ void enter_where(struct utmp *ut, PERSON *pn);
+ void enter_lastlog(PERSON *pn);
+ int match(struct passwd *pw, const char *user);
+-void netfinger(const char *name);
++int netfinger(const char *name);
+ const char *prphone(const char *num);
+ 
+ #ifndef DAYSPERNYEAR
+--- bsd-finger-0.17.orig/finger/lprint.c
++++ bsd-finger-0.17/finger/lprint.c
+@@ -48,7 +48,7 @@
+ #include <sys/types.h>
+ #include <sys/file.h>
+ #include <sys/stat.h>
+-#include <sys/time.h>
++#include <time.h>
+ #include "finger.h"
+ 
+ static void lprint(PERSON *pn);
+@@ -100,7 +100,7 @@
+ 	 *	office, office phone, home phone if available
+ 	 */
+ 	xprintf("Login: %-15s\t\t\tName: %s\nDirectory: %-25s",
+-		pn->name, pn->realname, pn->dir);
++		pn->name, pn->realname ? pn->realname : "", pn->dir);
+ 	xprintf("\tShell: %-s\n", *pn->shell ? pn->shell : _PATH_BSHELL);
+ 
+ 	/*
+--- bsd-finger-0.17.orig/finger/net.c
++++ bsd-finger-0.17/finger/net.c
+@@ -51,7 +51,7 @@
+ #include <ctype.h>
+ #include "finger.h"
+ 
+-void netfinger(const char *name) {
++int netfinger(const char *name) {
+ 	register FILE *fp;
+ 	struct in_addr defaddr;
+ 	register int c, sawret, ateol;
+@@ -62,7 +62,7 @@
+ 	char *alist[1], *host;
+ 
+ 	host = strrchr(name, '@');
+-	if (!host) return;
++	if (!host) return 1;
+ 	*host++ = '\0';
+ 
+ 	memset(&sn, 0, sizeof(sn));
+@@ -70,7 +70,7 @@
+ 	sp = getservbyname("finger", "tcp");
+ 	if (!sp) {
+ 		eprintf("finger: tcp/finger: unknown service\n");
+-		return;
++		return 1;
+ 	}
+ 	sn.sin_port = sp->s_port;
+ 
+@@ -78,7 +78,7 @@
+ 	if (!hp) {
+ 		if (!inet_aton(host, &defaddr)) {
+ 			eprintf("finger: unknown host: %s\n", host);
+-			return;
++			return 1;
+ 		}
+ 		def.h_name = host;
+ 		def.h_addr_list = alist;
+@@ -96,7 +96,7 @@
+ 
+ 	if ((s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0) {
+ 		eprintf("finger: socket: %s\n", strerror(errno));
+-		return;
++		return 1;
+ 	}
+ 
+ 	/* print hostname before connecting, in case it takes a while */
+@@ -104,7 +104,7 @@
+ 	if (connect(s, (struct sockaddr *)&sn, sizeof(sn)) < 0) {
+ 		eprintf("finger: connect: %s\n", strerror(errno));
+ 		close(s);
+-		return;
++		return 1;
+ 	}
+ 
+ 	/* -l flag for remote fingerd  */
+@@ -128,7 +128,7 @@
+ 	if (!fp) {
+ 		eprintf("finger: fdopen: %s\n", strerror(errno));
+ 		close(s);
+-		return;
++		return 1;
+ 	}
+ 
+ 	sawret = 0;
+@@ -152,4 +152,6 @@
+ 	}
+ 	if (!ateol) xputc('\n');
+ 	fclose(fp);
++
++	return 0;
+ }
+--- bsd-finger-0.17.orig/finger/sprint.c
++++ bsd-finger-0.17/finger/sprint.c
+@@ -40,7 +40,7 @@
+ #endif /* not lint */
+ 
+ #include <sys/types.h>
+-#include <sys/time.h>
++#include <time.h>
+ #include <stdio.h>
+ #include <stdlib.h>
+ #include <string.h>
+--- bsd-finger-0.17.orig/finger/util.c
++++ bsd-finger-0.17/finger/util.c
+@@ -64,7 +64,7 @@
+ 	struct stat sb;
+ 
+ 	/* No device for X console. Utmp entry by XDM login (":0"). */
+-	if (w->tty[0] == ':') {
++	if (strchr(w->tty, ':')) {
+ 		w->idletime = 0;  /* would be nice to have it emit ??? */
+ 		w->writable = 0;
+ 		return;
+@@ -109,9 +109,8 @@
+ 	 * fields[3] -> homephone
+ 	 */
+ 	nfields = 0;
+-	for (p = strtok(bp, ","); p; p = strtok(NULL, ",")) {
+-		if (*p==0) p = NULL;  // skip empties
+-		if (nfields < 4) fields[nfields++] = p;
++	while ((p = strsep(&bp, ","))) {
++		if (nfields < 4) fields[nfields++] = *p ? p : NULL;
+ 	}
+ 	while (nfields<4) fields[nfields++] = NULL;
+ 
+@@ -150,6 +149,9 @@
+ 
+ 		pn->realname = rname;
+ 	}
++	else {
++		pn->realname = NULL;
++	}
+ 
+ 	pn->office =      fields[1] ? strdup(fields[1]) : NULL;
+ 	pn->officephone = fields[2] ? strdup(fields[2]) : NULL;
diff --git a/pkgs/tools/networking/curl/connect-timeout.patch b/pkgs/tools/networking/curl/connect-timeout.patch
new file mode 100644
index 00000000000..829c724c30e
--- /dev/null
+++ b/pkgs/tools/networking/curl/connect-timeout.patch
@@ -0,0 +1,156 @@
+diff -rc curl-7.17.1-orig/lib/connect.c curl-7.17.1/lib/connect.c
+*** curl-7.17.1-orig/lib/connect.c	2007-10-22 16:30:17.000000000 +0200
+--- curl-7.17.1/lib/connect.c	2007-12-19 18:30:32.000000000 +0100
+***************
+*** 99,105 ****
+  singleipconnect(struct connectdata *conn,
+                  const Curl_addrinfo *ai, /* start connecting to this */
+                  long timeout_ms,
+!                 bool *connected);
+  
+  /*
+   * Curl_nonblock() set the given socket to either blocking or non-blocking
+--- 99,106 ----
+  singleipconnect(struct connectdata *conn,
+                  const Curl_addrinfo *ai, /* start connecting to this */
+                  long timeout_ms,
+!                 bool *connected,
+!                 bool *timed_out);
+  
+  /*
+   * Curl_nonblock() set the given socket to either blocking or non-blocking
+***************
+*** 492,497 ****
+--- 493,499 ----
+  {
+    curl_socket_t sockfd;
+    Curl_addrinfo *ai;
++   bool timed_out;
+  
+    /* first close the failed socket */
+    sclose(conn->sock[sockindex]);
+***************
+*** 505,511 ****
+    ai = conn->ip_addr->ai_next;
+  
+    while (ai) {
+!     sockfd = singleipconnect(conn, ai, 0L, connected);
+      if(sockfd != CURL_SOCKET_BAD) {
+        /* store the new socket descriptor */
+        conn->sock[sockindex] = sockfd;
+--- 507,513 ----
+    ai = conn->ip_addr->ai_next;
+  
+    while (ai) {
+!     sockfd = singleipconnect(conn, ai, 0L, connected, &timed_out);
+      if(sockfd != CURL_SOCKET_BAD) {
+        /* store the new socket descriptor */
+        conn->sock[sockindex] = sockfd;
+***************
+*** 669,675 ****
+  singleipconnect(struct connectdata *conn,
+                  const Curl_addrinfo *ai,
+                  long timeout_ms,
+!                 bool *connected)
+  {
+    char addr_buf[128];
+    int rc;
+--- 671,678 ----
+  singleipconnect(struct connectdata *conn,
+                  const Curl_addrinfo *ai,
+                  long timeout_ms,
+!                 bool *connected,
+!                 bool *timed_out)
+  {
+    char addr_buf[128];
+    int rc;
+***************
+*** 689,694 ****
+--- 692,699 ----
+    struct curl_sockaddr *addr=(struct curl_sockaddr*)&addr_storage;
+    const void *iptoprint;
+  
++   *timed_out = FALSE;
++ 
+    addr->family=ai->ai_family;
+    addr->socktype=conn->socktype;
+    addr->protocol=ai->ai_protocol;
+***************
+*** 790,797 ****
+      infof(data, "connected\n");
+      return sockfd;
+    }
+!   else if(WAITCONN_TIMEOUT == rc)
+      infof(data, "Timeout\n");
+    else {
+      data->state.os_errno = error;
+      infof(data, "%s\n", Curl_strerror(conn, error));
+--- 795,804 ----
+      infof(data, "connected\n");
+      return sockfd;
+    }
+!   else if(WAITCONN_TIMEOUT == rc) {
+!     *timed_out = TRUE;
+      infof(data, "Timeout\n");
++   }
+    else {
+      data->state.os_errno = error;
+      infof(data, "%s\n", Curl_strerror(conn, error));
+***************
+*** 822,829 ****
+    Curl_addrinfo *ai;
+    Curl_addrinfo *curr_addr;
+    int timeout_set = 0;
+  
+-   struct timeval after;
+    struct timeval before = Curl_tvnow();
+  
+    /*************************************************************
+--- 829,836 ----
+    Curl_addrinfo *ai;
+    Curl_addrinfo *curr_addr;
+    int timeout_set = 0;
++   bool timed_out;
+  
+    struct timeval before = Curl_tvnow();
+  
+    /*************************************************************
+***************
+*** 891,909 ****
+         curr_addr = curr_addr->ai_next, aliasindex++) {
+  
+      /* start connecting to the IP curr_addr points to */
+!     sockfd = singleipconnect(conn, curr_addr, timeout_per_addr, connected);
+  
+      if(sockfd != CURL_SOCKET_BAD)
+        break;
+  
+!     /* get a new timeout for next attempt */
+!     after = Curl_tvnow();
+!     timeout_ms -= Curl_tvdiff(after, before);
+!     if(timeout_ms < 0) {
+        failf(data, "connect() timed out!");
+        return CURLE_OPERATION_TIMEDOUT;
+      }
+-     before = after;
+    }  /* end of connect-to-each-address loop */
+  
+    if (sockfd == CURL_SOCKET_BAD) {
+--- 898,914 ----
+         curr_addr = curr_addr->ai_next, aliasindex++) {
+  
+      /* start connecting to the IP curr_addr points to */
+!     sockfd = singleipconnect(conn, curr_addr, timeout_per_addr, connected, &timed_out);
+  
+      if(sockfd != CURL_SOCKET_BAD)
+        break;
+  
+!     /* if this is the last address and it timed out, propagate the
+!        timeout to the caller */
+!     if(!curr_addr->ai_next && timed_out) {
+        failf(data, "connect() timed out!");
+        return CURLE_OPERATION_TIMEDOUT;
+      }
+    }  /* end of connect-to-each-address loop */
+  
+    if (sockfd == CURL_SOCKET_BAD) {
diff --git a/pkgs/tools/networking/curl/default.nix b/pkgs/tools/networking/curl/default.nix
index 21866f02bc8..7f3488b2f35 100644
--- a/pkgs/tools/networking/curl/default.nix
+++ b/pkgs/tools/networking/curl/default.nix
@@ -4,10 +4,10 @@ assert zlibSupport -> zlib != null;
 assert sslSupport -> openssl != null;
 
 stdenv.mkDerivation {
-  name = "curl-7.16.2";
+  name = "curl-7.17.1";
   src = fetchurl {
-    url = http://curl.haxx.se/download/curl-7.16.2.tar.bz2;
-    sha256 = "18mzp56y8qhlvi27av7866mvsiyiigb7c5qdppjr8qizsj0kx0rf";
+    url = http://curl.haxx.se/download/curl-7.17.1.tar.bz2;
+    sha256 = "0yz50r75jhfr2ya6wqi6n90bn4ij30299pjglmlckzq6jp28wrkz";
   };
   buildInputs =
     stdenv.lib.optional zlibSupport zlib ++
@@ -19,4 +19,15 @@ stdenv.mkDerivation {
   CXX = "g++";
   CXXCPP = "g++ -E";
   inherit sslSupport openssl;
+
+  patches = [
+    /* Fixes broken retry support when a timeout is used.  The
+       select() system call (used to wait for the connection to come
+       up) can return slightly before the computed deadline (a few
+       milliseconds).  Curl will think the problem is something else,
+       proceed with the next IP address (which usually doesn't exist),
+       then barf with a CURLE_COULDNT_CONNECT error, which is
+       considered non-transient so it won't retry. */
+    ./connect-timeout.patch
+  ];
 }
diff --git a/pkgs/tools/networking/dnsmasq/default.nix b/pkgs/tools/networking/dnsmasq/default.nix
index 7b3cd59ba6c..b50cdeadfa3 100644
--- a/pkgs/tools/networking/dnsmasq/default.nix
+++ b/pkgs/tools/networking/dnsmasq/default.nix
@@ -1,16 +1,14 @@
-args:
-args.stdenv.mkDerivation {
+args: with args;
+stdenv.mkDerivation {
   name = "dnsmasq-2.40";
 
-  src = args.fetchurl {
+  src = fetchurl {
     url = http://www.thekelleys.org.uk/dnsmasq/dnsmasq-2.40.tar.gz;
     sha256 = "1q346l403rvvmvr14fk2l201p8fl3p5417vkp95zlx00jdb7hl8n";
   };
 
   installPhase = "ensureDir \$out; make DESTDIR=\$out PREFIX=ôônstall"; 
 
-  buildInputs =(with args; []);
-
   meta = { 
       description = "DNS forwarder and DHCP server";
       homepage = http://www.thekelleys.org.uk/dnsmasq/doc.html;
diff --git a/pkgs/tools/networking/lsh/default.nix b/pkgs/tools/networking/lsh/default.nix
new file mode 100644
index 00000000000..087aeddf497
--- /dev/null
+++ b/pkgs/tools/networking/lsh/default.nix
@@ -0,0 +1,17 @@
+{stdenv, fetchurl, gperf, guile, gmp, zlib, liboop, gnum4}:
+
+stdenv.mkDerivation {
+  name = "lsh-2.0.4";
+  src = fetchurl {
+    url = http://www.lysator.liu.se/~nisse/archive/lsh-2.0.4.tar.gz;
+    sha256 = "614b9d63e13ad3e162c82b6405d1f67713fc622a8bc11337e72949d613713091";
+  };
+
+  buildInputs = [gperf guile gmp zlib liboop gnum4];
+
+  meta = {
+    description = "GNU lsh, a GPL'd implementation of the SSH protocol.";
+    homepage = http://www.lysator.liu.se/~nisse/lsh/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/tools/networking/nc6/1.0.nix b/pkgs/tools/networking/nc6/1.0.nix
new file mode 100644
index 00000000000..1a28e3b0cad
--- /dev/null
+++ b/pkgs/tools/networking/nc6/1.0.nix
@@ -0,0 +1,25 @@
+args : with args; with builderDefs {src="";} null;
+let localDefs = builderDefs (rec {
+    src = /* put a fetchurl here */
+    fetchurl {
+      url = ftp://ftp.deepspace6.net/pub/ds6/sources/nc6/nc6-1.0.tar.bz2;
+      sha256 = "01l28zv1yal58ilfnz6albdzqqxzsx3a58vmc14r9gv0bahffdgb";
+    };
+
+    buildInputs = [];
+    configureFlags = [];
+    }) null; /* null is a terminator for sumArgs */
+in with localDefs;
+stdenv.mkDerivation rec {
+  name = "nc6-"+version;
+  builder = writeScript (name + "-builder")
+    (textClosure localDefs 
+     [doConfigure doMakeInstall doForceShare doPropagate]);
+  meta = {
+    description = "
+      nc6 - one more netcat, IPv6 support included.
+    ";
+    homepage = "http://www.deepspace6.net/projects/netcat6.html";
+  };
+}
+
diff --git a/pkgs/tools/networking/ntp/default.nix b/pkgs/tools/networking/ntp/default.nix
index 57d2ee8ab71..f96d14e83c0 100644
--- a/pkgs/tools/networking/ntp/default.nix
+++ b/pkgs/tools/networking/ntp/default.nix
@@ -3,14 +3,14 @@
 assert stdenv.isLinux -> libcap != null;
  
 stdenv.mkDerivation {
-  name = "ntp-4.2.4p3";
+  name = "ntp-4.2.4p4";
   src = fetchurl {
-    url = http://www.eecis.udel.edu/~ntp/ntp_spool/ntp4/ntp-4.2.4p3.tar.gz;
-    sha256 = "077y1hw6v0qnp3j3w3pcxgsc76waswqhwsbzfj3jqc79jfh65jv9";
+    url = http://www.eecis.udel.edu/~ntp/ntp_spool/ntp4/ntp-4.2.4p4.tar.gz;
+    sha256 = "0im89i51ap7aqlhxq5isz5xg4h8w8ahwdhir8la3c83h3p47fcmv";
   };
-  configureFlags = "
+  configureFlags = ''
     --without-crypto
     ${if stdenv.isLinux then "--enable-linuxcaps" else ""}
-  ";
+  '';
   buildInputs = if stdenv.isLinux then [libcap] else [];
 }
diff --git a/pkgs/tools/networking/openssh/default.nix b/pkgs/tools/networking/openssh/default.nix
index 12e1594fdfb..2802ac887aa 100644
--- a/pkgs/tools/networking/openssh/default.nix
+++ b/pkgs/tools/networking/openssh/default.nix
@@ -24,6 +24,7 @@ stdenv.mkDerivation {
   preConfigure = "
     configureFlags=\"$configureFlags --with-privsep-path=$out/empty\"
     ensureDir $out/empty
+    substituteInPlace pathnames.h --replace 'SSHDIR \"/ssh_config\"' '\"/etc/ssh/ssh_config\"'
   ";
 
   postInstall = "
diff --git a/pkgs/tools/networking/p2p/bit-tornado/default.nix b/pkgs/tools/networking/p2p/bit-tornado/default.nix
index 75e06f7ca2f..d8b5d2bb015 100644
--- a/pkgs/tools/networking/p2p/bit-tornado/default.nix
+++ b/pkgs/tools/networking/p2p/bit-tornado/default.nix
@@ -13,7 +13,9 @@ stdenv.mkDerivation {
   installPhase = "python setup.py install --prefix=$out ;"+
 	" echo 'export PYTHONPATH=$PYTHONPATH:'$out'/lib/python2.4/site-packages:"+
 	wxPython26+"/lib/python2.4/site-packages:"+
-	wxPython26+"/lib/python2.4/site-packages/wx-2.6-gtk2-unicode; "+
+	"'$out'/lib/python2.5/site-packages:"+
+	wxPython26+"/lib/python2.4/site-packages/wx-2.6-gtk2-unicode:"+
+	wxPython26+"/lib/python2.5/site-packages/wx-2.6-gtk2-unicode; "+
 	"python `which btdownloadgui.py` --ipv6_enabled 1 --ipv6_binds_v4 0 \"$@\";' >"+
 	"$out/bin/bittornado ; chmod a+rx $out/bin/bittornado;";
 
diff --git a/pkgs/tools/networking/p2p/bittorrent/builder.sh b/pkgs/tools/networking/p2p/bittorrent/builder.sh
index 633f53ebd43..8097995dfbd 100644
--- a/pkgs/tools/networking/p2p/bittorrent/builder.sh
+++ b/pkgs/tools/networking/p2p/bittorrent/builder.sh
@@ -1,5 +1,4 @@
 source $stdenv/setup
-source $makeWrapper
 
 # Workaround for:
 #  File "...-python-2.4.4/lib/python2.4/posixpath.py", line 62, in join
@@ -20,12 +19,9 @@ installPhase() {
 
     # Create wrappers that set the environment correctly.
     for i in $(cd $out/bin && ls); do
-        # Note: the GUI apps except to be in a directory called `bin',
-        # so don't move them. 
-        mv $out/bin/$i $out/bin/.orig-$i
-        makeWrapper $out/bin/.orig-$i $out/bin/$i \
+        wrapProgram $out/bin/$i \
             --set PYTHONPATH "$(toPythonPath $out):$PYTHONPATH"
     done
 }
 
-genericBuild
\ No newline at end of file
+genericBuild
diff --git a/pkgs/tools/networking/p2p/bittorrent/default.nix b/pkgs/tools/networking/p2p/bittorrent/default.nix
index 3894cbd36d4..cfddd48a342 100644
--- a/pkgs/tools/networking/p2p/bittorrent/default.nix
+++ b/pkgs/tools/networking/p2p/bittorrent/default.nix
@@ -6,18 +6,16 @@
 assert gui -> wxPython != null;
 
 stdenv.mkDerivation {
-  name = "bittorrent-5.0.7";
+  name = "bittorrent-5.2.0";
   builder = ./builder.sh;
   
   src = fetchurl {
-    url = http://download.bittorrent.com/dl/BitTorrent-5.0.7.tar.gz;
-    sha256 = "09m2qlhzbc6j1hf6fniri0hh6cy6ccgwi2sph65bpjrc417l94gj";
+    url = http://download.bittorrent.com/dl/BitTorrent-5.2.0.tar.gz;
+    sha256 = "0lg54x5y2k1cb7vpj7hanlnvzqa2k3v24qq0g6fsycjk4n8dky02";
   };
   
-  buildInputs = [python pycrypto twisted]
-    ++ (if gui then [wxPython] else []);
-
-  inherit makeWrapper;
+  buildInputs = [python pycrypto twisted makeWrapper]
+    ++ stdenv.lib.optional gui wxPython;
 
   meta = {
     description = "The original client for the BitTorrent peer-to-peer file sharing protocol";
diff --git a/pkgs/tools/networking/p2p/ktorrent/default.nix b/pkgs/tools/networking/p2p/ktorrent/default.nix
index a28189757b3..0c724f2ca5d 100644
--- a/pkgs/tools/networking/p2p/ktorrent/default.nix
+++ b/pkgs/tools/networking/p2p/ktorrent/default.nix
@@ -3,13 +3,21 @@
 }:
 
 stdenv.mkDerivation {
-  name = "ktorrent-2.2.1";
+  name = "ktorrent-2.2.5";
+  
   src = fetchurl {
-    url = http://ktorrent.pwsp.net/downloads/2.2.1/ktorrent-2.2.1.tar.gz;
-    sha256 = "1wv7y8p21fliys55hcbxgxndz6y7ilr3cqyz99y32sm0v6l7qpyd";
+    url = http://ktorrent.org/downloads/2.2.5/ktorrent-2.2.5.tar.bz2;
+    sha256 = "1rkblfpg4ysg4935i3l22ns553h37rn2flm4rgkqzdf67aq0akkx";
   };
+  
   buildInputs = [
     pkgconfig kdelibs kdelibs.qt xlibs.xlibs zlib libpng libjpeg perl gmp
   ];
+  
   configureFlags = "--without-arts";
+
+  meta = {
+    homepage = http://ktorrent.org/;
+    description = "A BitTorrent client for KDE";
+  };
 }
diff --git a/pkgs/tools/networking/smbfs-fuse/0.8.7.nix b/pkgs/tools/networking/smbfs-fuse/0.8.7.nix
new file mode 100644
index 00000000000..9762358b80e
--- /dev/null
+++ b/pkgs/tools/networking/smbfs-fuse/0.8.7.nix
@@ -0,0 +1,29 @@
+args : with args; with builderDefs {src="";} null;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://www.ricardis.tudelft.nl/~vincent/fusesmb/download/fusesmb-0.8.7.tar.gz;
+			sha256 = "12gz2gn9iqjg27a233dn2wij7snm7q56h97k6gks0yijf6xcnpz1";
+		};
+
+		buildInputs = [samba fuse];
+		configureFlags = [];
+		postInstall = FullDepEntry 
+		(''
+		ensureDir $out/lib
+		ln -fs ${samba}/lib/libsmbclient.so $out/lib/libsmbclient.so.0
+		'')
+		[ "minInit" "defEnsureDir" "doMakeInstall"];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "smbfs-fuse-"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs 
+			[doConfigure doMakeInstall postInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+		Samba mounted via FUSE.
+";
+	};
+}
diff --git a/pkgs/tools/networking/socat/1.6.0.0.nix b/pkgs/tools/networking/socat/1.6.0.0.nix
new file mode 100644
index 00000000000..1e176f47720
--- /dev/null
+++ b/pkgs/tools/networking/socat/1.6.0.0.nix
@@ -0,0 +1,34 @@
+args : with args; with builderDefs {src="";} null;
+    let localDefs = builderDefs (rec {
+        src = /* put a fetchurl here */
+        fetchurl {
+            url = http://www.dest-unreach.org/socat/download/socat-1.6.0.0.tar.bz2;
+            sha256 = "1j01iazwfr63q71cfcfzrdz8digqlg3ldhlbb72yl5mn9awr0w0m";
+        };
+        patches = [
+          (fetchurl {
+              url = http://www.dest-unreach.org/socat/contrib/socat-servicenames.patch;
+              sha256 = "1r8zd6mk257n01i34i5syxl2k6fr35nlr7bqs9sfc79irjl62z66";
+          })
+          (fetchurl {
+              url = http://www.dest-unreach.org/socat/contrib/socat-maxfds.patch.gz;
+              sha256 = "0fsn0k0qsrdbjbhj09a6kxfsxb7yhxs4cad26znd9naginsj7pxa";
+          })
+        ];
+        buildInputs = [openssl];
+        configureFlags = [];
+    }) null; /* null is a terminator for sumArgs */
+    in with localDefs;
+stdenv.mkDerivation rec {
+    name = "socat-"+version;
+    builder = writeScript (name + "-builder")
+        (textClosure localDefs 
+            [doPatch doConfigure doMakeInstall doForceShare doPropagate]);
+    meta = {
+        description = "
+        Socat, one more analogue of netcat, but not mimicking it.
+	'netcat++' (extended design, new implementation)
+";
+        homepage = "http://www.dest-unreach.org/socat/";
+    };
+}
diff --git a/pkgs/tools/networking/socat/2.0.0-b1.nix b/pkgs/tools/networking/socat/2.0.0-b1.nix
new file mode 100644
index 00000000000..5fb3fee7879
--- /dev/null
+++ b/pkgs/tools/networking/socat/2.0.0-b1.nix
@@ -0,0 +1,25 @@
+args : with args; with builderDefs {src="";} null;
+    let localDefs = builderDefs (rec {
+        src = /* put a fetchurl here */
+        fetchurl {
+            url = http://www.dest-unreach.org/socat/download/socat-2.0.0-b1.tar.bz2;
+            sha256 = "0ybd5fw22icl10r33k987rskh9gvysm1jph90a1pfdjj57cy44fk";
+        };
+        
+        buildInputs = [openssl];
+        configureFlags = [];
+    }) null; /* null is a terminator for sumArgs */
+    in with localDefs;
+stdenv.mkDerivation rec {
+    name = "socat-"+version;
+    builder = writeScript (name + "-builder")
+        (textClosure localDefs 
+            [doPatch doConfigure doMakeInstall doForceShare doPropagate]);
+    meta = {
+        description = "
+        Socat, one more analogue of netcat, but not mimicking it.
+	'netcat++' (extended design, new implementation)
+";
+        homepage = "http://www.dest-unreach.org/socat/";
+    };
+}
diff --git a/pkgs/tools/networking/sshfs-fuse/default.nix b/pkgs/tools/networking/sshfs-fuse/default.nix
index 29a74aed7a1..e528f68af01 100644
--- a/pkgs/tools/networking/sshfs-fuse/default.nix
+++ b/pkgs/tools/networking/sshfs-fuse/default.nix
@@ -1,10 +1,15 @@
 {stdenv, fetchurl, pkgconfig, glib, fuse}:
 
 stdenv.mkDerivation {
-  name = "sshfs-fuse-1.7";
+  name = "sshfs-fuse-1.9";
   src = fetchurl {
-    url = mirror://sourceforge/fuse/sshfs-fuse-1.7.tar.gz;
-    md5 = "e91a2fed1da952a375798408dc6e41a0";
+    url = mirror://sourceforge/fuse/sshfs-fuse-1.9.tar.gz;
+    sha256 = "10ishsghdwd6a1cd36gp26qpch6z8d6wjs7aw8vs0ffnvrs4hdza";
   };
   buildInputs = [pkgconfig glib fuse];
+
+  meta = {
+    homepage = http://fuse.sourceforge.net/sshfs.html;
+    description = "FUSE-based filesystem that allows remote filesystems to be mounted over SSH";
+  };
 }
diff --git a/pkgs/tools/networking/tcpdump/default.nix b/pkgs/tools/networking/tcpdump/default.nix
index f47ca7a965c..82d8641f60b 100644
--- a/pkgs/tools/networking/tcpdump/default.nix
+++ b/pkgs/tools/networking/tcpdump/default.nix
@@ -1,10 +1,10 @@
 {stdenv, fetchurl, libpcap}:
 
 stdenv.mkDerivation {
-  name = "tcpdump-3.9.5";
+  name = "tcpdump-3.9.8";
   src = fetchurl {
-    url = http://www.tcpdump.org/release/tcpdump-3.9.5.tar.gz;
-    md5 = "2135e7b1f09af0eaf66d2af822bed44a";
+    url = http://www.tcpdump.org/release/tcpdump-3.9.8.tar.gz;
+    sha256 = "16fjm1ih56mwqniffp63adbxwfj5n10x1a7l22j3cx683pmwh293";
   };
   buildInputs = [libpcap];
 }
diff --git a/pkgs/tools/networking/vpnc/builder.sh b/pkgs/tools/networking/vpnc/builder.sh
new file mode 100644
index 00000000000..ecfabe2eb5e
--- /dev/null
+++ b/pkgs/tools/networking/vpnc/builder.sh
@@ -0,0 +1,9 @@
+source "$stdenv/setup"
+
+tar zxvf "$src" &&
+cd vpnc-*.*
+
+cat config.c |								\
+sed "s|/etc/vpnc/vpnc-script|$out/etc/vpnc/vpnc-script|g" > ,,tmp &&	\
+mv ,,tmp config.c &&							\
+patchPhase && buildPhase && installPhase && fixupPhase && distPhase
diff --git a/pkgs/tools/networking/vpnc/default.nix b/pkgs/tools/networking/vpnc/default.nix
new file mode 100644
index 00000000000..c11a4721cb7
--- /dev/null
+++ b/pkgs/tools/networking/vpnc/default.nix
@@ -0,0 +1,20 @@
+{stdenv, fetchurl, libgcrypt, perl}:
+
+stdenv.mkDerivation {
+  name = "vpnc-0.5.1";
+  src = fetchurl {
+    url = http://www.unix-ag.uni-kl.de/~massar/vpnc/vpnc-0.5.1.tar.gz;
+    sha256 = "f63660bd020bbe6a39e8eb67ad60c54d719046c6198a6834371d098947f9a2ed";
+  };
+
+  patches = [ ./makefile.patch ];
+
+  buildInputs = [libgcrypt perl];
+  builder = ./builder.sh;
+
+  meta = {
+    description = "VPNC, a virtual private network (VPN) client for Cisco's VPN concentrators";
+    homepage = http://www.unix-ag.uni-kl.de/~massar/vpnc/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/tools/networking/vpnc/makefile.patch b/pkgs/tools/networking/vpnc/makefile.patch
new file mode 100644
index 00000000000..89a8cd6da95
--- /dev/null
+++ b/pkgs/tools/networking/vpnc/makefile.patch
@@ -0,0 +1,22 @@
+--- vpnc-0.5.1.orig/Makefile	2008-02-10 22:22:43.000000000 +0100
++++ vpnc-0.5.1/Makefile	2008-02-10 22:22:32.000000000 +0100
+@@ -20,8 +20,8 @@
+ # $Id: Makefile 236 2007-09-05 20:40:59Z Joerg Mayer $
+ 
+ DESTDIR=
+-PREFIX=/usr/local
+-ETCDIR=/etc/vpnc
++PREFIX=$(out)
++ETCDIR=$(out)/etc/vpnc
+ BINDIR=$(PREFIX)/bin
+ SBINDIR=$(PREFIX)/sbin
+ MANDIR=$(PREFIX)/share/man
+@@ -71,7 +71,7 @@
+ 	$(CC) -o $@ $^ $(LDFLAGS)
+ 
+ vpnc.8 : vpnc.8.template makeman.pl vpnc
+-	./makeman.pl
++	perl makeman.pl
+ 
+ cisco-decrypt : cisco-decrypt.o config.o supp.o sysdep.o vpnc-debug.o
+ 	$(CC) -o $@ $^ $(LDFLAGS)
diff --git a/pkgs/tools/networking/wget/default.nix b/pkgs/tools/networking/wget/1.10.2.nix
index 8817466432d..8817466432d 100644
--- a/pkgs/tools/networking/wget/default.nix
+++ b/pkgs/tools/networking/wget/1.10.2.nix
diff --git a/pkgs/tools/networking/wget/1.11.nix b/pkgs/tools/networking/wget/1.11.nix
new file mode 100644
index 00000000000..c7295f1df94
--- /dev/null
+++ b/pkgs/tools/networking/wget/1.11.nix
@@ -0,0 +1,16 @@
+args: with args;
+
+stdenv.mkDerivation rec {
+  name = "wget-" + version;
+  src = fetchurl {
+    url = "mirror://gnu/wget/${name}.tar.bz2";
+    sha256 = "0mhd3181zdp1fwirxw0km7502sfvjmm1ncska9w6s2drczf37aix";
+  };
+
+  buildInputs = [gettext];
+
+  meta = {
+    description = "A console downloading program. Has some features for mirroring sites.";
+    homepage = http://www.gnu.org/software/wget;
+  };
+}
diff --git a/pkgs/tools/package-management/nix/custom.nix b/pkgs/tools/package-management/nix/custom.nix
new file mode 100644
index 00000000000..2cff9f53d87
--- /dev/null
+++ b/pkgs/tools/package-management/nix/custom.nix
@@ -0,0 +1,45 @@
+{ stdenv, fetchurl, aterm, db4, perl, curl, bzip2, openssl ? null
+, storeDir ? "/nix/store"
+, stateDir ? "/nix/var"
+, src
+, preConfigure ? ""
+, autoconf ? null, automake ? null, libtool ? null
+, bison ? null
+, flex ? null
+, w3m ? null
+, docbook5_xsl ? null, libxslt ? null
+, docbook5 ? null, docbook_xml_dtd_43 ? null 
+, configureFlags ? []
+}:
+
+stdenv.mkDerivation {
+  name = "nix-custom";
+  
+  inherit src;
+
+  buildInputs = [perl curl openssl] 
+  	++ (if automake != null then [automake] else [])
+  	++ (if autoconf != null then [autoconf] else [])
+  	++ (if libtool != null then [libtool] else [])
+  	++ (if bison != null then [bison] else [])
+  	++ (if flex != null then [flex] else [])
+  	++ (if docbook5_xsl != null then [docbook5_xsl] else [])
+  	++ (if libxslt != null then [libxslt] else [])
+  	++ (if docbook5 != null then [docbook5] else [])
+  	++ (if docbook_xml_dtd_43 != null then [docbook_xml_dtd_43] else [])
+  	++ (if w3m != null then [w3m] else [])
+  ;
+
+  inherit preConfigure;
+
+  configureFlags = ["
+    --with-store-dir=${storeDir} --localstatedir=${stateDir}
+    --with-aterm=${aterm} --with-bdb=${db4} --with-bzip2=${bzip2}
+    --disable-init-state"] ++ configureFlags ;
+
+  meta = {
+    description = "The Nix Deployment System";
+    homepage = http://nix.cs.uu.nl/;
+    license = "LGPL";
+  };
+}
diff --git a/pkgs/tools/package-management/nix/default.nix b/pkgs/tools/package-management/nix/default.nix
index 55c20a4b837..128bc23dd4b 100644
--- a/pkgs/tools/package-management/nix/default.nix
+++ b/pkgs/tools/package-management/nix/default.nix
@@ -1,17 +1,17 @@
-{ stdenv, fetchurl, aterm, db4, perl, curl, bzip2
+{ stdenv, fetchurl, aterm, db4, perl, curl, bzip2, openssl ? null
 , storeDir ? "/nix/store"
 , stateDir ? "/nix/var"
 }:
 
 stdenv.mkDerivation {
-  name = "nix-0.10.1";
+  name = "nix-0.11";
   
   src = fetchurl {
-    url = http://nix.cs.uu.nl/dist/nix/nix-0.10.1/nix-0.10.1.tar.bz2;
-    md5 = "22dc0c024ca5bb477da0b38ba834dbf2";
+    url = http://nix.cs.uu.nl/dist/nix/nix-0.11/nix-0.11.tar.bz2;
+    md5 = "890c25ac0005ff466683869efc288b67";
   };
   
-  buildInputs = [perl curl];
+  buildInputs = [perl curl openssl];
 
   configureFlags = "
     --with-store-dir=${storeDir} --localstatedir=${stateDir}
diff --git a/pkgs/tools/package-management/nix/unstable.nix b/pkgs/tools/package-management/nix/unstable.nix
index 9d381198bee..1a507f20a04 100644
--- a/pkgs/tools/package-management/nix/unstable.nix
+++ b/pkgs/tools/package-management/nix/unstable.nix
@@ -3,22 +3,23 @@
 , stateDir ? "/nix/var"
 }:
 
-let version = "0.11pre9570"; in
+let version = "0.12pre10505"; in
 
 stdenv.mkDerivation {
   name = "nix-${version}";
   
   src = fetchurl {
     url = "http://nix.cs.uu.nl/dist/nix/nix-${version}/nix-${version}.tar.bz2";
-    md5 = "5170f1b1e8feda2adeb2cac3c5ca5ff9";
+    md5 = "44dd2927ce97f12b3f110a7ad991828e";
   };
 
   buildInputs = [perl curl openssl];
 
-  configureFlags = "
+  configureFlags = ''
     --with-store-dir=${storeDir} --localstatedir=${stateDir}
     --with-aterm=${aterm} --with-bdb=${db4} --with-bzip2=${bzip2}
-    --disable-init-state";
+    --disable-init-state
+  '';
 
   meta = {
     description = "The Nix Deployment System";
diff --git a/pkgs/tools/package-management/snix/default.nix b/pkgs/tools/package-management/snix/default.nix
new file mode 100644
index 00000000000..caf852de4e2
--- /dev/null
+++ b/pkgs/tools/package-management/snix/default.nix
@@ -0,0 +1,36 @@
+{ stdenv, fetchurl, aterm, db4, perl, curl, bzip2, openssl ? null
+
+, ext3cowtools, e3cfsprogs, rsync
+#, libtool, docbook5, docbook5-xsl, flex, bison
+
+, ext3cow_kernel
+
+, storeDir ? "/nix/store"
+, stateDir ? "/nix/var"
+, nixStoreStateDir ? "/nix/state"
+}:
+
+stdenv.mkDerivation {
+  name = "snix-0.12rev9419";
+  
+  src = fetchurl {
+    url = http://www.denbreejen.net/public/nix/snix-0.12rev9419.tar.gz;
+    sha256 = "fe7c06a8c41f6c9c94898a5fd690ed76da397012ea4c624adac9029b23c88a1c";
+  };
+  
+  buildInputs = [perl curl openssl rsync];
+
+  configureFlags = "
+    --with-store-dir=${storeDir} --localstatedir=${stateDir}
+    --with-aterm=${aterm} --with-bdb=${db4} --with-bzip2=${bzip2}
+    --disable-init-state
+    --with-store-state-dir=${nixStoreStateDir}
+    --with-ext3cow-header=${ext3cow_kernel}/lib/modules/2.*/build/include/linux/ext3cow_fs.h
+    --with-rsync=${rsync}/bin/rsync";
+
+  meta = {
+    description = "The SNix Deployment System (Nix extended to handle state)";
+    homepage = http://nix.cs.uu.nl/;
+    license = "LGPL";
+  };
+}
diff --git a/pkgs/tools/security/chkrootkit/default.nix b/pkgs/tools/security/chkrootkit/default.nix
new file mode 100644
index 00000000000..e7545ac8cd6
--- /dev/null
+++ b/pkgs/tools/security/chkrootkit/default.nix
@@ -0,0 +1,16 @@
+{stdenv, fetchurl}:
+  
+stdenv.mkDerivation {
+  name = "chkrootkit-0.48";
+  
+  src = fetchurl {
+    url = ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz;
+    sha256 = "1yzid6bw092nf8k83y1119kc4ns7r0l3zsfah5xal8kh19ad7cxl";
+  };
+
+  installPhase = "
+    ensureDir $out/sbin
+    cp check_wtmpx chkdirs chklastlog chkproc chkrootkit chkutmp chkwtmp ifpromisc strings-static $out/sbin
+  ";
+  
+}
diff --git a/pkgs/tools/security/gnupg/default.nix b/pkgs/tools/security/gnupg/default.nix
index 95555c2e11c..16c86fbe804 100644
--- a/pkgs/tools/security/gnupg/default.nix
+++ b/pkgs/tools/security/gnupg/default.nix
@@ -7,15 +7,20 @@
 }:
 
 stdenv.mkDerivation {
-  name = "gnupg-1.4.7";
+  name = "gnupg-1.4.8";
   builder = ./builder.sh;
   src = fetchurl {
-    url = ftp://ftp.surfnet.nl/pub/security/gnupg/gnupg/gnupg-1.4.7.tar.bz2;
-    sha256 = "13a6qrgswbrfj3z5hcjx62ahraj4j16cpssgxlkwlqiz35yqplb9";
+    url = ftp://ftp.cert.dfn.de/pub/tools/crypt/gcrypt/gnupg/gnupg-1.4.8.tar.bz2;
+    sha256 = "0v009vqpa4l9zwhcaaagz5sx65fjp8g0alsf8kac5s5gvrs2b78i";
   };
   buildInputs = [readline];
   idea = if ideaSupport then fetchurl {
     url = http://nix.cs.uu.nl/dist/tarballs/idea.c.gz;
     md5 = "9dc3bc086824a8c7a331f35e09a3e57f";
   } else null;
+
+  meta = {
+    description = "A free implementation of the OpenPGP standard for encrypting and signing data";
+    homepage = http://www.gnupg.org/;
+  };
 }
diff --git a/pkgs/tools/security/gnupg2/default.nix b/pkgs/tools/security/gnupg2/default.nix
new file mode 100644
index 00000000000..f6e22bec51d
--- /dev/null
+++ b/pkgs/tools/security/gnupg2/default.nix
@@ -0,0 +1,16 @@
+args: with args;
+stdenv.mkDerivation {
+  name = "gnupg-2.0.8";
+  src = fetchurl {
+    url = ftp://ftp.cert.dfn.de/pub/tools/crypt/gcrypt/gnupg/gnupg-2.0.8.tar.bz2;
+    sha256 = "04v9s92xph1hrhac49yyrgzdwjqshs2zawvjbi3jc2klwjpi1wqn";
+  };
+  buildInputs = [ readline openldap bzip2 zlib libgpgerror pth libgcrypt
+    libassuan libksba libusb curl ];
+
+  meta = {
+    description = "A free implementation of the OpenPGP standard for encrypting
+	and signing data, v2";
+    homepage = http://www.gnupg.org/;
+  };
+}
diff --git a/pkgs/tools/system/cron/default.nix b/pkgs/tools/system/cron/default.nix
index 066f594ea84..4d7dcb93db2 100644
--- a/pkgs/tools/system/cron/default.nix
+++ b/pkgs/tools/system/cron/default.nix
@@ -10,7 +10,7 @@ stdenv.mkDerivation {
   unpackCmd = "(mkdir cron && cd cron && sh $src)";
 
   preBuild = "
-    substituteInPlace Makefile --replace '-o root' '' --replace 111 755
+    substituteInPlace Makefile --replace ' -o root' ' ' --replace 111 755
     makeFlags=\"DESTROOT=$out\"
   ";
 
diff --git a/pkgs/tools/system/gdmap/0.7.5.nix b/pkgs/tools/system/gdmap/0.7.5.nix
new file mode 100644
index 00000000000..062f63566a6
--- /dev/null
+++ b/pkgs/tools/system/gdmap/0.7.5.nix
@@ -0,0 +1,22 @@
+args : with args;
+	let localDefs = builderDefs {
+		src = /* put a fetchurl here */
+		fetchurl {
+			url = http://dfn.dl.sourceforge.net/sourceforge/gdmap/gdmap-0.7.5.tar.gz;
+			sha256 = "0vxfgz1bq0jvny6dy7dkzg2kl56plrxby6c4y5d6bv4bq2xd6v26";
+		};
+
+		buildInputs = [gtk pkgconfig libxml2 intltool];
+		configureFlags = [];
+	} null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "gdmap"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [doConfigure doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	Recursive rectangle map of disk usage.	
+";
+	};
+}
diff --git a/pkgs/tools/system/pciutils/default.nix b/pkgs/tools/system/pciutils/default.nix
index 84bd24195ce..5dd67574777 100644
--- a/pkgs/tools/system/pciutils/default.nix
+++ b/pkgs/tools/system/pciutils/default.nix
@@ -1,16 +1,16 @@
 {stdenv, fetchurl, zlib}:
 
 stdenv.mkDerivation {
-  name = "pciutils-2.2.5";
+  name = "pciutils-2.2.8";
   builder = ./builder.sh;
   src = fetchurl {
-    url = mirror://kernel/software/utils/pciutils/pciutils-2.2.5.tar.bz2;
-    sha256 = "1zlamdax1i8cf3kvzg7dh7nshvvzlhvkwlxdmym0hbnmbf0p100p";
+    url = mirror://kernel/software/utils/pciutils/pciutils-2.2.8.tar.bz2;
+    sha256 = "0hgri2ancnjl56ld2flb9w606dyvr5gly8gsz3bzl71r8s464qsq";
   };
   buildInputs = [zlib];
 
   pciids = fetchurl {
-    url = http://nix.cs.uu.nl/dist/tarballs/pci.ids.20070226.bz2;
-    sha256 = "1wrpq4dxm03v5jvvdlvwl8nrkj3hspgifkw5czmd647lzikp13qc";
+    url = http://nix.cs.uu.nl/dist/tarballs/pci.ids.20080118.bz2;
+    sha256 = "0dl6psdac62llbklxn4dvkzbw1j1sdadw9i4l36vpd6mvqa7lz0a";
   };
 }
diff --git a/pkgs/tools/system/which/default.nix b/pkgs/tools/system/which/default.nix
index 6b151709b63..b6c35c4fbf1 100644
--- a/pkgs/tools/system/which/default.nix
+++ b/pkgs/tools/system/which/default.nix
@@ -1,9 +1,11 @@
-{stdenv, fetchurl}: stdenv.mkDerivation {
-  name = "which-2.16";
+{stdenv, fetchurl, readline}: stdenv.mkDerivation {
+  name = "which-2.19";
   src = fetchurl {
-    url = http://ftp.gnu.org/gnu/which/which-2.17.tar.gz;
-    sha256 = "1nnnbn83da8481blmcyv96gm15ccsilr93fmgmwdlzj8a72fjvqp";
+    url = mirror://gnu/which/which-2.19.tar.gz;
+    sha256 = "0lnd8mfpc0r1r2ch54vl3vc6r0fnzfl33sqdda2aq62iyrsbhybx";
   };
+
+  buildInputs = [readline];
 }
 
 
diff --git a/pkgs/tools/text/diffutils/default.nix b/pkgs/tools/text/diffutils/default.nix
index 3c0d5479ec5..44b7715607c 100644
--- a/pkgs/tools/text/diffutils/default.nix
+++ b/pkgs/tools/text/diffutils/default.nix
@@ -2,10 +2,17 @@
 
 stdenv.mkDerivation {
   name = "diffutils-2.8.1";
+  
   src = fetchurl {
     url = mirror://gnu/diffutils/diffutils-2.8.1.tar.gz;
     md5 = "71f9c5ae19b60608f6c7f162da86a428";
   };
+  
   /* If no explicit coreutils is given, use the one from stdenv. */
   buildInputs = [coreutils];
+
+  meta = {
+    homepage = http://www.gnu.org/software/diffutils/diffutils.html;
+    description = "Commands for showing the differences between files (diff, cmp, etc.)";
+  };
 }
diff --git a/pkgs/tools/text/gawk/default.nix b/pkgs/tools/text/gawk/default.nix
index 2c495f8c271..10dd08214af 100644
--- a/pkgs/tools/text/gawk/default.nix
+++ b/pkgs/tools/text/gawk/default.nix
@@ -1,9 +1,15 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "gawk-3.1.5";
+  name = "gawk-3.1.6";
+  
   src = fetchurl {
-    url = ftp://ftp.gnu.org/gnu/gawk/gawk-3.1.5.tar.bz2;
-    md5 = "5703f72d0eea1d463f735aad8222655f";
+    url = mirror://gnu/gawk/gawk-3.1.6.tar.bz2;
+    sha256 = "0v6ba4hxfiiy3bny5japd3zmzxlh8vdkmswk96yngd6i1dddsgsi";
+  };
+
+  meta = {
+    homepage = http://www.gnu.org/software/gawk/;
+    description = "GNU implementation of the AWK programming language";
   };
 }
diff --git a/pkgs/tools/text/gnugrep/default.nix b/pkgs/tools/text/gnugrep/default.nix
index 15a7a5ad239..9b36dad6cfe 100644
--- a/pkgs/tools/text/gnugrep/default.nix
+++ b/pkgs/tools/text/gnugrep/default.nix
@@ -1,10 +1,17 @@
 {stdenv, fetchurl, pcre}:
 
 stdenv.mkDerivation {
-  name = "gnugrep-2.5.1a";
+  name = "gnugrep-2.5.3";
+  
   src = fetchurl {
-    url = http://ftp.gnu.org/gnu/grep/grep-2.5.1a.tar.bz2;
-    md5 = "52202fe462770fa6be1bb667bd6cf30c";
+    url = http://nix.cs.uu.nl/dist/tarballs/grep-2.5.3-with-info.tar.bz2;
+    sha256 = "0rg9dipksqzbg8v1xalib1n3xkkycc5r1l2gb9cxy1cz3cjip5l8";
   };
+  
   buildInputs = [pcre];
+
+  meta = {
+    homepage = http://www.gnu.org/software/grep/;
+    description = "GNU implementation of the Unix grep command";
+  };
 }
diff --git a/pkgs/tools/text/gnused/default.nix b/pkgs/tools/text/gnused/default.nix
index c70cf022570..2425147688b 100644
--- a/pkgs/tools/text/gnused/default.nix
+++ b/pkgs/tools/text/gnused/default.nix
@@ -2,10 +2,17 @@
 
 stdenv.mkDerivation {
   name = "gnused-4.1.5";
+  
   src = fetchurl {
     url = mirror://gnu/sed/sed-4.1.5.tar.gz;
     md5 = "7a1cbbbb3341287308e140bd4834c3ba";
   };
+  
   # !!! hack: this should go away in gnused > 4.1.5
   patches = [./gettext-fix.patch];
+
+  meta = {
+    homepage = http://www.gnu.org/software/grep/;
+    description = "GNU implementation of the Unix sed command";
+  };
 }
diff --git a/pkgs/tools/text/replace/default.nix b/pkgs/tools/text/replace/default.nix
index 3135204ef03..ca96309e40e 100644
--- a/pkgs/tools/text/replace/default.nix
+++ b/pkgs/tools/text/replace/default.nix
@@ -1,4 +1,5 @@
 {stdenv, fetchurl}:
+
 stdenv.mkDerivation {
   name = "replace-2.24";
 
@@ -7,14 +8,12 @@ stdenv.mkDerivation {
     sha256 = "1c2nkxx83vmlh1v3ib6r2xqh121gdb1rharwsimcb2h0xwc558dm";
   };
 
-  buildInputs = [];
-  makeFlags = " TREE=\$(out) ";
+  makeFlags = "TREE=\$(out)";
 
   postInstall = "mv \$out/bin/replace \$out/bin/replace-literal";
 
   meta = {
-    description = "
-	Replace verbatim strings. Sed is not fit to do it. Replace is.
-";
+    homepage = http://replace.richardlloyd.org.uk/;
+    description = "A tool to replace verbatim strings";
   };
 }
diff --git a/pkgs/tools/typesetting/lhs2tex/default.nix b/pkgs/tools/typesetting/lhs2tex/default.nix
index fc0ce40f8e5..f071f67fe97 100644
--- a/pkgs/tools/typesetting/lhs2tex/default.nix
+++ b/pkgs/tools/typesetting/lhs2tex/default.nix
@@ -3,12 +3,12 @@
 assert tetex == polytable.tetex;
 
 stdenv.mkDerivation {
-  name = "lhs2tex-1.12";
+  name = "lhs2tex-1.13pre3";
   builder = ./builder.sh;
   
   src = fetchurl {
-    url = http://www.informatik.uni-bonn.de/~loeh/lhs2tex/lhs2tex-1.12.tar.bz2;
-    md5 = "1bc982e96f19201aaf1c39c1d4b5e358";
+    url = "http://www.cs.uu.nl/~andres/lhs2tex/lhs2tex-1.13pre3.tar.bz2";
+    sha256 = "8ddc9bd150c20c33518d747fee95577ec8f587146532cda12b8034adc847826c";
   };
 
   buildInputs = [tetex ghc];
diff --git a/pkgs/tools/typesetting/lout/builder.sh b/pkgs/tools/typesetting/lout/builder.sh
new file mode 100755
index 00000000000..28788fc5227
--- /dev/null
+++ b/pkgs/tools/typesetting/lout/builder.sh
@@ -0,0 +1,42 @@
+#!/bin/sh
+
+# Prepare a makefile specifying the appropriate output directories.
+#
+# Written by Ludovic Courtès <ludo@gnu.org>.
+
+source "$stdenv/setup" || exit 1
+
+nixMakefile="nix-makefile"
+
+# Build and install documentation, PS and PDF.
+installDoc ()
+{
+  echo "building and installing documentation..."
+  for doc in design expert slides user
+  do
+    echo "building \`$doc' document..."
+    if [ ! -f "doc/$doc/outfile.ps" ]
+    then
+      ( PATH="$PWD:$PATH" ;				\
+        cd "doc/$doc" && lout -r4 -o outfile.ps all )	\
+      || return 1
+    fi
+    cp "doc/$doc/outfile.ps" "$out/doc/lout/$doc.ps" &&		\
+    ps2pdf "doc/$doc/outfile.ps" "$out/doc/lout/$doc.pdf"
+  done
+
+  return 0
+}
+
+unpackPhase &&									\
+cd lout-*.* &&									\
+cat makefile |									\
+  sed -e "s|^PREFIX[[:blank:]]*=.*\$|PREFIX = $out|g ;				\
+          s|^LOUTLIBDIR[[:blank:]]*=.*$|LOUTLIBDIR = \$(PREFIX)/lib/lout|g ;	\
+	  s|^LOUTDOCDIR[[:blank:]]*=.*$|LOUTDOCDIR = \$(PREFIX)/doc/lout|g ;	\
+	  s|^MANDIR[[:blank:]]*=.*$|MANDIR = \$(PREFIX)/man|g"			\
+  > "$nixMakefile" &&								\
+mkdir -p "$out/bin" && mkdir -p "$out/lib"					\
+mkdir -p "$out/man" && mkdir -p "$out/doc/lout" &&				\
+make -f "$nixMakefile" install installman &&					\
+installDoc
diff --git a/pkgs/tools/typesetting/lout/default.nix b/pkgs/tools/typesetting/lout/default.nix
new file mode 100644
index 00000000000..e36cc9ad303
--- /dev/null
+++ b/pkgs/tools/typesetting/lout/default.nix
@@ -0,0 +1,20 @@
+{stdenv, fetchurl, ghostscript}:
+
+stdenv.mkDerivation {
+  name = "lout-3.36";
+  src = fetchurl {
+    url = ftp://ftp.cs.usyd.edu.au/jeff/lout/lout-3.36.tar.gz;
+    sha256 = "b689cbe12074be8817c90070b162593fc9cc51f2f8868701833ff599b24fd4ad";
+  };
+
+  buildInputs = [ ghostscript ];
+  builder = ./builder.sh;
+
+  meta = {
+    description = ''Lout is a document layout system, similar in functionality
+    		    to TeX/LaTeX, but based on a purely functional programming
+		    language.  It can produce PostScript output.'';
+    homepage = http://www.cs.usyd.edu.au/~jeff/;
+    license = "GPL";
+  };
+}
diff --git a/pkgs/top-level/all-packages.nix b/pkgs/top-level/all-packages.nix
index 1b31a9e69a0..5a207434202 100644
--- a/pkgs/top-level/all-packages.nix
+++ b/pkgs/top-level/all-packages.nix
@@ -119,16 +119,49 @@ rec {
   # inside the set for derivations.
   recurseIntoAttrs = attrs: attrs // {recurseForDerivations = true;};
 
-  useFromStdenv = hasIt: it: alternative: if hasIt then it else alternative;
-
-  lib = library;
-
-  library = import ../lib;
-  lib_unstable = import ../lib/default-unstable.nix;
+  useFromStdenv = it : alternative : if (builtins.hasAttr it stdenv) then
+    (builtins.getAttr it stdenv) else alternative;
+
+  lib = import ../lib;
+
+  annotatedDerivations = (import ../lib/annotatedDerivations.nix) { inherit lib; };
+
+  # optional srcDir
+  annotatedWithSourceAndTagInfo = x : (x ? sourceWithTags);
+
+  # example arguments see annotatedGhcCabalDerivation
+  # tag command must create file named $TAG_FILE
+  sourceWithTagsDerivation = args: with args; 
+    let createTagFiles = (lib.maybeAttr "createTagFiles" [] args ); in
+  stdenv.mkDerivation {
+    phases = "unpackPhase buildPhase";
+    inherit (args) src name;
+    srcDir = (lib.maybeAttr "srcDir" "." args);
+    # using separate tag directory so that you don't have to glob that much files when starting your editor
+    # is this a good choice?
+    buildPhase = "
+      SRC_DEST=\$out/src/\$name
+      t=\$out/tags/\$name
+      ensureDir \$SRC_DEST \$t
+      cp -r \$srcDir \$SRC_DEST"
+      + lib.defineShList "sh_list_names" (lib.catAttrs "name" createTagFiles)
+      + lib.defineShList "sh_list_cmds" (lib.catAttrs "tagCmd" createTagFiles)
+      + "cd \$SRC_DEST
+      for a in `seq 0 \${#sh_list}`; do
+          TAG_FILE=\"\$SRC_DEST/\"\${sh_list_names[\$a]}
+          cmd=\"\${sh_list_cmds[\$a]}\"
+          echo running tag cmd \"\$cmd\" in `pwd`
+          eval \"\$cmd\";
+          ln -s \$TAG_FILE \"\$t/\"\${sh_list_names[\$a]}
+       done
+    ";
+  };
+  # example usage
+  testSourceWithTags = sourceWithTagsDerivation (ghc68_extra_libs ghcsAndLibs.ghc68).mtl.sourceWithTags;
 
   # Return an attribute from the Nixpkgs configuration file, or
   # a default value if the attribute doesn't exist.
-  getConfig = attrPath: default: library.getAttr attrPath default config;
+  getConfig = attrPath: default: lib.getAttr attrPath default config;
 
   # Return user-choosen version of given package. If you define package as
   #
@@ -142,15 +175,16 @@ rec {
   # pkgname = getVersion "name" pkgname_alts;
   #
   # user will be able to write in his configuration.nix something like
-  # environment = { versions = { name = v_0_2; }; }; and pkgname will be equal
-  # to pkgname_alts.v_0_2. Using alts.default by default.
+  # name = { version = "0.2"; }; and pkgname will be equal
+  # to getAttr pkgname_alts "0.2". Using alts.default by default.
   getVersion = name: alts: builtins.getAttr
-    (getConfig [ "environment" "versions" name ] "default") alts;
+    (getConfig [ name "version" ] "default") alts;
 
-  # Whether user enabled given feature for the given package?
-  getFlag = flag: package: default:
-  getConfig [ "environment" "flags" package flag ]
-  (getConfig [ "environment" "flags" "default" flag ] default);
+  # The same, another syntax.
+  # Warning: syntax for configuration.nix changed too
+  useVersion = name: f: f {
+    version = getConfig [ "environment" "versions" name ];
+  };
 
   # The contents of the configuration file found at $NIXPKGS_CONFIG or
   # $HOME/.nixpkgs/config.nix.
@@ -189,12 +223,15 @@ rec {
     meta = (if drv ? meta then drv.meta else {}) // {priority = "10";};
   };
 
-  mkDerivationByConfiguration = { flagConfig ? {}, optionals ? [], defaults ? [],  
-        extraAttrs, collectExtraPhaseActions ? []} :
+  mkDerivationByConfiguration = 
+    assert builtins ? isAttrs;
+    { flagConfig ? {}, optionals ? [], defaults ? []
+    , extraAttrs, collectExtraPhaseActions ? []
+    }:
     args: with args.lib; with args;
-    if ( __isAttrs extraAttrs ) then builtins.throw "the argument extraAttrs needs to be a function beeing passed co, but attribute set passed "
+    if ( builtins.isAttrs extraAttrs ) then builtins.throw "the argument extraAttrs needs to be a function beeing passed co, but attribute set passed "
     else
-    let co = chooseOptionsByFlags { inherit args flagConfig optionals defaults collectExtraPhaseActions; }; in
+    let co = lib.chooseOptionsByFlags { inherit args flagConfig optionals defaults collectExtraPhaseActions; }; in
       args.stdenv.mkDerivation ( 
       {
         inherit (co) configureFlags buildInputs /*flags*/;
@@ -207,17 +244,31 @@ rec {
 			(import ../build-support/checker) 
 			opts config); in
 			(if (result=="") then x else
-			abort result)
+			abort ("Unknown option specified: " + result))
 		else x);
 
 	builderDefs = lib.sumArgs (import ./builder-defs.nix) {
-		inherit stringsWithDeps lib stdenv writeScript;
+		inherit stringsWithDeps lib stdenv writeScript fetchurl;
 	};
 
 	stringsWithDeps = import ../lib/strings-with-deps.nix {
 		inherit stdenv lib;
 	};
 
+  # Call a specific version of a Nix expression, that is,
+  # `selectVersion ./foo {version = "0.1.2"; args...}' evaluates to
+  # `import ./foo/0.1.2.nix args'.
+  selectVersion = dir: defVersion: args:
+    let
+      pVersion =
+        if (args ? version && args.version != "") then
+          args.version
+        else
+          getConfig [ (baseNameOf (toString dir)) "version" ] defVersion;
+    in
+      import (dir + "/${pVersion}.nix") (args // { version = pVersion; });
+        
+        
   ### STANDARD ENVIRONMENT
 
 
@@ -237,7 +288,6 @@ rec {
         }
       else defaultStdenv;
 
-  stdenvUsingSetupNew2 = overrideSetup stdenv ../stdenv/generic/setup-new-2.sh;
 
   ### BUILD SUPPORT
 
@@ -266,12 +316,17 @@ rec {
 
   # Allow the stdenv to determine fetchurl, to cater for strange
   # requirements.
-  fetchurl = useFromStdenv (stdenv ? fetchurl) stdenv.fetchurl
+  fetchurl = useFromStdenv "fetchurl"
     (import ../build-support/fetchurl {
       inherit stdenv curl;
     });
 
-  makeWrapper = ../build-support/make-wrapper/make-wrapper.sh;
+  makeSetupHook = script: runCommand "hook" {} ''
+    ensureDir $out/nix-support
+    cp ${script} $out/nix-support/setup-hook
+  '';
+
+  makeWrapper = makeSetupHook ../build-support/make-wrapper/make-wrapper.sh;
 
   # Run the shell command `buildCommand' to produce a store object
   # named `name'.  The attributes in `env' are added to the
@@ -286,16 +341,17 @@ rec {
   writeText = name: text: runCommand name {inherit text;} "echo -n \"$text\" > $out";
 
   writeScript = name: text: runCommand name {inherit text;} "echo -n \"$text\" > $out; chmod +x $out";
-  
-  stdenvNewSetupScript = overrideSetup stdenv ../stdenv/generic/setup-new.sh;
-
+ 
+  writeScriptBin = name: text: runCommand name {inherit text;} "mkdir -p \$out/bin; echo -n \"\$text\" > \$out/bin/\$name ; chmod +x \$out/bin/\$name";
+ 
   substituteAll = import ../build-support/substitute/substitute-all.nix {
-    stdenv = stdenvNewSetupScript;
+    inherit stdenv;
   };
 
   nukeReferences = import ../build-support/nuke-references/default.nix {
     inherit stdenv;
   };
+  
 
   ### TOOLS
 
@@ -308,6 +364,12 @@ rec {
     inherit fetchurl stdenv zlib wxGTK;
   };
 
+  avahi = selectVersion ../development/libraries/avahi "0.6.22" {
+    inherit stdenv fetchurl pkgconfig libdaemon dbus perl perlXMLParser qt4
+      python expat;
+    inherit (gtkLibs) glib gtk;
+  };
+
   axel = import ../tools/networking/axel {
     inherit fetchurl stdenv;
   };
@@ -338,7 +400,7 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  bzip2 = useFromStdenv (stdenv ? bzip2) stdenv.bzip2
+  bzip2 = useFromStdenv "bzip2"
     (import ../tools/compression/bzip2 {
       inherit fetchurl stdenv;
     });
@@ -347,11 +409,15 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  chkrootkit = import ../tools/security/chkrootkit {
+    inherit fetchurl stdenv;
+  };
+
   cksfv = import ../tools/networking/cksfv {
     inherit fetchurl stdenv;
   };
 
-  coreutils = useFromStdenv (stdenv ? coreutils) stdenv.coreutils
+  coreutils = useFromStdenv "coreutils"
     ((if stdenv ? isDietLibC
       then import ../tools/misc/coreutils-5
       else import ../tools/misc/coreutils)
@@ -383,11 +449,19 @@ rec {
     inherit fetchurl stdenv groff nettools coreutils iputils gnused bash;
   };
 
-  diffutils = useFromStdenv (stdenv ? diffutils) stdenv.diffutils
+  diffutils = useFromStdenv "diffutils"
     (import ../tools/text/diffutils {
       inherit fetchurl stdenv coreutils;
     });
 
+  dosfstoolsFun = lib.sumArgs (selectVersion ../tools/misc/dosfstools)
+  {
+    inherit builderDefs;
+    version = "2.11deb";
+  };
+
+  dosfstools = dosfstoolsFun null;
+
   ed = import ../tools/text/ed {
     inherit fetchurl stdenv;
   };
@@ -414,7 +488,7 @@ rec {
     qt = qt3;
   };
 
-  findutils = useFromStdenv (stdenv ? findutils) stdenv.findutils
+  findutils = useFromStdenv "findutils"
     (if system == "i686-darwin" then findutils4227 else
       import ../tools/misc/findutils {
         inherit fetchurl stdenv coreutils;
@@ -429,16 +503,28 @@ rec {
     inherit stdenv findutils;
   }));
 
+  finger_bsd = import ../tools/networking/bsd-finger {
+	  inherit fetchurl stdenv;
+  };
+
   fontforge = import ../tools/misc/fontforge {
     inherit fetchurl stdenv gettext freetype zlib
       libungif libpng libjpeg libtiff libxml2;
   };
 
-  gawk = useFromStdenv (stdenv ? gawk) stdenv.gawk
+  gawk = useFromStdenv "gawk"
     (import ../tools/text/gawk {
       inherit fetchurl stdenv;
     });
 
+  gdmapFun = lib.sumArgs (selectVersion ../tools/system/gdmap "0.7.5") {
+    inherit stdenv fetchurl builderDefs pkgconfig libxml2
+      intltool;
+    inherit (gtkLibs) gtk;
+  };
+
+  gdmap = gdmapFun null;
+
   getopt = import ../tools/misc/getopt {
     inherit fetchurl stdenv;
   };
@@ -448,12 +534,12 @@ rec {
     inherit (xlibs) libXext;
   };
 
-  gnugrep = useFromStdenv (stdenv ? gnugrep) stdenv.gnugrep
+  gnugrep = useFromStdenv "gnugrep"
     (import ../tools/text/gnugrep {
       inherit fetchurl stdenv pcre;
     });
 
-  gnupatch = useFromStdenv (stdenv ? patch) stdenv.patch (import ../tools/text/gnupatch {
+  gnupatch = useFromStdenv "patch" (import ../tools/text/gnupatch {
     inherit fetchurl stdenv;
   });
 
@@ -462,6 +548,11 @@ rec {
     ideaSupport = true; # enable for IDEA crypto support
   };
 
+  gnupg2 = import ../tools/security/gnupg2 {
+	  inherit fetchurl stdenv readline openldap bzip2 zlib libgpgerror pth
+	    libgcrypt libassuan libksba libusb curl;
+  };
+
   gnuplot = import ../tools/graphics/gnuplot {
     inherit fetchurl stdenv zlib gd texinfo;
   };
@@ -472,7 +563,7 @@ rec {
     x11Support = true;
   };
 
-  gnused = useFromStdenv (stdenv ? gnused) stdenv.gnused
+  gnused = useFromStdenv "gnused"
     (import ../tools/text/gnused {
       inherit fetchurl stdenv;
     });
@@ -481,7 +572,7 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  gnutar = useFromStdenv (stdenv ? gnutar) stdenv.gnutar
+  gnutar = useFromStdenv "gnutar"
     (import ../tools/archivers/gnutar {
       inherit fetchurl stdenv;
     });
@@ -504,7 +595,7 @@ rec {
       (import ./all-packages.nix {system = "i686-linux";}).grub
     else 
       import ../tools/misc/grub {
-        inherit fetchurl stdenv;
+        inherit fetchurl stdenv autoconf automake;
       };
 
   gtkgnutella = import ../tools/networking/p2p/gtk-gnutella {
@@ -512,15 +603,27 @@ rec {
     inherit (gtkLibs) glib gtk;
   };
 
-  gzip = useFromStdenv (stdenv ? gzip) stdenv.gzip
+  gzip = useFromStdenv "gzip"
     (import ../tools/compression/gzip {
       inherit fetchurl stdenv;
     });
 
+  hddtemp = import ../tools/hddtemp {
+    inherit fetchurl stdenv;
+  };
+
   hevea = import ../tools/typesetting/hevea {
     inherit fetchurl stdenv ocaml;
   };
 
+  /*hyppocampusFun = lib.sumArgs ( selectVersion ../tools/misc/hyppocampus "0.3rc1") {
+    inherit builderDefs stdenv fetchurl libdbi libdbiDrivers fuse
+      pkgconfig perl gettext dbus dbus_glib pcre libscd;
+    inherit (gtkLibs) glib;
+    bison = bison23;
+    flex = flex2533;
+  };*/
+
   jdiskreport = import ../tools/misc/jdiskreport {
     inherit fetchurl stdenv unzip jdk;
   };
@@ -554,10 +657,36 @@ rec {
     inherit fetchurl stdenv ghc tetex polytable;
   };
 
+  lout = import ../tools/typesetting/lout {
+    inherit fetchurl stdenv ghostscript;
+  };
+
+  lzma = import ../tools/compression/lzma {
+    inherit fetchurl stdenv;
+  };
+
+  lsh = import ../tools/networking/lsh {
+    inherit stdenv fetchurl gperf guile gmp zlib liboop gnum4;
+  };
+
   man = import ../tools/misc/man {
+     inherit fetchurl stdenv groff less;
+  };
+
+  man_db = import ../tools/misc/man-db {
      inherit fetchurl stdenv db4 groff;
   };
 
+  memtest86 = import ../tools/misc/memtest86 {
+     inherit fetchurl stdenv;
+  };
+
+  mc = import ../tools/misc/mc {
+     inherit fetchurl stdenv pkgconfig ncurses shebangfix perl zip;
+     inherit (gtkLibs) glib;
+     inherit (xlibs) libX11;
+  };
+
   mjpegtools = import ../tools/video/mjpegtools {
     inherit fetchurl stdenv libjpeg;
     inherit (xlibs) libX11;
@@ -567,6 +696,16 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  mssys = import ../tools/misc/mssys {
+    inherit fetchurl stdenv gettext;
+  };
+
+  nc6Fun = lib.sumArgs (selectVersion ../tools/networking/nc6 "1.0") {
+    inherit builderDefs;
+  };
+
+  nc6 = nc6Fun null;
+
   ncat = import ../tools/networking/ncat {
     inherit fetchurl stdenv openssl;
   };
@@ -622,6 +761,10 @@ rec {
     inherit (xlibs) libX11;
   };
 
+  psmisc = import ../tools/misc/psmisc {
+    inherit stdenv fetchurl ncurses;
+  };
+
   pwgen = import ../tools/security/pwgen {
     inherit stdenv fetchurl;
   };
@@ -636,6 +779,14 @@ rec {
     zlibSupport = !stdenv ? isDietLibC;
   };
 
+  relfsFun = lib.sumArgs (selectVersion ../tools/misc/relfs "cvs.2007.12.01") {
+    inherit fetchcvs stdenv ocaml postgresql fuse pcre
+      builderDefs e2fsprogs pkgconfig;
+    inherit (gnome) gnomevfs GConf;
+  };
+
+  relfs = relfsFun null;
+
   replace = import ../tools/text/replace {
     inherit fetchurl stdenv;
   };
@@ -647,6 +798,12 @@ rec {
   };
   */
 
+  rlwrapFun = lib.sumArgs (selectVersion ../tools/misc/rlwrap "0.28") {
+    inherit builderDefs readline;
+  };
+
+  rlwrap = rlwrapFun null;
+
   rpm = import ../tools/package-management/rpm {
     inherit fetchurl stdenv cpio zlib bzip2 file sqlite beecrypt neon elfutils;
   };
@@ -659,10 +816,30 @@ rec {
     inherit fetchurl stdenv ncurses;
   };
 
+  sharutils = selectVersion ../tools/archivers/sharutils "4.6.3" {
+    inherit fetchurl stdenv;
+  };
+
+  shebangfix = import ../tools/misc/shebangfix {
+    inherit stdenv perl;
+  };
+
   smartmontools = import ../tools/system/smartmontools {
     inherit fetchurl stdenv;
   };
 
+  smbfsFuseFun = lib.sumArgs (selectVersion ../tools/networking/smbfs-fuse "0.8.7") {
+    inherit builderDefs samba fuse;
+  };
+
+  smbfsFuse = smbfsFuseFun null;
+
+  socatFun = lib.sumArgs (selectVersion ../tools/networking/socat "1.6.0.0") {
+    inherit builderDefs openssl;
+  };
+
+  socat = socatFun null;
+
   sudo = import ../tools/security/sudo {
     inherit fetchurl stdenv coreutils pam;
   };
@@ -695,6 +872,10 @@ rec {
     inherit fetchurl stdenv ncurses;
   };
 
+  vpnc = import ../tools/networking/vpnc {
+    inherit fetchurl stdenv libgcrypt perl;
+  };
+
   testdisk = import ../tools/misc/testdisk {
     inherit fetchurl stdenv ncurses libjpeg e2fsprogs zlib openssl;
   };
@@ -733,17 +914,19 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  wget = import ../tools/networking/wget {
+  wgetFun = lib.sumArgs (selectVersion ../tools/networking/wget "1.11") {
     inherit fetchurl stdenv gettext;
   };
 
+  wget = wgetFun null;
+
   which = import ../tools/system/which {
-    inherit fetchurl stdenv;
+    inherit fetchurl stdenv readline;
   };
 
   wv = import ../tools/misc/wv {
     inherit fetchurl stdenv libpng zlib imagemagick
-	pkgconfig libgsf libxml2;
+      pkgconfig libgsf libxml2 bzip2;
     inherit (gtkLibs) glib;
   };
 
@@ -795,7 +978,7 @@ rec {
   ### SHELLS
 
 
-  bash = lowPrio (useFromStdenv (stdenv ? bash) stdenv.bash
+  bash = lowPrio (useFromStdenv "bash"
     (import ../shells/bash {
       inherit fetchurl stdenv;
       bison = bison23;
@@ -811,10 +994,12 @@ rec {
     inherit fetchurl stdenv ncurses;
   };
 
-  zsh = import ../shells/zsh {
+  zshFun = lib.sumArgs (selectVersion ../shells/zsh "4.3.5") {
     inherit fetchurl stdenv ncurses coreutils;
   };
 
+  zsh = zshFun null;
+
 
   ### DEVELOPMENT / COMPILERS
 
@@ -835,6 +1020,11 @@ rec {
       inherit stdenv fetchurl jre;
     };
 
+  bigloo = import ../development/compilers/bigloo {
+    inherit fetchurl mkDerivationByConfiguration lib;
+    stdenv = overrideGCC stdenv gcc34;
+  };
+
   dylan = import ../development/compilers/gwydion-dylan {
     inherit fetchurl stdenv perl boehmgc yacc flex readline;
     dylan =
@@ -913,9 +1103,7 @@ rec {
     profiledCompiler = false;
   });
 
-  gcc41NPTL = wrapGCCWithGlibc gcc41.gcc glibcNPTL;
-
-  gcc42 = useFromStdenv (stdenv ? gcc) stdenv.gcc (wrapGCC (import ../development/compilers/gcc-4.2 {
+  gcc42 = useFromStdenv "gcc" (wrapGCC (import ../development/compilers/gcc-4.2 {
     inherit fetchurl stdenv noSysDirs;
     profiledCompiler = true;
   }));
@@ -925,46 +1113,248 @@ rec {
     profiledCompiler = true;
   });
 
-  # This new ghc stuff is under heavy development and might change ! 
+  # This new ghc stuff is under heavy development and will change ! 
+  # =========  =======================================================
 
-  # usage: see ghcPkgUtil.sh - use setup-new2 because of PATH_DELIMITER
+  # usage: see ghcPkgUtil.sh
+  # depreceated -> use functions defined in builderDefs
   ghcPkgUtil = runCommand "ghcPkgUtil-internal" 
      { ghcPkgUtil = ../development/libraries/haskell/generic/ghcPkgUtil.sh; }
      "mkdir -p $out/nix-support; cp $ghcPkgUtil \$out/nix-support/setup-hook;";
 
-  ghcsAndLibs = recurseIntoAttrs (import ../development/compilers/ghcs {
-      inherit ghcboot fetchurl recurseIntoAttrs perl gnum4 gmp readline;
-      inherit ghcPkgUtil;
-      stdenv = stdenvUsingSetupNew2;
-      lib = lib_unstable;
-  });
+  ghcsAndLibs = 
+    assert builtins ? listToAttrs;
+    recurseIntoAttrs (import ../development/compilers/ghcs {
+      inherit ghcboot fetchurl stdenv recurseIntoAttrs perl gnum4 gmp readline lib;
+      inherit ghcPkgUtil annotatedDerivations hasktags ctags;
+    });
 
   # creates ghc-X-wl wich adds the passed libraries to the env var GHC_PACKAGE_PATH
   createGhcWrapper = { ghcPackagedLibs ? false, ghc, libraries, name, suffix ? "ghc_wrapper_${ghc.name}" } :
         import ../development/compilers/ghc/createGhcWrapper {
-    inherit ghcPackagedLibs ghc name suffix libraries ghcPkgUtil;
-    stdenv = stdenvUsingSetupNew2;
+    inherit stdenv ghcPackagedLibs ghc name suffix libraries ghcPkgUtil
+      annotatedDerivations lib sourceWithTagsDerivation annotatedWithSourceAndTagInfo;
+    installSourceAndTags = true;
+  };
+
+
+  # args must contain src name buildInputs
+  # classic expression style.. seems to work fine
+  # used now
+  #
+  # args must contain: src name buildInputs propagatedBuildInputs
+  # classic expression style.. seems to work fine
+  # used now
+  # goSrc contains source directory (containing the .cabal file)
+  ghcCabalDerivation = args : null_ : with lib; with args;
+    stdenv.mkDerivation ({
+      goSrcDir = "cd ${srcDir}";
+      inherit name src propagatedBuildInputs;
+      phases = "unpackPhase patchPhase buildPhase";
+      buildInputs = (if (args ? buildInputs) then args.buildInputs else [])
+                    ++ [ ghcPkgUtil ];
+      # TODO remove echo line
+      buildPhase ="
+          createEmptyPackageDatabaseAndSetupHook
+          export GHC_PACKAGE_PATH
+
+          \$goSrcDir
+          ghc --make Setup.*hs -o setup
+          CABAL_SETUP=./setup
+
+          nix_ghc_pkg_tool join local-pkg-db
+
+          \$CABAL_SETUP configure --package-db=local-pkg-db
+          \$CABAL_SETUP build
+          \$CABAL_SETUP copy --destdir=\$out
+          \$CABAL_SETUP register --gen-script
+          sed -e \"s=/usr/local/lib=\$out/usr/local/lib=g\" \\
+              -e \"s#bin/ghc-pkg --package-conf.*#bin/ghc-pkg --package-conf=\$PACKAGE_DB register -#\" \\
+              -i register.sh
+          ./register.sh
+          rm \${PACKAGE_DB}.old
+
+         ensureDir \"\$out/nix-support\"
+
+         echo \"\$propagatedBuildInputs\" > \"\$out/nix-support/propagated-build-inputs\"
+      ";
+  } // (subsetmap id args [ "patchPhase" ])); 
+
+  # creates annotated derivation (comments see above
+  annotatedGhcCabalDerivation = args : null_ : with lib; with args;
+  rec {
+    inherit name;
+
+    #aDeps = concatLists ( catAttrs ( subsetmap id args [ "buildInputs" "propagatedBuildInputs" ] ) );
+    aDeps = []; #TODO 
+
+    aDeriv = ghcCabalDerivation (args // (annotatedDerivations.delAnnotationsFromInputs args) ) null;
+
+   # annotation data
+
+    sourceWithTags = {
+     inherit src srcDir;
+     name = name + "-src-with-tags";
+     createTagFiles = [
+           { name = "${name}_haskell_tags";
+             # tagCmd = "${toString ghcsAndLibs.ghc68.ghc}/bin/hasktags --ctags `find . -type f -name \"*.*hs\"`; sort tags > \$TAG_FILE"; }
+             tagCmd = "${toString hasktags}/bin/hasktags-modified --ctags `find . -type f -name \"*.*hs\"`; sort tags > \$TAG_FILE"; }
+      ];
+    };
   };
 
+  # this will change in the future 
+  # TODO enhance speed ! ?
+  ghc68_extra_libs = ghc: rec {
+      #   name (using lowercase letters everywhere because using installing packages having different capitalization is discouraged) - this way there is not that much to remember?
+
+      cabal_darcs_name = "cabal-darcs";
+
+      # introducing p here to speed things up.
+      # It merges derivations (defined below) and additional inputs. I hope that using as few nix functions as possible results in greates speed?
+      # unfortunately with x; won't work because it forces nix to evaluate all attributes of x which would lead to infinite recursion
+      pkgs = let x = ghc.core_libs // derivations; in {
+          # ghc extra packages 
+          mtl     = { name="mtl-1.1.0.0";     srcDir="libraries/mtl";    p_deps=[ x.base ]; src = ghc.extra_src; };
+          parsec  = { name="parsec-2.1.0.0";  srcDir="libraries/parsec"; p_deps=[ x.base ];       src = ghc.extra_src; };
+          network = { name="network-2.1.0.0"; srcDir="libraries/network"; p_deps=[ x.base x.parsec x.haskell98 ];       src = ghc.extra_src; };
+          regex_base = { name="regex-base-0.72.0.1"; srcDir="libraries/regex-base"; p_deps=[ x.base x.array x.bytestring x.haskell98 ]; src = ghc.extra_src; };
+          regex_posix = { name="regex-posix-0.72.0.2"; srcDir="libraries/regex-posix"; p_deps=[ x.regex_base x.haskell98 ]; src = ghc.extra_src; };
+          regex_compat = { name="regex-compat-0.71.0.1"; srcDir="libraries/regex-compat"; p_deps=[ x.base x.regex_posix x.regex_base x.haskell98 ]; src = ghc.extra_src; };
+          stm = { name="stm-2.1.1.0"; srcDir="libraries/stm"; p_deps=[ x.base x.array ]; src = ghc.extra_src; };
+          hunit = { name="HUnit-1.2.0.0"; srcDir="libraries/HUnit"; p_deps=[ x.base ]; src = ghc.extra_src; };
+          quickcheck = { name="QuickCheck-1.1.0.0"; srcDir="libraries/QuickCheck"; p_deps=[x.base x.random]; src = ghc.extra_src; };
+
+
+          # other pacakges  (hackage etc)
+          binary = rec { name = "binary-0.4.1"; p_deps = [ x.base x.bytestring x.containers x.array ];
+                           src = fetchurl { url = "http://hackage.haskell.org/packages/archive/binary/0.4.1/binary-0.4.1.tar.gz";
+                                        sha256 = "0jg5i1k5fz0xp1piaaf5bzhagqvfl3i73hlpdmgs4gc40r1q4x5v"; };
+                 };
+          # 1.13 is stable. There are more recent non stable versions
+          haxml = rec { name = "HaXml-1.13.3"; p_deps = [ x.base x.rts x.directory x.process x.pretty x.containers x.filepath x.haskell98 ];
+                       src = fetchurl { url = "http://www.haskell.org/HaXml/${name}.tar.gz";
+                                        sha256 = "08d9wy0rg9m66dd10x0zvkl74l25vxdakz7xp3j88s2gd31jp1v0"; };
+                 };
+          xhtml = rec { name = "xhtml-3000.0.2.2"; p_deps = [ x.base ];
+                       src = fetchurl { url = "http://hackage.haskell.org/packages/archive/xhtml/3000.0.2.2/xhtml-3000.0.2.2.tar.gz";
+                                        sha256 = "112mbq26ksh7r22y09h0xvm347kba3p4ns12vj5498fqqj333878"; };
+                 };
+          html = rec { name = "html-1.0.1.1"; p_deps = [ x.base ];
+                       src = fetchurl { url = "http://hackage.haskell.org/packages/archive/html/1.0.1.1/html-1.0.1.1.tar.gz";
+                                        sha256 = "10fayfm18p83zlkr9ikxlqgnzxg1ckdqaqvz6wp1xj95fy3p6yl1"; };
+                 };
+          crypto = rec { name = "crypto-4.1.0"; p_deps = [ x.base x.array x.pretty x.quickcheck x.random x.hunit ];
+                       src = fetchurl { url = "http://hackage.haskell.org/packages/archive/Crypto/4.1.0/Crypto-4.1.0.tar.gz";
+                                        sha256 = "13rbpbn6p1da6qa9m6f7dmkzdkmpnx6jiyyndzaz99nzqlrwi109"; };
+                 };
+          hslogger = rec { name = "hslogger-1.0.4"; p_deps = [ x.containers x.directory x.mtl x.network x.process];
+                       src = fetchurl { url = "http://hackage.haskell.org/packages/archive/hslogger/1.0.4/hslogger-1.0.4.tar.gz";
+                                        sha256 = "0kmz8xs1q41rg2xwk22fadyhxdg5mizhw0r4d74y43akkjwj96ar"; };
+                 };
+          parsep = { name = "parsep-0.1"; p_deps = [ x.base x.mtl x.bytestring ];
+                         src = fetchurl { url = "http://twan.home.fmf.nl/parsep/parsep-0.1.tar.gz";
+                                        sha256 = "1y5pbs5mzaa21127cixsamahlbvmqzyhzpwh6x0nznsgmg2dpc9q"; };
+                         patchPhase = "pwd; sed -i 's/fps/bytestring/' *.cabal";
+                 };
+
+        # HAPPS - Libraries
+          http_darcs = { name="http-darcs"; p_deps = [x.network x.parsec];
+                   src = fetchdarcs { url = "http://darcs.haskell.org/http/"; md5 = "4475f858cf94f4551b77963d08d7257c"; };
+                 };
+          syb_with_class_darcs = { name="syb-with-class-darcs"; p_deps = [x.template_haskell x.bytestring ];
+                   src = fetchdarcs { url = "http://happs.org/HAppS/syb-with-class"; md5 = "b42336907f7bfef8bea73bc36282d6ac"; };
+                 };
+
+        happs_data_darcs = { name="HAppS-Data-darcs"; p_deps=[ x.base x.mtl x.template_haskell x.syb_with_class_darcs x.haxml x.happs_util_darcs x.regex_compat x.bytestring x.pretty ];
+                    src = fetchdarcs { url = "http://happs.org/repos/HAppS-Data"; md5 = "10c505dd687e9dc999cb187090af9ba7"; };
+                    };
+        happs_util_darcs = { name="HAppS-Util-darcs"; p_deps=[ x.base x.mtl x.hslogger x.template_haskell x.array x.bytestring x.old_time x.process x.directory ];
+                    src = fetchdarcs { url = "http://happs.org/repos/HAppS-Util"; md5 = "693cb79017e522031c307ee5e59fc250"; };
+                    };
+        happs_state_darcs = { name="HAppS-State-darcs"; p_deps=[ x.base x.haxml
+                      x.mtl x.network x.stm x.template_haskell x.hslogger
+                        x.happs_util_darcs x.happs_data_darcs x.bytestring x.containers
+                        x.random x.old_time x.old_locale x.unix x.directory x.binary ];
+                      src = fetchdarcs { url = "http://happs.org/repos/HAppS-State"; 
+                                         md5 = "956e5c293b60f4a98148fedc5fa38acc"; 
+                                       };
+                    };
+        happs_plugins_darcs = { name="HAppS-plugins-darcs"; p_deps=[ x.base x.mtl x.hslogger x.happs_util_darcs x.happs_data_darcs x.happs_state_darcs ];
+                    src = fetchdarcs { url = "http://happs.org/repos/HAppS-Util"; md5 = "693cb79017e522031c307ee5e59fc250"; };
+                    };
+        # there is no .cabal yet 
+        #happs_smtp_darcs = { name="HAppS-smtp-darcs"; p_deps=[];
+                    #src = fetchdarcs { url = "http://happs.org/repos/HAppS-smtp"; md5 = "5316917e271ea1ed8ad261080bcb47db"; };
+                    #};
+
+        happs_ixset_darcs = { name="HAppS-IxSet-darcs"; p_deps=[ x.base x.mtl
+                          x.hslogger x.happs_util_darcs x.happs_state_darcs x.happs_data_darcs
+                          x.template_haskell x.syb_with_class_darcs x.containers ];
+                    src = fetchdarcs { url = "http://happs.org/repos/HAppS-IxSet"; 
+                                       #md5 = "fa6b24517f09aa16e972f087430967fd"; 
+                                       #tag = "0.9.2";
+                                        # no tag
+                                       md5 = "fa6b24517f09aa16e972f087430967fd"; 
+                                     };
+                    };
+        happs_server_darcs = { name="HAppS-Server-darcs"; p_deps=[x.haxml x.parsec x.mtl
+                x.network x.regex_compat x.hslogger x.happs_data_darcs
+                  x.happs_util_darcs x.happs_state_darcs x.happs_ixset_darcs x.http_darcs
+                  x.template_haskell x.xhtml x.html x.bytestring x.random
+                  x.containers x.old_time x.old_locale x.directory x.unix];
+                    src = fetchdarcs { url = "http://happs.org/repos/HAppS-HTTP"; md5 = "e1bb17eb30a39d30b8c34dffbf80edc2"; };
+                    };
+        # we need recent version of cabal (because only this supports --pkg-config propably) Thu Feb  7 14:54:07 CET 2008
+        # is be added to buildInputs automatically
+        cabal_darcs = { name=cabal_darcs_name; p_deps = with ghc.core_libs; [base rts directory process pretty containers filepath];
+                  src = fetchdarcs { url = "http://darcs.haskell.org/cabal"; md5 = "8b0bc3c7f2676ce642f98b1568794cd6"; };
+                };
+      };
+      toDerivation = attrs : with attrs;
+      # result is { mtl = <deriv>;
+        annotatedGhcCabalDerivation ({
+            inherit name src;
+            propagatedBuildInputs = p_deps ++ (lib.optional (attrs.name != cabal_darcs_name) derivations.cabal_darcs );
+            srcDir = if attrs ? srcDir then attrs.srcDir else ".";
+            patches = if attrs ? patches then attrs.patches else [];
+            # add cabal, take deps either from this list or from ghc.core_libs 
+        }//( lib.subsetmap lib.id attrs [ "patchPhase" ] )) null;
+      derivations = with lib; builtins.listToAttrs (lib.concatLists ( lib.mapRecordFlatten 
+                ( n : attrs : let d = (toDerivation attrs); in [ (nv n d) (nv attrs.name d) ] ) pkgs ) );
+    }.derivations;
+
+
   # the wrappers basically does one thing: It defines GHC_PACKAGE_PATH before calling ghc{i,-pkg}
   # So you can have different wrappers with different library combinations
-  # So installing ghc libraries isn't done by nix-env -i package but by adding the lib to the libraries list below
+  # So installing ghc libraries isn't done by nix-env -i package but by adding
+  # the lib to the libraries list below
+  # Doesn't create that much useless symlinks (you seldomly want to read the
+  # .hi and .o files, right?
   ghcLibraryWrapper68 = 
     let ghc = ghcsAndLibs.ghc68.ghc; in
     createGhcWrapper rec {
       ghcPackagedLibs = true;
-      name = "ghc68_wrapper";
-      suffix = "68wrapper";
-      libraries = map ( a : __getAttr a ghcsAndLibs.ghc68.core_libs ) 
-        [ "old-locale-1.0" "old-time-1.0" "filepath-1.0" "directory-1.0" "array-0.1" "containers-0.1" 
-          "hpc-0.5" "bytestring-0.9" "pretty-1.0" "packedstring-0.1" "template-haskell-0.1" 
-          "unix-2.0" "process-1.0" "readline-1.0" "Cabal-1.2.0" "random-1.0" "haskell98-1.0" "ghc-6.8.0.20071004"
-          "array-0.1" "bytestring-0.9" "containers-0.1" "directory-1.0" "filepath-1.0"
-          "ghc-6.8.0.20071004" "haskell98-1.0" "hpc-0.5" "old-locale-1.0" "old-time-1.0" 
-          "packedstring-0.1" "pretty-1.0" "process-1.0" "random-1.0"
-          "readline-1.0" "rts-1.0" "template-haskell-0.1" "unix-2.0"
-        ];
-        # (flatten ghcsAndLibs.ghc68.core_libs);
+      name = "ghc${ghc.version}_wrapper";
+      suffix = "${ghc.version}wrapper";
+      libraries = # map ( a : __getAttr a (ghc68_extra_libs ghcsAndLibs.ghc68 ) ) [ "mtl" ];
+        # core_libs  distributed with this ghc version
+        #(lib.flattenAttrs ghcsAndLibs.ghc68.core_libs)
+          map ( a : __getAttr a ghcsAndLibs.ghc68.core_libs ) [ 
+            "cabal" "array" "base" "bytestring" "containers" "containers" "directory"
+            "filepath" "ghc-${ghc.version}" "haskell98" "hpc" "old_locale" "old_time"
+            "old_time" "packedstring" "pretty" "process" "random" "readline" "rts"
+            "template_haskell" "unix" "template_haskell" ]
+        # some extra libs
+
+           ++  (lib.flattenAttrs (ghc68_extra_libs ghcsAndLibs.ghc68) );
+        # or specify the ones you want to install using this list (possible values see attributes in ghc68_extra_libs
+           #++ map ( a : __getAttr a (ghc68_extra_libs ghcsAndLibs.ghc68 ) )
+           #[ "mtl" "parsec" "cabal_darcs" "haxml" "network" "regex_base"
+           #"regex_compat" "regex_posix" "stm" "hunit" "quickcheck" "crypto"
+           #"hslogger" "http_darcs" "syb_with_class_darcs"
+           #];
+        # some additional libs
       inherit ghc;
   };
 
@@ -973,13 +1363,13 @@ rec {
   #  m4 = gnum4;
   #};
 
-  ghc = ghc661;
+  ghc = ghc68;
 
-  ghc68 = lowPrio (appendToName "snapshot" (import ../development/compilers/ghc-6.8 {
+  ghc68 = import ../development/compilers/ghc-6.8 {
     inherit fetchurl stdenv readline perl gmp ncurses;
     m4 = gnum4;
     ghc = ghcboot;
-  }));
+  };
 
   ghc661 = import ../development/compilers/ghc-6.6.1 {
     inherit fetchurl stdenv readline perl gmp ncurses;
@@ -1011,9 +1401,24 @@ rec {
       libraries = [];
     };
   */
+  
+  gwt = import ../development/compilers/gwt {
+    inherit stdenv fetchurl;
+    inherit (gtkLibs) glib gtk pango atk;
+    inherit (xlibs) libX11 libXt;
+    libstdcpp5 = gcc33.gcc;
+  };
 
   helium = import ../development/compilers/helium {
-    inherit fetchurl stdenv ghc;
+    inherit fetchurl stdenv;
+    ghc = ghc661;
+  };
+
+  javafront = import ../development/compilers/java-front {
+    inherit stdenv fetchurl pkgconfig;
+    sdf = sdf24;
+    aterm = aterm25;
+    strategoxt = strategoxt017;
   };
 
   #TODO add packages http://cvs.haskell.org/Hugs/downloads/2006-09/packages/ and test
@@ -1028,6 +1433,12 @@ rec {
       inherit fetchurl stdenv;
     };
 
+  jdk5 =
+    assert system == "i686-linux" || system == "x86_64-linux";
+    import ../development/compilers/jdk/default-5.nix {
+      inherit fetchurl stdenv unzip;
+    };
+  
   jdk       = jdkdistro true  false;
   jre       = jdkdistro false false;
 
@@ -1059,17 +1470,18 @@ rec {
     inherit stdenv perl;
   };
 
+  monotone = import ../applications/version-management/monotone {
+    inherit stdenv fetchurl boost zlib;
+  };
+
   nasm = import ../development/compilers/nasm {
     inherit fetchurl stdenv;
   };
 
-  ocaml = import ../development/compilers/ocaml {
-    inherit fetchurl stdenv x11 ncurses;
-  };
+  ocaml = getVersion  "ocaml" ocaml_alts;
 
-  ocaml3080 = import ../development/compilers/ocaml/ocaml-3.08.0.nix {
-    inherit fetchurl x11;
-    stdenv = overrideGCC stdenv gcc34;
+  ocaml_alts = import ../development/compilers/ocaml {
+    inherit fetchurl stdenv x11 ncurses;
   };
 
 /*
@@ -1096,10 +1508,19 @@ rec {
 
   qcmm = import ../development/compilers/qcmm {
     lua   = lua4;
-    ocaml = ocaml3080;
+    ocaml = builtins.getAttr "3.08.0" ocaml_alts;
     inherit fetchurl stdenv mk noweb groff;
   };
 
+  roadsend = import ../development/compilers/roadsend {
+    inherit fetchurl stdenv flex bison mkDerivationByConfiguration bigloo lib curl;
+    # optional features
+    # all features pcre, fcgi xml mysql, sqlite3, (not implemented: odbc gtk gtk2)
+    flags = ["pcre" "fcgi" "xml" "mysql"];
+    inherit mysql;
+    inherit libxml2;
+  };
+
   strategoLibraries = import ../development/compilers/strategoxt/libraries/stratego-libraries-0.17pre.nix {
     inherit stdenv fetchurl pkgconfig aterm;
   };
@@ -1109,6 +1530,13 @@ rec {
     stdenv = overrideInStdenv stdenv [gnumake380];
   };
 
+  strategoxt017 = import ../development/compilers/strategoxt/strategoxt-0.17.nix {
+    inherit fetchurl pkgconfig;
+    sdf = sdf24;
+    aterm = aterm25;
+    stdenv = overrideInStdenv stdenv [gnumake380];
+  };
+
   strategoxtUtils = import ../development/compilers/strategoxt/utils {
     inherit fetchurl pkgconfig stdenv aterm sdf strategoxt;
   };
@@ -1134,6 +1562,13 @@ rec {
     inherit fetchurl stdenv cabextract;
   };
 
+  webdsl = import ../development/compilers/webdsl {
+    inherit stdenv fetchurl pkgconfig javafront;
+    aterm = aterm25;
+    sdf = sdf24;
+    strategoxt = strategoxt017;
+  };
+
   win32hello = import ../development/compilers/visual-c++/test {
     inherit fetchurl stdenv visualcpp windowssdk;
   };
@@ -1158,8 +1593,12 @@ rec {
     inherit (xlibs) libX11 libXau libXt;
   };
 
+  erlang = selectVersion ../development/interpreters/erlang "R12B-1" {
+    inherit fetchurl stdenv perl gnum4 ncurses openssl;
+  };
+
   guile = import ../development/interpreters/guile {
-    inherit fetchurl stdenv ncurses readline libtool gmp;
+    inherit fetchurl stdenv ncurses readline libtool gmp gawk makeWrapper;
   };
 
   kaffe =  import ../development/interpreters/kaffe {
@@ -1182,7 +1621,7 @@ rec {
   perl = if !stdenv.isLinux then sysPerl else realPerl;
 
   # FIXME: unixODBC needs patching on Darwin (see darwinports)
-  php = import ../development/interpreters/php {
+  phpOld = import ../development/interpreters/php {
     inherit stdenv fetchurl flex bison libxml2 apacheHttpd;
     unixODBC =
       if stdenv.isDarwin then null else unixODBC;
@@ -1192,40 +1631,35 @@ rec {
   # tell the apache module where to look for this file is using a compile time flag ;-(
   # perhaps this can be done setting php_value in apache don't have time to investigate any further ?
   # This expression is a quick hack now. But perhaps it helps you adding the configuration flags you need?
-  /*
+  php = php_unstable;
+
+  # compiling without xdebug is currenlty broken (should be easy to fix though 
   php_unstable = (import ../development/interpreters/php_configurable) {
-   inherit mkDerivationByConfiguration;
-   lib = lib_unstable;
-   stdenv = stdenvUsingSetupNew2;
-   inherit fetchurl flex bison apacheHttpd mysql; # gettext;
-   inherit libxml2;
+   inherit stdenv mkDerivationByConfiguration autoconf automake lib;
+   # optional features
+   inherit fetchurl flex bison apacheHttpd mysql libxml2; # gettext;
+   inherit zlib;
+   flags = [ "xdebug" "mysql" "mysqli" "pdo_mysql" "libxml2" "apxs2" ];
   };
-  */
 
-  python = import ../development/interpreters/python {
-    inherit fetchurl stdenv zlib bzip2;
-  };
+  python = getVersion "python" python_alts;
 
-  python25 = import ../development/interpreters/python/2.5 {
+  python_alts = import ../development/interpreters/python {
     inherit fetchurl stdenv zlib bzip2;
   };
 
-  pyrexFun = lib.sumArgs (import ../development/interpreters/pyrex) {
-  	inherit fetchurl stdenv stringsWithDeps lib builderDefs;
-	python = python25;
+  pyrexFun = lib.sumArgs (selectVersion ../development/interpreters/pyrex "0.9.6") {
+    inherit fetchurl stdenv stringsWithDeps lib builderDefs;
+	python = builtins.getAttr "2.5" python_alts;
   };
 
-  pyrex = pyrexFun {
-  	version = "0.9.6";
-  } null;
+  pyrex = pyrexFun null;
 
-  QiFun = lib.sumArgs (import ../development/compilers/qi) {
+  QiFun = lib.sumArgs (selectVersion ../development/compilers/qi "9.1") {
     inherit clisp stdenv fetchurl builderDefs unzip;
   };
 
-  Qi = QiFun {
-    version = getConfig ["Qi" "version"] "9.1";
-  } null;
+  Qi = QiFun null;
 
   realPerl = import ../development/interpreters/perl {
     inherit fetchurl stdenv;
@@ -1277,6 +1711,10 @@ rec {
     inherit fetchurl stdenv unzip;
   };
 
+  guileLib = import ../development/guile-modules/guile-lib {
+    inherit fetchurl stdenv guile;
+  };
+
   windowssdk = import ../development/misc/windows-sdk {
     inherit fetchurl stdenv cabextract;
   };
@@ -1285,6 +1723,10 @@ rec {
   ### DEVELOPMENT / TOOLS
 
 
+  alex = import ../development/tools/parsing/alex {
+    inherit cabal perl;
+  };
+
   antlr = import ../development/tools/parsing/antlr/antlr-2.7.6.nix {
     inherit fetchurl stdenv jre;
   };
@@ -1321,12 +1763,16 @@ rec {
     inherit fetchurl stdenv perl autoconf;
   };
 
+  automake110x = import ../development/tools/misc/automake/automake-1.10.x.nix {
+    inherit fetchurl stdenv perl autoconf;
+  };
+
   # commented out because it's using the new configuration style proposal which is unstable
   #avrdude = import ../development/tools/misc/avrdude {
   #  inherit lib fetchurl stdenv flex yacc;
   #};
 
-  binutils = useFromStdenv (stdenv ? binutils) stdenv.binutils
+  binutils = useFromStdenv "binutils"
     (import ../development/tools/misc/binutils {
       inherit fetchurl stdenv noSysDirs;
     });
@@ -1341,6 +1787,10 @@ rec {
     inherit fetchurl stdenv m4;
   };
 
+  ccache = import ../development/tools/misc/ccache {
+    inherit fetchurl stdenv;
+  };
+
   ctags = import ../development/tools/misc/ctags {
     inherit fetchurl stdenv;
   };
@@ -1349,16 +1799,23 @@ rec {
     inherit fetchurl stdenv replace;
   };
 
-  elfutils = import ../development/tools/misc/elfutils {
-    inherit fetchurl stdenv;
+  elfutilsFun = lib.sumArgs 
+    (selectVersion ../development/tools/misc/elfutils "0.131") {
+      inherit fetchurl stdenv;
   };
 
+  elfutils = elfutilsFun null;
+
   epm = import ../development/tools/misc/epm {
     inherit fetchurl stdenv rpm;
   };
 
   flex = flex254a;
 
+  flex2534 = import ../development/tools/parsing/flex/flex-2.5.34.nix {
+    inherit fetchurl stdenv yacc m4;
+  };
+
   flex2533 = import ../development/tools/parsing/flex/flex-2.5.33.nix {
     inherit fetchurl stdenv yacc m4;
   };
@@ -1377,7 +1834,7 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  gnumake = useFromStdenv (stdenv ? gnumake) stdenv.gnumake
+  gnumake = useFromStdenv "gnumake"
     (import ../development/tools/build-managers/gnumake {
       inherit fetchurl stdenv;
     });
@@ -1390,8 +1847,25 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  happy = import ../development/tools/parsing/happy {
-    inherit fetchurl stdenv perl ghc;
+  haddock = import ../development/tools/documentation/haddock {
+    inherit cabal;
+  };
+
+  guileLint = import ../development/tools/guile/guile-lint {
+    inherit fetchurl stdenv guile;
+  };
+
+  # happy = import ../development/tools/parsing/happy {
+  #   inherit fetchurl stdenv perl ghc;
+  # };
+
+  happy = import ../development/tools/parsing/happy/happy-1.17.nix {
+    inherit cabal perl;
+  };
+
+  hasktags = import ../development/tools/misc/hasktags {
+    inherit fetchurl stdenv;
+    ghc = ghcsAndLibs.ghc68.ghc;
   };
 
   help2man = import ../development/tools/misc/help2man {
@@ -1402,6 +1876,12 @@ rec {
     inherit fetchurl stdenv perl perlXMLSimple;
   };
 
+  indentFun = lib.sumArgs (selectVersion ../development/tools/misc/indent "2.2.9") {
+    inherit fetchurl stdenv builderDefs;
+  };
+
+  indent = indentFun null;
+
   jikespg = import ../development/tools/parsing/jikespg {
     inherit fetchurl stdenv;
   };
@@ -1424,11 +1904,13 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  ltrace = import ../development/tools/misc/ltrace {
-  	inherit fetchurl stdenv builderDefs stringsWithDeps lib 
-		elfutils;
+  ltraceFun = lib.sumArgs (selectVersion ../development/tools/misc/ltrace "0.5-3deb") {
+  	inherit fetchurl stdenv builderDefs stringsWithDeps lib;
+	elfutils = elfutilsFun {version = "0.127";} null;
   };
 
+  ltrace = ltraceFun null;
+
   mk = import ../development/tools/build-managers/mk {
     inherit fetchurl stdenv;
   };
@@ -1437,7 +1919,7 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  patchelf = useFromStdenv (stdenv ? patchelf) stdenv.patchelf
+  patchelf = useFromStdenv "patchelf"
     (import ../development/tools/misc/patchelf {
       inherit fetchurl stdenv;
     });
@@ -1446,11 +1928,16 @@ rec {
    * pkgconfig is optionally taken from the stdenv to allow bootstrapping
    * of glib and pkgconfig itself on MinGW.
    */
-  pkgconfig = useFromStdenv (stdenv ? pkgconfig) stdenv.pkgconfig
+  pkgconfig = useFromStdenv "pkgconfig"
     (import ../development/tools/misc/pkgconfig {
       inherit fetchurl stdenv;
     });
 
+  # couldn't find the source yet
+  selenium_rc_binary = import ../development/tools/selenium/remote-control {
+    inherit fetchurl stdenv unzip;
+  };
+
   scons = import ../development/tools/build-managers/scons {
     inherit fetchurl stdenv python;
   };
@@ -1462,6 +1949,14 @@ rec {
     stdenv = overrideInStdenv stdenv [gnumake380];
   };
 
+  sdf24 = import ../development/tools/parsing/sdf/sdf2-bundle-2.4.nix {
+    inherit fetchurl getopt pkgconfig;
+    aterm = aterm25;
+    # Note: sdf2-bundle currently requires GNU make 3.80; remove
+    # explicit dependency when this is fixed.
+    stdenv = overrideInStdenv stdenv [gnumake380];
+  };
+
   strace = import ../development/tools/misc/strace {
     inherit fetchurl stdenv;
   };
@@ -1489,9 +1984,7 @@ rec {
   };
 
   uuagc = import ../development/tools/haskell/uuagc {
-    inherit fetchurl stdenv;
-    ghc = ghc66;
-    uulib = uulib66;
+    inherit cabal uulib;
   };
 
   gdb = import ../development/tools/misc/gdb {
@@ -1516,6 +2009,10 @@ rec {
     inherit fetchurl stdenv ncurses;
   };
 
+  acl = import ../development/libraries/acl {
+    inherit stdenv fetchurl autoconf libtool gettext attr;
+  };
+
   /*
   agg = import ../development/libraries/agg {
     inherit fetchurl stdenv autoconf automake libtool pkgconfig;
@@ -1539,6 +2036,14 @@ rec {
     inherit (gnome) glib;
   };
 
+  aspell = import ../development/libraries/aspell {
+    inherit fetchurl stdenv perl;
+  };
+
+  aspellDicts = recurseIntoAttrs (import ../development/libraries/aspell/dictionaries.nix {
+    inherit fetchurl stdenv aspell which;
+  });
+
   aterm = lowPrio (import ../development/libraries/aterm {
     inherit fetchurl stdenv;
   });
@@ -1551,13 +2056,13 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  aspell = import ../development/libraries/aspell {
-    inherit fetchurl stdenv perl;
+  aterm25 = import ../development/libraries/aterm/2.5.nix {
+    inherit fetchurl stdenv;
   };
 
-  aspellDicts = recurseIntoAttrs (import ../development/libraries/aspell/dictionaries.nix {
-    inherit fetchurl stdenv aspell which;
-  });
+  attr = import ../development/libraries/attr {
+    inherit stdenv fetchurl autoconf libtool gettext;
+  };
 
   audiofile = import ../development/libraries/audiofile {
     inherit fetchurl stdenv;
@@ -1583,6 +2088,10 @@ rec {
     inherit fetchurl stdenv pkgconfig x11 fontconfig freetype zlib libpng;
   };
 
+  cairomm = import ../development/libraries/cairomm {
+    inherit fetchurl stdenv pkgconfig cairo x11 fontconfig freetype;
+  };
+
   chmlib = import ../development/libraries/chmlib {
     inherit fetchurl stdenv;
   };
@@ -1605,18 +2114,18 @@ rec {
     inherit fetchurl stdenv python;
   };
 
-  cluceneContrib = (import ../development/libraries/clucene-contrib) {
-    inherit fetchurl stdenv cluceneCore;
-   };
-
-   cluceneCore = (import ../development/libraries/clucene-core) {
-     inherit fetchurl stdenv;
-   };
+  cluceneCore = (import ../development/libraries/clucene-core) {
+    inherit fetchurl stdenv;
+  };
 
   coredumper = import ../development/libraries/coredumper {
     inherit fetchurl stdenv;
   };
 
+  ctl = import ../development/libraries/ctl {
+    inherit fetchurl stdenv ilmbase;
+  };
+
   cppunit = import ../development/libraries/cppunit {
 	  inherit fetchurl stdenv;
   };
@@ -1639,20 +2148,11 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  # I think, this is a bad practice to use getVersion for various build
-  # variants, but it's 5 o'clock now...
-  dbus = getVersion "dbus" dbus_alts;
-
-  dbus_alts = rec
-  {
-    noX11 = import ../development/libraries/dbus {
+  dbus = import ../development/libraries/dbus {
     inherit fetchurl stdenv pkgconfig expat;
-    };
-    withX11 = import ../development/libraries/dbus_x {
-	  inherit fetchurl stdenv pkgconfig expat;
 	  inherit (xlibs) libX11 libICE libSM;
-    };
-	default = noX11;
+    useX11 = getConfig [ "dbus" "tools" "useX11" ]
+      (getConfig [ "services" "xserver" "enable" ] false);
   };
 
   dbus_glib = import ../development/libraries/dbus-glib {
@@ -1668,7 +2168,7 @@ rec {
     inherit fetchurl stdenv perl;
   };
 
-  enchant = import ../development/libraries/enchant {
+  enchant = selectVersion ../development/libraries/enchant "1.3.0" {
 	  inherit fetchurl stdenv aspell pkgconfig;
 	  inherit (gnome) glib;
   };
@@ -1681,6 +2181,16 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  facile = import ../development/libraries/facile {
+    inherit fetchurl stdenv;
+    # Actually, we don't need this version but we need native-code compilation
+    ocaml = builtins.getAttr "3.10.0" ocaml_alts;
+  };
+
+  fcgi = import ../development/libraries/fcgi {
+      inherit fetchurl stdenv;
+  };
+
   ffmpeg = import ../development/libraries/ffmpeg {
     inherit fetchurl stdenv;
   };
@@ -1693,14 +2203,15 @@ rec {
     inherit fetchurl stdenv builderDefs stringsWithDeps;
   };
 
+  fltk20 = (import ../development/libraries/fltk) {
+    inherit mkDerivationByConfiguration x11 lib;
+    inherit fetchurl stdenv mesa mesaHeaders libpng libjpeg zlib ;
+    flags = [ "useNixLibs" "threads" "shared" "gl" ];
+  };
 
-  # commented out because it's using the new configuration style proposal which is unstable
-  # needs some testing ..
-  #fltk20 = (import ../development/libraries/fltk) {
-    #inherit fetchurl stdenv lib mesa mesaHeaders libpng libjpeg zlib ;
-    #inherit (xlibs) libX11 libXext;
-    #flags = [ "useNixLibs" "threads" "shared" ];
-  #};
+  cfitsio = import ../development/libraries/cfitsio {
+    inherit fetchurl stdenv;
+  };
 
   fontconfig = import ../development/libraries/fontconfig {
     inherit fetchurl stdenv freetype expat;
@@ -1722,12 +2233,27 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  gettext = getVersion "gettext" gettext_alts;
+  fam = gamin;
+
+  gamin = import ../development/libraries/gamin {
+	  inherit fetchurl stdenv python pkgconfig;
+	  inherit (gtkLibs) glib;
+  };
+
+  geos = import ../development/libraries/geos {
+    inherit fetchurl fetchsvn stdenv mkDerivationByConfiguration autoconf automake libtool swig which lib;
+    use_svn = stdenv.system == "x86_64-linux";
+    python = python;
+    # optional features:  
+    # python / ruby support
+  };
 
-  gettext_alts = import ../development/libraries/gettext {
+  gettextFun = lib.sumArgs (selectVersion ../development/libraries/gettext "0.16.x") {
     inherit fetchurl stdenv;
   };
 
+  gettext = gettextFun null;
+
   gd = import ../development/libraries/gd {
     inherit fetchurl stdenv zlib libpng freetype libjpeg fontconfig;
   };
@@ -1740,21 +2266,17 @@ rec {
     };
   };
 
-  glibc = useFromStdenv (stdenv ? glibc) stdenv.glibc
-    (import ../development/libraries/glibc {
+  glew = import ../development/libraries/glew {
+    inherit fetchurl stdenv mesa x11 libtool;
+    inherit (xlibs) libXmu libXi;
+  };
+
+  glibc = useFromStdenv "glibc"
+    (import ../development/libraries/glibc-2.7 {
       inherit fetchurl stdenv kernelHeaders;
       #installLocales = false;
     });
 
-  glibcNPTL = import ../development/libraries/glibc-nptl {
-    inherit fetchurl stdenv kernelHeaders;
-  };
-
-  glibmm = import ../development/libraries/gtk-libs-2.6/glibmm {
-    inherit fetchurl stdenv pkgconfig libsigcxx;
-    inherit (gtkLibs26) glib;
-  };
-
   gmime = import ../development/libraries/gmime {
     inherit fetchurl stdenv pkgconfig zlib;
     inherit (gtkLibs) glib;
@@ -1779,50 +2301,28 @@ rec {
   };
 
   gpgme = import ../development/libraries/gpgme {
-    inherit fetchurl stdenv libgpgerror gnupg;
+    inherit fetchurl stdenv libgpgerror pkgconfig pth gnupg gnupg2;
+	inherit (gtkLibs) glib;
+  };
+
+  # gnu scientific library
+  gsl = import ../development/libraries/gsl {
+    inherit fetchurl stdenv;
   };
 
   gtkLibs = recurseIntoAttrs gtkLibs210;
 
-  gtkLibs1x = import ../development/libraries/gtk-libs-1.x {
+  gtkLibs1x = import ../development/libraries/gtk-libs/1.x {
     inherit fetchurl stdenv x11 libtiff libjpeg libpng;
   };
 
-  gtkLibs210 = import ../development/libraries/gtk-libs-2.10 {
+  gtkLibs210 = import ../development/libraries/gtk-libs/2.10 {
     inherit fetchurl stdenv pkgconfig gettext perl x11
-            libtiff libjpeg libpng cairo;
+            libtiff libjpeg libpng cairo libsigcxx cairomm;
     inherit (xlibs) libXinerama libXrandr;
     xineramaSupport = true;
   };
 
-  gtkLibs22 = import ../development/libraries/gtk-libs-2.2 {
-    inherit fetchurl stdenv pkgconfig gettext perl x11
-            libtiff libjpeg libpng;
-  };
-
-  gtkLibs24 = import ../development/libraries/gtk-libs-2.4 {
-    inherit fetchurl stdenv pkgconfig gettext perl x11
-            libtiff libjpeg libpng;
-  };
-
-  gtkLibs26 = import ../development/libraries/gtk-libs-2.6 {
-    inherit fetchurl stdenv pkgconfig gettext perl x11
-            libtiff libjpeg libpng;
-  };
-
-  gtkLibs28 = import ../development/libraries/gtk-libs-2.8 {
-    inherit fetchurl stdenv pkgconfig gettext perl x11
-            libtiff libjpeg libpng cairo;
-    inherit (xlibs) libXinerama;
-    xineramaSupport = true;
-  };
-
-  gtkmm = import ../development/libraries/gtk-libs-2.6/gtkmm {
-    inherit fetchurl stdenv pkgconfig libsigcxx;
-    inherit (gtkLibs26) gtk atk;
-    inherit glibmm;
-  };
-
   gtkmozembedsharp = import ../development/libraries/gtkmozembed-sharp {
     inherit fetchurl stdenv mono pkgconfig monoDLLFixer;
     inherit (gnome) gtk;
@@ -1855,6 +2355,13 @@ rec {
     inherit aspell;
   };
 
+  # TODO : Add MIT Kerberos and let admin choose.
+  kerberos = heimdal;
+
+  heimdal = import ../development/libraries/kerberos/heimdal.nix {
+	  inherit fetchurl stdenv readline db4 openssl openldap cyrus_sasl;
+  };
+
   hsqldb = import ../development/libraries/java/hsqldb {
     inherit stdenv fetchurl unzip;
   };
@@ -1867,6 +2374,10 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  ilbc = import ../development/libraries/ilbc {
+    inherit stdenv msilbc;
+  };
+
   ilmbase = import ../development/libraries/ilmbase {
 	  inherit fetchurl stdenv;
   };
@@ -1880,12 +2391,25 @@ rec {
     inherit fetchurl stdenv x11 libjpeg libtiff libungif libpng bzip2;
   };
 
-  intltoolFun = lib.sumArgs (import ../development/tools/misc/intltool) {
-  	inherit fetchurl stdenv lib builderDefs stringsWithDeps
-		perl perlXMLParser;
+  indilib = import ../development/libraries/indilib {
+	  inherit fetchurl stdenv cfitsio libusb zlib;
+  };
+
+  iniparser = import ../development/libraries/iniparser {
+    inherit fetchurl stdenv;
+  };
+
+  intltoolFun = lib.sumArgs (selectVersion ../development/tools/misc/intltool "0.36.2") {
+    inherit fetchurl stdenv lib builderDefs stringsWithDeps
+      perl perlXMLParser;
   };
 
-  intltool = intltoolFun {version = "0.36.2";} null;
+  intltool = intltoolFun null;
+
+  jasper = import ../development/libraries/jasper {
+	  inherit fetchurl stdenv unzip libjpeg freeglut mesa;
+	  inherit (xlibs) xproto libX11 libICE libXmu libXi libXext libXt;
+  };
 
   lablgtk = import ../development/libraries/lablgtk {
     inherit fetchurl stdenv ocaml pkgconfig;
@@ -1901,6 +2425,26 @@ rec {
     inherit (xlibs) libXp libXau;
   };
 
+  libaal = import ../development/libraries/libaal {
+    inherit fetchurl stdenv;
+  };
+
+  libao = import ../development/libraries/libao {
+    inherit stdenv fetchurl pkgconfig;
+  };
+
+  libarchive = selectVersion ../development/libraries/libarchive "2.4.12" {
+    inherit fetchurl stdenv zlib bzip2 e2fsprogs sharutils;
+  };
+
+  libassuan = import ../development/libraries/libassuan {
+    inherit fetchurl stdenv pth;
+  };
+
+  libavc1394 = import ../development/libraries/libavc1394 {
+    inherit fetchurl stdenv pkgconfig libraw1394;
+  };
+
   libcaca = import ../development/libraries/libcaca {
     inherit fetchurl stdenv ncurses;
   };
@@ -1918,6 +2462,25 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  libdbiFun = lib.sumArgs (selectVersion ../development/libraries/libdbi "0.8.2") {
+    inherit stdenv fetchurl builderDefs;
+  };
+
+  libdbi = libdbiFun null;
+
+  libdbiDriversFun = lib.sumArgs (selectVersion ../development/libraries/libdbi-drivers "0.8.2-1") {
+    inherit stdenv fetchurl builderDefs libdbi;
+  };
+
+  libdbiDrivers = libdbiDriversFun {
+    mysql = mysql5;
+    inherit sqlite;
+  } null;
+
+  libdv = import ../development/libraries/libdv {
+    inherit fetchurl stdenv lib mkDerivationByConfiguration;
+  };
+
   libdrm = import ../development/libraries/libdrm {
     inherit fetchurl stdenv;
   };
@@ -1939,9 +2502,16 @@ rec {
   };
 
   libexif = import ../development/libraries/libexif {
-    inherit fetchurl stdenv;
+    inherit fetchurl stdenv gettext;
+  };
+
+  libextractorFun = lib.sumArgs (selectVersion ../development/libraries/libextractor "0.5.18")
+  {
+    inherit fetchurl stdenv builderDefs zlib;
   };
 
+  libextractor = libextractorFun null;
+
   libgcrypt = import ../development/libraries/libgcrypt {
     inherit fetchurl stdenv libgpgerror;
   };
@@ -1951,23 +2521,36 @@ rec {
   };
 
   libgphoto2 = import ../development/libraries/libgphoto2 {
-    inherit fetchurl stdenv pkgconfig libusb;
+    inherit fetchurl stdenv pkgconfig libusb libtool libexif libjpeg gettext;
   };
 
   # commented out because it's using the new configuration style proposal which is unstable
-  #libsamplerate = (import ../development/libraries/libsamplerate) {
-  #  inherit fetchurl stdenv mkDerivationByConfigruation pkgconfig lib;
-  #};
+  libsamplerate = if builtins ? listToAttrs then (import ../development/libraries/libsamplerate) {
+    inherit fetchurl stdenv mkDerivationByConfiguration pkgconfig lib;
+  } else null;
 
   libgsf = import ../development/libraries/libgsf {
-    inherit fetchurl stdenv perl perlXMLParser pkgconfig libxml2 gettext;
-    inherit (gnome) glib;
+    inherit fetchurl stdenv perl perlXMLParser pkgconfig libxml2 gettext bzip2
+	python;
+    inherit (gnome) glib gnomevfs libbonobo;
+  };
+
+  libid3tag = import ../development/libraries/libid3tag {
+    inherit fetchurl stdenv zlib;
   };
 
   libidn = import ../development/libraries/libidn {
 	  inherit fetchurl stdenv;
   };
 
+  libiec61883 = import ../development/libraries/libiec61883 {
+    inherit fetchurl stdenv pkgconfig libraw1394;
+  };
+
+  libjingle = selectVersion ../development/libraries/libjingle "0.3.11" {
+    inherit fetchurl stdenv mediastreamer;
+  };
+
   libjpeg = import ../development/libraries/libjpeg {
     inherit fetchurl stdenv libtool;
   };
@@ -1977,6 +2560,10 @@ rec {
     static = true;
   }));
 
+  libksba = import ../development/libraries/libksba {
+	  inherit fetchurl stdenv libgpgerror;
+  };
+
   libmad = import ../development/libraries/libmad {
     inherit fetchurl stdenv;
   };
@@ -1989,10 +2576,18 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  libnova = import ../development/libraries/libnova {
+	  inherit fetchurl stdenv;
+  };
+
   libogg = import ../development/libraries/libogg {
     inherit fetchurl stdenv;
   };
 
+  liboop = import ../development/libraries/liboop {
+    inherit fetchurl stdenv;
+  };
+
   libotr = import ../development/libraries/libotr {
     inherit fetchurl stdenv libgcrypt;
   };
@@ -2005,11 +2600,17 @@ rec {
     inherit fetchurl stdenv zlib;
   };
 
+  /*libscdFun = lib.sumArgs (selectVersion ../development/libraries/libscd "0.4.2") {
+    inherit stdenv fetchurl builderDefs libextractor perl pkgconfig;
+  };
+
+  libscd = libscdFun null;*/
+
   libsigcxx = import ../development/libraries/libsigcxx {
     inherit fetchurl stdenv pkgconfig;
   };
 
-  libsigsegv = import ../development/libraries/libsigsegv {
+  libsigsegv = selectVersion ../development/libraries/libsigsegv "2.5" {
     inherit fetchurl stdenv;
   };
 
@@ -2025,7 +2626,11 @@ rec {
     inherit fetchurl stdenv zlib libjpeg;
   };
 
-  libungif = import ../development/libraries/libungif {
+  giflib = import ../development/libraries/giflib {
+    inherit fetchurl stdenv;
+  };
+
+  libungif = import ../development/libraries/giflib/libungif.nix {
     inherit fetchurl stdenv;
   };
 
@@ -2033,6 +2638,10 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  libunwind = import ../development/libraries/libunwind {
+    inherit fetchurl stdenv;
+  };
+
   libvorbis = import ../development/libraries/libvorbis {
     inherit fetchurl stdenv libogg;
   };
@@ -2044,7 +2653,7 @@ rec {
   };
 
   libwpd = import ../development/libraries/libwpd {
-    inherit fetchurl stdenv pkgconfig libgsf libxml2;
+    inherit fetchurl stdenv pkgconfig libgsf libxml2 bzip2;
     inherit (gnome) glib;
   };
 
@@ -2052,6 +2661,12 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  libxklavier = selectVersion ../development/libraries/libxklavier "3.4" {
+    inherit fetchurl stdenv xkeyboard_config pkgconfig libxml2;
+    inherit (xorg) libX11 libICE libxkbfile;
+    inherit (gtkLibs) glib;
+  };
+
   libxml2 = import ../development/libraries/libxml2 {
     inherit fetchurl stdenv zlib python;
     pythonSupport = false;
@@ -2080,13 +2695,28 @@ rec {
   };
 
   log4cxx = import ../development/libraries/log4cxx {
-	  inherit fetchurl stdenv automake autoconf libtool cppunit libxml2;
+	  inherit fetchurl stdenv automake autoconf libtool cppunit libxml2 boost;
+  };
+
+  loudmouth = import ../development/libraries/loudmouth {
+	  inherit fetchurl stdenv libidn gnutls pkgconfig;
+	  inherit (gtkLibs) glib;
   };
 
   lzo = import ../development/libraries/lzo {
 	  inherit fetchurl stdenv;
   };
 
+#failed to build
+  mediastreamerFun = lib.sumArgs (selectVersion
+      ../development/libraries/mediastreamer "2.2.0-cvs20080207") {
+    inherit fetchurl stdenv automake libtool autoconf alsaLib pkgconfig speex
+      ortp;
+    ffmpeg = ffmpeg_svn;
+  };
+
+  mediastreamer = mediastreamerFun null;
+
   mesaSupported =
     system == "i686-linux" ||
     system == "x86_64-linux";
@@ -2104,14 +2734,20 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  msilbc = selectVersion ../development/libraries/msilbc "2.0.0" {
+    inherit fetchurl stdenv ilbc mediastreamer pkgconfig;
+  };
+
   mysqlConnectorODBC = import ../development/libraries/mysql-connector-odbc {
     inherit fetchurl stdenv mysql libtool zlib unixODBC;
   };
 
-  ncurses = import ../development/libraries/ncurses {
+  ncursesFun = lib.sumArgs (import ../development/libraries/ncurses) {
     inherit fetchurl stdenv;
     unicode = (system != "i686-cygwin");
   };
+  
+  ncurses = ncursesFun null;
 
   ncursesDiet = import ../development/libraries/ncurses-diet {
     inherit fetchurl;
@@ -2132,12 +2768,31 @@ rec {
     inherit fetchurl stdenv alsaLib autoconf automake libtool;
   };
 
+  # added because I hope that it has been easier to compile on x86 (for blender)
+  openalSoft = import ../development/libraries/openalSoft {
+    inherit fetchurl stdenv alsaLib libtool cmake;
+  };
+
   openbabel = import ../development/libraries/openbabel {
 	  inherit fetchurl stdenv zlib libxml2;
   };
 
-  openexr = import ../development/libraries/openexr {
-	  inherit fetchurl stdenv ilmbase zlib pkgconfig;
+  # this ctl version is needed by openexr_viewers
+  openexr_ctl = import ../development/libraries/openexr_ctl {
+    inherit fetchurl stdenv ilmbase ctl;
+    openexr = openexr_1_6_1;
+  };
+
+  openexr_1_6_1 = import ../development/libraries/openexr {
+	  inherit fetchurl stdenv ilmbase zlib pkgconfig lib;
+          version = "1.6.1";
+          # optional features:
+          inherit ctl;
+  };
+  # This older version is needed by blender (it complains about missing half.h )
+  openexr_1_4_0 = import ../development/libraries/openexr {
+	  inherit fetchurl stdenv ilmbase zlib pkgconfig lib;
+          version = "1.4.0";
   };
 
   openldap = import ../development/libraries/openldap {
@@ -2145,7 +2800,11 @@ rec {
   };
 
   openssl = import ../development/libraries/openssl {
-    inherit fetchurl stdenv perl gmp;
+    inherit fetchurl stdenv perl;
+  };
+
+  ortp = selectVersion ../development/libraries/ortp "0.13.1" {
+    inherit fetchurl stdenv;
   };
 
   pangoxsl = import ../development/libraries/pangoxsl {
@@ -2155,12 +2814,13 @@ rec {
 
   pcre = import ../development/libraries/pcre {
     inherit fetchurl stdenv;
-    unicodeSupport = getFlag "unicode" "pcre" false;
+    unicodeSupport = getConfig ["pcre" "unicode"] false;
+    cplusplusSupport = !stdenv ? isDietLibC;
   };
 
   poppler = import ../development/libraries/poppler {
-	  inherit fetchurl stdenv qt4 cairo freetype fontconfig zlib libjpeg;
-	  inherit (gtkLibs) glib gtk;
+    inherit fetchurl stdenv qt4 cairo freetype fontconfig zlib libjpeg;
+    inherit (gtkLibs) glib gtk;
   };
 
   popt = import ../development/libraries/popt {
@@ -2171,23 +2831,31 @@ rec {
     inherit fetchurl stdenv gettext libtool autoconf automake;
   };
 
+
+  proj = import ../development/libraries/proj.4 {
+    inherit fetchurl stdenv;
+  };
+
+  pth = import ../development/libraries/pth {
+	  inherit fetchurl stdenv;
+  };
+
   qt3 = import ../development/libraries/qt-3 {
     inherit fetchurl stdenv x11 zlib libjpeg libpng which mysql mesa;
     inherit (xlibs) xextproto libXft libXrender libXrandr randrproto
       libXmu libXinerama xineramaproto libXcursor;
     openglSupport = mesaSupported;
-    mysqlSupport = false;
+    mysqlSupport = getConfig ["qt" "mysql"] false;
   };
 
   qt4 = getVersion "qt4" qt4_alts;
   qt4_alts = import ../development/libraries/qt-4 {
-	inherit fetchurl fetchsvn zlib libjpeg libpng which mysql mesa openssl cups dbus
+    inherit fetchurl stdenv fetchsvn zlib libjpeg libpng which mysql mesa openssl cups dbus
 	  fontconfig freetype pkgconfig libtiff;
     inherit (xlibs) xextproto libXft libXrender libXrandr randrproto
 	  libXmu libXinerama xineramaproto libXcursor libICE libSM libX11 libXext
 	  inputproto fixesproto libXfixes;
     inherit (gnome) glib;
-    stdenv = overrideSetup stdenv ../stdenv/generic/setup-new-2.sh;
     openglSupport = mesaSupported;
     mysqlSupport = true;
   };
@@ -2204,8 +2872,9 @@ rec {
 
 # Also known as librdf, includes raptor and rasqal
   redland = import ../development/libraries/redland {
-    inherit fetchurl stdenv openssl libxml2 pkgconfig perl;
-	bdb = db4;
+    inherit fetchurl stdenv openssl libxml2 pkgconfig perl postgresql sqlite
+      mysql libxslt curl pcre;
+    bdb = db4;
   };
 
   rte = import ../development/libraries/rte {
@@ -2228,6 +2897,10 @@ rec {
     inherit fetchurl stdenv SDL libogg libvorbis;
   };
 
+  SDL_net = import ../development/libraries/SDL_net {
+    inherit fetchurl stdenv SDL;
+  };
+
   SDL_ttf = import ../development/libraries/SDL_ttf {
     inherit fetchurl stdenv SDL freetype;
   };
@@ -2244,25 +2917,40 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  strigi = import ../development/libraries/strigi {
-	  inherit stdenv fetchurl zlib cluceneCore cluceneContrib expat bzip2
-	  pkgconfig cmake dbus libxml2 perl;
-	  qt = qt4;
-  };
-
   t1lib = import ../development/libraries/t1lib {
     inherit fetchurl stdenv x11;
-    inherit (xlibs) libXaw;
+    inherit (xlibs) libXaw libXpm;
   };
 
   taglib = import ../development/libraries/taglib {
     inherit fetchurl stdenv zlib;
   };
 
-  tk = import ../development/libraries/tk {
+  tapioca_qt = import ../development/libraries/tapioca-qt {
+    inherit fetchsvn stdenv cmake telepathy_qt;
+	qt = qt4;
+  };
+
+  telepathy_gabble = import ../development/libraries/telepathy-gabble {
+    inherit fetchurl stdenv pkgconfig libxslt telepathy_glib loudmouth;
+  };
+
+  telepathy_glib = import ../development/libraries/telepathy-glib {
+    inherit fetchurl stdenv dbus_glib pkgconfig libxslt python;
+	inherit (gtkLibs) glib;
+  };
+
+  telepathy_qt = import ../development/libraries/telepathy-qt {
+    inherit fetchsvn stdenv cmake;
+	qt = qt4;
+  };
+
+  tkFun = lib.sumArgs (selectVersion ../development/libraries/tk "8.4.16") {
     inherit fetchurl stdenv tcl x11;
   };
 
+  tk = tkFun null;
+
   unixODBC = import ../development/libraries/unixODBC {
     inherit fetchurl stdenv;
   };
@@ -2292,7 +2980,8 @@ rec {
   };
 
   xineLib = import ../development/libraries/xine-lib {
-    inherit fetchurl stdenv zlib x11 libdvdcss alsaLib;
+	inherit fetchurl stdenv zlib x11 libdvdcss alsaLib pkgconfig mesa aalib SDL
+	  libvorbis libtheora speex;
     inherit (xlibs) libXv libXinerama;
   };
 
@@ -2409,20 +3098,70 @@ rec {
 
   ### DEVELOPMENT / LIBRARIES / HASKELL
 
+  binary = import ../development/libraries/haskell/binary {
+    inherit cabal; 
+  };
+
+  # cabal is a utility function to build cabal-based
+  # Haskell packages
+  cabal68 = import ../development/libraries/haskell/cabal/cabal.nix {
+    inherit stdenv fetchurl;
+    ghc = ghc68;
+  };
+  cabal = cabal68;
+
+  Crypto = import ../development/libraries/haskell/Crypto {
+    inherit cabal;
+  };
+
+  gtk2hs = import ../development/libraries/haskell/gtk2hs {
+    inherit pkgconfig stdenv fetchurl cairo ghc;
+    inherit (gnome) gtk glib GConf libglade libgtkhtml gtkhtml;
+  };
+
+  HDBC = import ../development/libraries/haskell/HDBC/HDBC-1.1.4.nix {
+    inherit cabal;
+  };
+
+  HDBCPostgresql = import ../development/libraries/haskell/HDBC/HDBC-postgresql-1.1.4.0.nix {
+    inherit cabal HDBC postgresql;
+  };
+
+  HDBCSqlite = import ../development/libraries/haskell/HDBC/HDBC-sqlite3-1.1.4.0.nix {
+    inherit cabal HDBC sqlite;
+  };
 
-  uulib64 = import ../development/libraries/haskell/uulib { # !!! remove?
-    inherit stdenv fetchurl ghc;
+  pcreLight = import ../development/libraries/haskell/pcre-light {
+    inherit cabal pcre;
   };
 
-  uulib66 = import ../development/libraries/haskell/uulib-ghc-6.6 { # !!! ugh
-    inherit stdenv fetchurl autoconf;
-    ghc = ghc66;
+  uulib = import ../development/libraries/haskell/uulib {
+    inherit cabal;
   };
 
   wxHaskell = import ../development/libraries/haskell/wxHaskell {
-    inherit stdenv fetchurl unzip ghc wxGTK;
+    inherit stdenv fetchurl unzip wxGTK;
+    ghc = ghc661;
+  };
+
+  # wxHaskell68 = lowPrio (appendToName "ghc68" (import ../development/libraries/haskell/wxHaskell {
+  #   inherit stdenv fetchurl unzip wxGTK;
+  #   ghc = ghc68;
+  # }));
+
+  X11 = import ../development/libraries/haskell/X11 {
+    inherit cabal;
+    inherit (xlibs) libX11 libXinerama libXext;
+    xineramaSupport = true;
+  };
+
+  vty = import ../development/libraries/haskell/vty {
+    inherit cabal;
   };
 
+  zlibHaskell = import ../development/libraries/haskell/zlib {
+    inherit cabal zlib;
+  };
 
   ### DEVELOPMENT / PERL MODULES
 
@@ -2447,6 +3186,14 @@ rec {
     inherit fetchurl perl;
   };
 
+  perlCryptPasswordMD5 = import ../development/perl-modules/generic perl {
+    name = "Crypt-PasswdMD5-1.3";
+    src = fetchurl {
+      url = http://search.cpan.org/CPAN/authors/id/L/LU/LUISMUNOZ/Crypt-PasswdMD5-1.3.tar.gz;
+      sha256 = "13j0v6ihgx80q8jhyas4k48b64gnzf202qajyn097vj8v48khk54";
+    };
+  };
+
   perlDateManip = import ../development/perl-modules/generic perl {
     name = "DateManip-5.42a";
     src = fetchurl {
@@ -2455,6 +3202,10 @@ rec {
     };
   };
 
+  perlDBFile = import ../development/perl-modules/DB_File {
+    inherit fetchurl perl db4;
+  };
+
   perlDigestSHA1 = import ../development/perl-modules/generic perl {
     name = "Digest-SHA1-2.11";
     src = fetchurl {
@@ -2549,6 +3300,14 @@ rec {
     };
   };
 
+  perlStringMkPasswd = import ../development/perl-modules/generic perl {
+    name = "String-MkPasswd-0.02";
+    src = fetchurl {
+      url = http://search.cpan.org/CPAN/authors/id/C/CG/CGRAU/String-MkPasswd-0.02.tar.gz;
+      sha256 = "0si4xfgf8c2pfag1cqbr9jbyvg3hak6wkmny56kn2qwa4ljp9bk6";
+    };
+  };
+
   perlTermReadKey = import ../development/perl-modules/generic perl {
     name = "TermReadKey-2.30";
     src = fetchurl {
@@ -2723,10 +3482,26 @@ rec {
     inherit fetchurl stdenv ;
   };
 
+  ejabberd = import ../servers/xmpp/ejabberd {
+    inherit fetchurl stdenv expat erlang zlib openssl;
+  };
+
+  fingerd_bsd = import ../servers/fingerd/bsd-fingerd {
+	  inherit fetchurl stdenv;
+  };
+
   ircdHybrid = import ../servers/irc/ircd-hybrid {
 		inherit fetchurl stdenv openssl zlib;
 	};
 
+  jboss = import ../servers/http/jboss {
+    inherit fetchurl stdenv jdk5 jdk;
+  };
+
+  jboss_mysql_jdbc = import ../servers/http/jboss/jdbc/mysql {
+    inherit stdenv jboss mysql_jdbc;
+  };
+
   jetty = import ../servers/http/jetty {
     inherit fetchurl stdenv unzip;
   };
@@ -2735,13 +3510,17 @@ rec {
     inherit fetchurl stdenv apacheHttpd python;
   };
 
+  tomcat_connectors = import ../servers/http/apache-modules/tomcat-connectors {
+    inherit fetchurl stdenv apacheHttpd jdk;
+  };
+
   mysql = import ../servers/sql/mysql {
     inherit fetchurl stdenv ncurses zlib perl;
     ps = procps; /* !!! Linux only */
   };
 
   mysql5 = import ../servers/sql/mysql5 {
-    inherit fetchurl stdenv ncurses zlib perl;
+    inherit fetchurl stdenv ncurses zlib perl openssl;
     ps = procps; /* !!! Linux only */
   };
 
@@ -2750,14 +3529,15 @@ rec {
   };
 
   nagios = import ../servers/monitoring/nagios {
-    inherit fetchurl stdenv perl;
+    inherit fetchurl stdenv perl gd libpng zlib;
+    gdSupport = true;
   };
 
   nagiosPluginsOfficial = import ../servers/monitoring/nagios/plugins/official {
     inherit fetchurl stdenv openssh;
   };
 
-  postgresql = import ../servers/sql/postgresql {
+  postgresql = selectVersion ../servers/sql/postgresql "8.3.0" {
     inherit fetchurl stdenv readline ncurses zlib;
   };
 
@@ -2766,22 +3546,34 @@ rec {
   };
 
   samba = import ../servers/samba {
-    inherit stdenv fetchurl readline openldap pam;
+    inherit stdenv fetchurl readline openldap pam kerberos popt iniparser
+	libunwind acl fam;
+  };
+
+  squid = import ../servers/squid {
+    inherit fetchurl stdenv mkDerivationByConfiguration perl lib;
   };
 
   tomcat5 = import ../servers/http/tomcat {
     inherit fetchurl stdenv jdk;
   };
 
+  tomcat6 = import ../servers/http/tomcat/6.0.nix {
+    inherit fetchurl stdenv jdk;
+  };
+
+  axis2 = import ../servers/http/tomcat/axis2 {
+    inherit fetchurl stdenv jdk apacheAnt unzip;  
+  };
+
   vsftpd = import ../servers/ftp/vsftpd {
-    inherit fetchurl openssl ;
-    stdenv = overrideGCC stdenv gcc295 ;
+    inherit fetchurl openssl stdenv libcap pam;
   };
 
   xorg = recurseIntoAttrs (import ../servers/x11/xorg {
     inherit fetchurl stdenv pkgconfig freetype fontconfig
       libxslt expat libdrm libpng zlib perl mesa mesaHeaders
-      xkeyboard_config gettext;
+      xkeyboard_config dbus hal;
   });
 
 
@@ -2798,14 +3590,32 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  #nfsUtils = import ../os-specific/linux/nfs-utils {
-  #  inherit fetchurl stdenv;
-  #};
+  /*
+  nfsUtils = import ../os-specific/linux/nfs-utils {
+   inherit fetchurl stdenv kernelHeaders tcp_wrapper;
+  };
+  */
 
   alsaLib = import ../os-specific/linux/alsa/library {
     inherit fetchurl stdenv;
   };
 
+  atherosFun = lib.sumArgs (selectVersion ../os-specific/linux/atheros "r3122") {
+    inherit fetchurl stdenv builderDefs;
+  };
+
+  atherosFunCurrent = kernel: atherosFun {
+    inherit kernel;
+  } null;
+
+  aufs = import ../os-specific/linux/aufs {
+    inherit fetchurl stdenv kernel;
+  };
+
+  bridge_utils = import ../os-specific/linux/bridge_utils {
+    inherit fetchurl stdenv autoconf automake;
+  };
+
   alsaUtils = import ../os-specific/linux/alsa/utils {
     inherit fetchurl stdenv alsaLib ncurses gettext;
   };
@@ -2823,10 +3633,16 @@ rec {
     static = true;
   }));
 
+  dmidecodeFun = lib.sumArgs (selectVersion ../os-specific/linux/dmidecode "2.9") {
+    inherit fetchurl stdenv builderDefs;
+  };
+
+  dmidecode = dmidecodeFun null;
+
   dietlibc = import ../os-specific/linux/dietlibc {
     inherit fetchurl glibc;
     # Dietlibc 0.30 doesn't compile on PPC with GCC 4.1, bus GCC 3.4 works.
-   stdenv = if stdenv.system == "powerpc-linux" then overrideGCC stdenv gcc34 else stdenv;
+    stdenv = if stdenv.system == "powerpc-linux" then overrideGCC stdenv gcc34 else stdenv;
   };
 
   e2fsprogs = import ../os-specific/linux/e2fsprogs {
@@ -2852,6 +3668,10 @@ rec {
   };
 
   fuse = import ../os-specific/linux/fuse {
+    inherit fetchurl stdenv utillinux;
+  };
+
+  fxload = import ../os-specific/linux/fxload {
     inherit fetchurl stdenv;
   };
 
@@ -2871,7 +3691,7 @@ rec {
   };
  
   htop = import ../os-specific/linux/htop {
-	  inherit fetchurl stdenv ncurses;
+    inherit fetchurl stdenv ncurses;
   };
 
   hwdata = import ../os-specific/linux/hwdata {
@@ -2905,19 +3725,29 @@ rec {
     inherit fetchurl stdenv;
   };
 
-  kbd = import ../os-specific/linux/kbd {
-    inherit fetchurl stdenv bison flex;
+  iwlwifi = import ../os-specific/linux/iwlwifi {
+    inherit fetchurl stdenv kernel;
+  };
+
+  iwlwifi3945ucode = import ../os-specific/linux/firmware/iwlwifi-3945-ucode {
+    inherit fetchurl stdenv;
   };
 
-  kernelHeaders = import ../os-specific/linux/kernel-headers {
+  iwlwifi4965ucode = import ../os-specific/linux/firmware/iwlwifi-4965-ucode {
     inherit fetchurl stdenv;
   };
 
+  kbd = import ../os-specific/linux/kbd {
+    inherit fetchurl stdenv bison flex;
+  };
+
+  kernelHeaders = kernelHeaders_2_6_23;
+
   kernelHeaders_2_6_21 = import ../os-specific/linux/kernel-headers/2.6.21.3.nix {
     inherit fetchurl stdenv;
   };
 
-  kernelHeaders_2_6_23 = import ../os-specific/linux/kernel-headers/2.6.23.1.nix {
+  kernelHeaders_2_6_23 = import ../os-specific/linux/kernel-headers/2.6.23.8.nix {
     inherit fetchurl stdenv;
   };
 
@@ -2941,7 +3771,7 @@ rec {
     modules = [];
   };
 
-  kernel = kernel_2_6_21;
+  kernel = kernel_2_6_23;
 
   systemKernel = (if (getConfig ["kernel" "version"] "2.6.21") == "2.6.22" then
 	kernel_2_6_22 else if (getConfig ["kernel" "version"] "2.6.21") == "2.6.23" then
@@ -3016,17 +3846,16 @@ rec {
   kernel_2_6_22 = import ../os-specific/linux/kernel/linux-2.6.22.nix {
     inherit fetchurl stdenv perl mktemp module_init_tools;
     kernelPatches = [
-      /*{ name = "ext3cow";
-        patch = ../os-specific/linux/kernel/linux-2.6.20.3-ext3cow.patch;
+      /*
+      { name = "ext3cow";
+        patch = ../os-specific/linux/kernel/linux-2.6.21.7-ext3cow_wouter.patch;
         extraConfig =
         "CONFIG_EXT3COW_FS=m\n" +
         "CONFIG_EXT3COW_FS_XATTR=y\n" +
         "CONFIG_EXT3COW_FS_POSIX_ACL=y\n" +
         "CONFIG_EXT3COW_FS_SECURITY=y\n";
-      }*/
-      { name = "paravirt-nvidia";
-        patch = ../os-specific/linux/kernel/2.6.22-paravirt-nvidia.patch;
       }
+      */
       /*
       { name = "skas-2.6.20-v9-pre9";
         patch = fetchurl {
@@ -3054,19 +3883,78 @@ rec {
       [(getConfig ["kernel" "addConfig"] "")];
   };
 
-  kernel_2_6_23 = import ../os-specific/linux/kernel/linux-2.6.23.nix {
+  kernel_2_6_21_ck = import ../os-specific/linux/kernel/linux-2.6.21_ck.nix {
     inherit fetchurl stdenv perl mktemp module_init_tools;
     kernelPatches = [
+      { name = "ext3cow";
+        patch = ../os-specific/linux/kernel/linux-2.6.21.7-ext3cow_wouter.patch;
+        extraConfig =
+        "CONFIG_EXT3COW_FS=m\n" +
+        "CONFIG_EXT3COW_FS_XATTR=y\n" +
+        "CONFIG_EXT3COW_FS_POSIX_ACL=y\n" +
+        "CONFIG_EXT3COW_FS_SECURITY=y\n";
+      }
+      { name = "Con Kolivas Patch";
+        patch = ../os-specific/linux/kernel/patch-2.6.21-ck1;
+      }
       { name = "paravirt-nvidia";
-        patch = ../os-specific/linux/kernel/2.6.22-paravirt-nvidia.patch;
+        patch = ../os-specific/linux/kernel/2.6.20-paravirt-nvidia.patch;
+      }
+      { name = "skas-2.6.20-v9-pre9";
+        patch = fetchurl {
+          url = http://www.user-mode-linux.org/~blaisorblade/patches/skas3-2.6/skas-2.6.20-v9-pre9/skas-2.6.20-v9-pre9.patch.bz2;
+          md5 = "02e619e5b3aaf0f9768f03ac42753e74";
+        };
+        extraConfig =
+          "CONFIG_PROC_MM=y\n" +
+          "# CONFIG_PROC_MM_DUMPABLE is not set\n";
       }
       { name = "fbsplash-0.9.2-r5-2.6.21";
         patch = fetchurl {
+          url = http://dev.gentoo.org/~dsd/genpatches/trunk/2.6.21/4200_fbsplash-0.9.2-r5.patch;
+          sha256 = "00s8074fzsly2zpir885zqkvq267qyzg6vhsn7n1z2v1z78avxd8";
+        };
+        extraConfig = "CONFIG_FB_SPLASH=y";
+      }
+    ];
+  };
+
+  kernel_2_6_23 = import ../os-specific/linux/kernel/linux-2.6.23.nix {
+    inherit fetchurl stdenv perl mktemp module_init_tools;
+    kernelPatches = [
+      /*
+      { # resume with resume=swap:/dev/xx
+        name = "tux on ice"; # (swsusp2)
+        patch = fetchurl {
+          url = "http://www.tuxonice.net/downloads/all/tuxonice-3.0-rc5-for-2.6.23.14.patch.bz2";
+          sha256 = "187190rxbn9x1c6bwv59mwy1zhff8nn5ad58cfiz23wa5wrk4mif";
+        };
+        extraConfig = "
+          CONFIG_SUSPEND2=y
+          CONFIG_SUSPEND2_FILE=y
+          CONFIG_SUSPEND2_SWAP=y
+          CONFIG_CRYPTO_LZF=y
+        ";
+      }
+      */
+      { name = "fbsplash-0.9.2-r5-2.6.21";
+        patch = fetchurl {
           url = http://dev.gentoo.org/~dsd/genpatches/trunk/2.6.22/4200_fbsplash-0.9.2-r5.patch;
           sha256 = "0822wwlf2dqsap5qslnnp0yl1nbvvvb76l73w2dd8zsyn0bqg3px";
         };
         extraConfig = "CONFIG_FB_SPLASH=y";
       }
+      /* !!! Not needed anymore for the NixOS LiveCD - we have AUFS. */
+      { name = "unionfs-2.2.2";
+        patch = fetchurl {
+          url = http://download.filesystems.org/unionfs/unionfs-2.x/unionfs-2.2.2_for_2.6.23.13.diff.gz;
+          sha256 = "104hahp6fjpxwprcl2njw5mimyh442ma3cp5r1ww0mzq3vwrcdyz";
+        };
+        extraConfig = ''
+          CONFIG_UNION_FS=m
+          CONFIG_UNION_FS_XATTR=y
+        '';
+      }
     ];
     extraConfig =
       lib.optional (getConfig ["kernel" "timer_stats"] false) "CONFIG_TIMER_STATS=y" ++
@@ -3074,11 +3962,29 @@ rec {
       [(getConfig ["kernel" "addConfig"] "")];
   };
 
+  kqemuFun = lib.sumArgs (selectVersion ../os-specific/linux/kqemu "1.3.0pre11") {
+    inherit fetchurl stdenv builderDefs;
+  };
+
+  # No finished expression is provided - pick your own kernel
+  kqemuFunCurrent = theKernel:  (kqemuFun { 
+    kernel = theKernel;
+  } null);
 
   libselinux = import ../os-specific/linux/libselinux {
     inherit fetchurl stdenv libsepol;
   };
 
+  libraw1394 = import ../development/libraries/libraw1394 {
+    inherit fetchurl stdenv;
+  };
+
+ 
+  libsexy = import ../development/libraries/libsexy {
+    inherit stdenv fetchurl pkgconfig libxml2;
+    inherit (gtkLibs) glib gtk pango;
+  };
+
   librsvg = import ../development/libraries/librsvg {
     inherit fetchurl stdenv;
     inherit libxml2 pkgconfig cairo fontconfig freetype;
@@ -3100,7 +4006,7 @@ rec {
 	kernel = systemKernel;
   };
 
-  kvm = kvm49;
+  kvm = kvm57;
 
   kvm12 = import ../os-specific/linux/kvm/12.nix {
     inherit fetchurl zlib e2fsprogs SDL alsaLib;
@@ -3120,6 +4026,12 @@ rec {
     kernelHeaders = kernelHeaders_2_6_23;
   };
 
+  kvm57 = import ../os-specific/linux/kvm/57.nix {
+    inherit fetchurl zlib e2fsprogs SDL alsaLib;
+    stdenv = overrideGCC stdenv gcc34;
+    kernelHeaders = kernelHeaders_2_6_23;
+  };
+
   libcap = import ../os-specific/linux/libcap {
     inherit fetchurl stdenv;
   };
@@ -3128,6 +4040,11 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  libnotify = import ../development/libraries/libnotify {
+    inherit stdenv fetchurl pkgconfig dbus dbus_glib;
+    inherit (gtkLibs) gtk glib;
+  };
+
   libvolume_id = import ../os-specific/linux/libvolume_id {
     inherit fetchurl stdenv;
   };
@@ -3159,19 +4076,29 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  module_aggregation = moduleSources:  
+  import ../os-specific/linux/module-init-tools/aggregator.nix {
+    inherit fetchurl stdenv module_init_tools moduleSources builderDefs;
+  };
+
   modutils = import ../os-specific/linux/modutils {
     inherit fetchurl bison flex;
     stdenv = overrideGCC stdenv gcc34;
   };
 
+  /* compiles but has to be integrated into the kernel somehow
+  ndiswrapper = import ../os-specific/linux/ndiswrapper {
+    inherit fetchurl stdenv;
+    inherit kernel;
+  };
+  */
+
   nettools = import ../os-specific/linux/net-tools {
     inherit fetchurl stdenv;
   };
 
   nvidiaDrivers = import ../os-specific/linux/nvidia {
-    inherit stdenv fetchurl kernel coreutils;
-    xorg_server = xorg.xorgserver;
-    inherit (xlibs) libX11 libXext;
+    inherit stdenv fetchurl kernel xlibs gtkLibs;
   };
 
   gw6c = import ../os-specific/linux/gw6c {
@@ -3229,11 +4156,21 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  reiser4progs = import ../os-specific/linux/reiser4progs {
+    inherit fetchurl stdenv libaal;
+  };
+
   radeontools = import ../os-specific/linux/radeontools {
     inherit pciutils;
     inherit fetchurl stdenv;
   };
 
+  sdparmFun = lib.sumArgs (selectVersion ../os-specific/linux/sdparm "1.02") {
+    inherit fetchurl stdenv builderDefs;
+  };
+
+  sdparm = sdparmFun null;
+ 
   shadowutils = import ../os-specific/linux/shadow {
     inherit fetchurl stdenv;
   };
@@ -3269,6 +4206,13 @@ rec {
     withoutInitTools = true;
   };
 
+  /*
+  # needed for nfs utils
+  tcp_wrapper = import ../os-specific/linux/tcp-wrapper {
+    inherit fetchurl stdenv kernelHeaders gnused;
+  };
+  */
+
   udev = import ../os-specific/linux/udev {
     inherit fetchurl stdenv;
   };
@@ -3287,6 +4231,10 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  upstartJobControl = import ../os-specific/linux/upstart/jobcontrol.nix {
+    inherit stdenv;
+  };
+
   usbutils = import ../os-specific/linux/usbutils {
     inherit fetchurl stdenv libusb;
   };
@@ -3295,15 +4243,27 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  utillinuxCurses = import ../os-specific/linux/util-linux {
+    inherit fetchurl stdenv ncurses;
+  };
+
   utillinuxStatic = lowPrio (appendToName "static" (import ../os-specific/linux/util-linux {
     inherit fetchurl;
     stdenv = makeStaticBinaries stdenv;
   }));
 
+  wesnoth = import ../games/wesnoth {
+    inherit fetchurl stdenv SDL SDL_image SDL_mixer SDL_net gettext zlib boost freetype;
+  };
+
   wirelesstools = import ../os-specific/linux/wireless-tools {
     inherit fetchurl stdenv;
   };
 
+  wis_go7007 = import ../os-specific/linux/wis-go7007 {
+    inherit fetchurl stdenv kernel ncurses fxload;
+  };
+
   wpa_supplicant = import ../os-specific/linux/wpa_supplicant {
     inherit fetchurl stdenv openssl;
   };
@@ -3312,6 +4272,9 @@ rec {
     inherit stdenv xlibs expat libdrm;
   };
 
+  zd1211fw = import ../os-specific/linux/firmware/zd1211 {
+    inherit stdenv fetchurl;
+  };
 
   ### DATA
 
@@ -3324,6 +4287,11 @@ rec {
     inherit fetchurl stdenv cabextract;
   };
 
+  wrapFonts = paths : ((import ../data/fonts/fontWrap) {
+    inherit fetchurl stdenv builderDefs paths;
+    inherit (xorg) mkfontdir mkfontscale;
+  });
+
   docbook5 = import ../data/sgml+xml/schemas/docbook-5.0 {
     inherit fetchurl stdenv;
   };
@@ -3362,9 +4330,9 @@ rec {
      inherit fetchurl stdenv;
   };
 
-  shared_mime_info = import ../data/misc/shared-mime-info {
-	inherit fetchurl stdenv perl perlXMLParser pkgconfig gettext libxml2;
-	inherit (gtkLibs) glib;
+  shared_mime_info = selectVersion ../data/misc/shared-mime-info "0.23" {
+    inherit fetchurl stdenv perl perlXMLParser pkgconfig gettext libxml2;
+    inherit (gtkLibs) glib;
   };
 
   iana_etc = import ../data/misc/iana-etc {
@@ -3372,7 +4340,7 @@ rec {
   };
 
   poppler_data = import ../data/misc/poppler-data {
-	  inherit fetchurl stdenv;
+    inherit fetchurl stdenv;
   };
 
   ttf_bitstream_vera = import ../data/fonts/ttf-bitstream-vera {
@@ -3383,11 +4351,13 @@ rec {
     inherit fetchurl stdenv cabextract;
   };
 
-  xkeyboard_config = import ../data/misc/xkeyboard-config {
-    inherit fetchurl stdenv perl perlXMLParser;
+  xkeyboard_configFun = lib.sumArgs (selectVersion ../data/misc/xkeyboard-config "1.2") {
+    inherit fetchurl stdenv perl perlXMLParser gettext;
     inherit (xlibs) xkbcomp;
   };
 
+  xkeyboard_config = xkeyboard_configFun null;
+
 
   ### APPLICATIONS
 
@@ -3423,23 +4393,54 @@ rec {
   };
 
   audacity = import ../applications/audio/audacity {
-    inherit fetchurl libogg libvorbis libsndfile libmad 
-	pkgconfig gettext;
-	inherit (gtkLibs) gtk glib;
-	wxGTK = wxGTK28deps;
-    stdenv = overrideGCC stdenv gcc41NPTL;
-	inherit builderDefs stringsWithDeps;
+    inherit fetchurl stdenv libogg libvorbis libsndfile libmad 
+      pkgconfig gettext;
+    inherit (gtkLibs) gtk glib;
+    wxGTK = wxGTK28deps;
+    inherit builderDefs stringsWithDeps;
+  };
+
+  aumix = import ../applications/audio/aumix {
+    inherit fetchurl stdenv ncurses pkgconfig gettext;
+    inherit (gtkLibs) gtk;
+    gtkGUI = false;
   };
 
   batik = import ../applications/graphics/batik {
     inherit fetchurl stdenv unzip;
   };
 
+  bazaar = import ../applications/version-management/bazaar {
+    inherit fetchurl stdenv python makeWrapper;
+  };
+
+  bitlbee = import ../applications/networking/instant-messengers/bitlbee {
+    inherit fetchurl stdenv gnutls pkgconfig;
+    inherit (gtkLibs) glib;
+  };
+
   # commented out because it's using the new configuration style proposal which is unstable
   #biew = import ../applications/misc/biew {
   #  inherit lib stdenv fetchurl ncurses;
   #};
 
+  # only to be able to compile blender - I couldn't compile the default openal software
+  # Perhaps this can be removed - don't know which one openal{,soft} is better
+  freealut_soft = import ../development/libraries/freealut {
+    inherit fetchurl stdenv;
+    openal = openalSoft;
+  };
+
+  blender = import ../applications/misc/blender {
+    inherit stdenv cmake mesa gettext freetype SDL libtiff fetchurl glibc scons x11 lib
+      libjpeg libpng zlib /* smpeg  sdl */;
+    inherit (xlibs) inputproto libXi;
+    python = builtins.getAttr "2.5" python_alts;
+    freealut = freealut_soft;
+    openal = openalSoft;
+    openexr = openexr_1_4_0;
+  };
+
   bmp = import ../applications/audio/bmp {
     inherit fetchurl stdenv pkgconfig libogg libvorbis alsaLib id3lib;
     inherit (gnome) esound libglade;
@@ -3454,6 +4455,10 @@ rec {
     inherit fetchurl stdenv pkgconfig bmp;
   };
 
+  bvi = import ../applications/editors/bvi {
+    inherit fetchurl stdenv ncurses;
+  };
+
   cdparanoiaIII = import ../applications/audio/cdparanoia {
     inherit fetchurl stdenv;
   };
@@ -3480,10 +4485,9 @@ rec {
       libXinerama libICE libSM libXrender xextproto;
     inherit (gnome) startupnotification libwnck GConf;
     inherit (gtkLibs) gtk;
-    inherit (gnome) libgnome libgnomeui metacity
-	      glib pango libglade libgtkhtml gtkhtml
-              libgnomecanvas libgnomeprint
-              libgnomeprintui gnomepanel;
+    inherit (gnome) libgnome libgnomeui metacity glib pango
+      libglade libgtkhtml gtkhtml libgnomecanvas libgnomeprint
+      libgnomeprintui gnomepanel;
     gnomegtk = gnome.gtk;
     inherit librsvg fuse;
   };
@@ -3492,49 +4496,45 @@ rec {
     version = "0.6.2";
   };
 
-  compizFun = lib.sumArgs (assert mesaSupported; import ../applications/window-managers/compiz) {
- 	inherit lib builderDefs stringsWithDeps;
+  compizFun = lib.sumArgs (assert mesaSupported; selectVersion ../applications/window-managers/compiz "0.6.2") {
+    inherit lib builderDefs stringsWithDeps;
     inherit fetchurl stdenv pkgconfig libpng mesa perl perlXMLParser libxslt;
     inherit (xorg) libXcomposite libXfixes libXdamage libXrandr
-      libXinerama libICE libSM libXrender xextproto;
+      libXinerama libICE libSM libXrender xextproto compositeproto fixesproto
+      damageproto randrproto xineramaproto renderproto kbproto;
     inherit (gnome) startupnotification libwnck GConf;
     inherit (gtkLibs) gtk;
     inherit (gnome) libgnome libgnomeui metacity
-	      glib pango libglade libgtkhtml gtkhtml
-              libgnomecanvas libgnomeprint
-              libgnomeprintui gnomepanel;
+      glib pango libglade libgtkhtml gtkhtml
+      libgnomecanvas libgnomeprint
+      libgnomeprintui gnomepanel;
     gnomegtk = gnome.gtk;
     inherit librsvg fuse;
     inherit dbus dbus_glib;
   };
 
   compiz = compizFun {
-    version = getConfig ["compiz" "version"] "0.5.0";
     extraConfigureFlags = getConfig ["compiz" "extraConfigureFlags"] [];
   } null;
 
   compizFusion = assert mesaSupported; import ../applications/window-managers/compiz-fusion {
-
-  	version = getConfig ["compizFusion" "version"] "0.6.0" ;
-	inherit compiz;
-
-	inherit stringsWithDeps lib builderDefs;
-
+    version = getConfig ["compizFusion" "version"] "0.6.0";
+    inherit compiz;
+    inherit stringsWithDeps lib builderDefs;
     inherit fetchurl stdenv pkgconfig libpng mesa perl perlXMLParser libxslt;
     inherit (xorg) libXcomposite libXfixes libXdamage libXrandr
       libXinerama libICE libSM libXrender xextproto;
     inherit (gnome) startupnotification libwnck GConf;
     inherit (gtkLibs) gtk;
     inherit (gnome) libgnome libgnomeui metacity
-	      glib pango libglade libgtkhtml gtkhtml
-              libgnomecanvas libgnomeprint
-              libgnomeprintui gnomepanel gnomedesktop;
+      glib pango libglade libgtkhtml gtkhtml
+      libgnomecanvas libgnomeprint
+      libgnomeprintui gnomepanel gnomedesktop;
     gnomegtk = gnome.gtk;
     inherit librsvg fuse dbus dbus_glib git;
- 
- 	inherit automake autoconf libtool intltool python pyrex gettext;
-	inherit pygtk pycairo getopt libjpeg glxinfo;
-	inherit (xorg) xvinfo xdpyinfo;
+    inherit automake autoconf libtool intltool python pyrex gettext;
+    inherit pygtk pycairo getopt libjpeg glxinfo;
+    inherit (xorg) xvinfo xdpyinfo;
   };
   
   compizExtra = import ../applications/window-managers/compiz/extra.nix {
@@ -3543,6 +4543,10 @@ rec {
     inherit (gtkLibs) gtk;
   };
 
+  bbdb = import ../applications/editors/emacs-modes/bbdb {
+    inherit fetchurl stdenv emacs texinfo ctags;
+  };
+
   cua = import ../applications/editors/emacs-modes/cua {
     inherit fetchurl stdenv;
   };
@@ -3552,7 +4556,7 @@ rec {
   };
 
   cvs2svn = import ../applications/version-management/cvs2svn {
-    inherit fetchurl stdenv python bsddb3 makeWrapper;
+    inherit fetchurl stdenv python makeWrapper;
   };
 
   d4x = import ../applications/misc/d4x {
@@ -3561,7 +4565,14 @@ rec {
   };
   
   darcs = import ../applications/version-management/darcs {
-    inherit fetchurl stdenv ghc zlib ncurses curl;
+    inherit fetchurl stdenv zlib ncurses curl;
+    ghc = ghc661;
+  };
+
+  # some speed bottle necks are resolved in this version I think .. perhaps you like to try it? 
+  darcs_2_pre = import ../applications/version-management/darcs_2_pre.nix {
+    inherit fetchurl stdenv zlib ncurses curl;
+    ghc = ghc661;
   };
 
   dia = import ../applications/graphics/dia {
@@ -3574,15 +4585,20 @@ rec {
   djvulibre = import ../applications/misc/djvulibre {
     inherit stdenv fetchurl libjpeg libtiff libungif zlib
 	ghostscript libpng x11 mesa;
-    qt = qt3;
+    qt = if (getConfig ["djvulibre" "qt3Frontend"] true) then qt3 else null;
     inherit (xlibs) libX11;
   };
 
-  /*
-  djview4 = import ../applications/graphics/djview4 {
+  djview4 = import ../applications/graphics/djview {
     inherit fetchurl stdenv qt4 djvulibre;
   };
-  */
+
+  /* TODO: rename to be able to set version */
+  dvdplusrwtoolsFun = lib.sumArgs (selectVersion ../os-specific/linux/dvd+rw-tools "7.0") {
+    inherit fetchurl stdenv builderDefs cdrkit m4;
+  };
+ 
+  dvdplusrwtools = dvdplusrwtoolsFun null;
 
   eclipse = plugins:
     import ../applications/editors/eclipse {
@@ -3598,7 +4614,7 @@ rec {
 
   elinks = import ../applications/networking/browsers/elinks {
     inherit stdenv fetchurl python perl ncurses x11 zlib openssl spidermonkey
-	guile bzip2 libtool;
+	guile bzip2;
   };
 
   emacs = emacs22;
@@ -3628,6 +4644,20 @@ rec {
     xftSupport = true;
   };
 
+  exrdisplay = import ../applications/graphics/exrdisplay {
+    inherit fetchurl stdenv pkgconfig mesa which openexr_ctl;
+    fltk = fltk20;
+    openexr = openexr_1_6_1;
+  };
+
+  fbpanelFun = lib.sumArgs (selectVersion ../applications/window-managers/fbpanel "4.12") {
+    inherit fetchurl stdenv builderDefs pkgconfig libpng libjpeg libtiff librsvg;
+    inherit (gtkLibs) gtk;
+    inherit (xlibs) libX11 libXmu libXpm;
+  };
+
+  fbpanel = fbpanelFun null;
+
   fetchmail = import ../applications/misc/fetchmail {
     inherit stdenv fetchurl;
   };
@@ -3649,12 +4679,34 @@ rec {
     #enableOfficialBranding = true;
   });
 
-  firefoxWrapper = wrapFirefox firefox;
+  firefoxWrapper = wrapFirefox firefox "";
+
+  firefox3 = lowPrio (import ../applications/networking/browsers/firefox-3 {
+    inherit fetchurl stdenv pkgconfig perl zip libjpeg libpng zlib cairo
+      python curl coreutils dbus dbus_glib freetype fontconfig;
+    inherit (gtkLibs) gtk pango;
+    inherit (gnome) libIDL;
+    inherit (xlibs) libXi libX11 libXrender libXft libXt;
+    #enableOfficialBranding = true;
+  });
+
+  firefox3b1Bin = lowPrio (import ../applications/networking/browsers/firefox-3/binary.nix {
+    inherit fetchurl stdenv pkgconfig perl zip libjpeg libpng zlib cairo
+    	python curl coreutils freetype fontconfig;
+    inherit (gtkLibs) gtk atk pango glib;
+    inherit (gnome) libIDL;
+    inherit (xlibs) libXi libX11 libXrender libXft libXt;
+  });
 
-  flac = import ../applications/audio/flac {
+  firefox3Wrapper = lowPrio (wrapFirefox firefox3 "");
+  firefox3b1BinWrapper = lowPrio (wrapFirefox firefox3b1Bin "");
+ 
+  flacAlts = import ../applications/audio/flac {
     inherit fetchurl stdenv libogg;
   };
 
+  flac = getVersion "flac" flacAlts;
+
   flashplayer = flashplayer9;
 
   flashplayer7 = import ../applications/networking/browsers/mozilla-plugins/flashplayer-7 {
@@ -3670,6 +4722,12 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  freemind = import ../applications/misc/freemind {
+    inherit fetchurl stdenv ant;
+    jdk = jdk;
+    jre = jdk;
+  };
+
   fspot = import ../applications/graphics/f-spot {
     inherit fetchurl stdenv perl perlXMLParser pkgconfig mono
             libexif libjpeg sqlite lcms libgphoto2 monoDLLFixer;
@@ -3702,7 +4760,13 @@ rec {
   };
 
   git = import ../applications/version-management/git {
-    inherit fetchurl stdenv curl openssl zlib expat perl;
+    inherit fetchurl stdenv curl openssl zlib expat perl gettext emacs;
+  };
+
+  gkrellm = import ../applications/misc/gkrellm {
+    inherit fetchurl stdenv gettext pkgconfig;
+    inherit (gtkLibs) glib gtk;
+    inherit (xlibs) libX11 libICE libSM;
   };
 
   gnash = assert mesaSupported; import ../applications/video/gnash {
@@ -3711,16 +4775,14 @@ rec {
     inherit (xlibs) libX11 libXext libXi libXmu;
   };
 
-  gocrFun = lib.sumArgs (import ../applications/graphics/gocr) {
-  	inherit builderDefs fetchurl stdenv;
+  gocrFun = lib.sumArgs (selectVersion ../applications/graphics/gocr "0.44") {
+    inherit builderDefs fetchurl stdenv;
   };
 
-  gocr = gocrFun {
-  	version	= "0.44";
-  } null;
+  gocr = gocrFun null;
 
   gphoto2 = import ../applications/misc/gphoto2 {
-    inherit fetchurl stdenv pkgconfig libgphoto2 libexif popt;
+    inherit fetchurl stdenv pkgconfig libgphoto2 libexif popt readline gettext;
   };
 
   gqview = import ../applications/graphics/gqview {
@@ -3754,8 +4816,8 @@ rec {
     inherit (xlibs) libX11 libXft libXext libXinerama libXrandr;
   };
 
-  imagemagickFun = lib.sumArgs (import ../applications/graphics/ImageMagick) {
-    inherit stdenv fetchurl; 
+  imagemagickFun = lib.sumArgs (selectVersion ../applications/graphics/ImageMagick "6.3.8-5" ) {
+    inherit stdenv fetchurl libtool; 
   };
 
   imagemagick = imagemagickFun {
@@ -3771,12 +4833,11 @@ rec {
   } null;
 
   inkscape = import ../applications/graphics/inkscape {
-    inherit fetchurl perl perlXMLParser pkgconfig zlib
-      popt libxml2 libxslt libpng boehmgc fontconfig gtkmm
-      glibmm libsigcxx lcms boost gettext;
-    inherit (gtkLibs) gtk glib;
+    inherit fetchurl stdenv perl perlXMLParser pkgconfig zlib
+      popt libxml2 libxslt libpng boehmgc fontconfig
+      libsigcxx lcms boost gettext cairomm;
+    inherit (gtkLibs) gtk glib glibmm gtkmm;
     inherit (xlibs) libXft;
-    stdenv = overrideGCC stdenv gcc34;
   };
 
   ion3 = import ../applications/window-managers/ion-3 {
@@ -3789,10 +4850,25 @@ rec {
     inherit (gtkLibs) glib;
   };
 
+  jedit = import ../applications/jedit {
+    inherit fetchurl stdenv ant;
+  };
+
   joe = import ../applications/editors/joe {
     inherit stdenv fetchurl;
   };
 
+  kino = import ../applications/video/kino {
+    inherit fetchurl stdenv pkgconfig libxml2 perl perlXMLParser 
+      libdv libraw1394 libavc1394 libiec61883 x11 gettext cairo; /* libavformat */
+    inherit libsamplerate ffmpeg;
+    inherit (gnome) libglade gtk glib;
+    inherit (xlibs) libXv libX11;
+    inherit (gtkLibs) pango;
+    # #  optional
+    #  inherit ffmpeg2theora sox, vorbis-tools lame mjpegtools dvdauthor 'Q'dvdauthor growisofs mencoder;
+  };
+
   kuickshow = import ../applications/graphics/kuickshow {
     inherit fetchurl stdenv kdelibs arts libpng libjpeg libtiff libungif imlib expat perl;
     inherit (xlibs) libX11 libXext libSM;
@@ -3800,7 +4876,7 @@ rec {
   };
 
   lame = import ../applications/audio/lame {
-    inherit fetchurl stdenv ;
+    inherit fetchurl stdenv;
   };
 
   ladspaH = import ../applications/audio/ladspa-plugins/ladspah.nix {
@@ -3819,6 +4895,11 @@ rec {
     inherit fetchurl stdenv ncurses openssl;
   };
 
+  lyx = import ../applications/misc/lyx {
+   inherit fetchurl stdenv tetex python;
+   qt = qt4;
+  };
+
   maxima = import ../applications/misc/maxima {
     inherit fetchurl stdenv clisp;
   };
@@ -3847,6 +4928,10 @@ rec {
     inherit (xlibs) libXi;
   };
 
+  mpg321 = import ../applications/audio/mpg321 {
+    inherit stdenv fetchurl libao libmad libid3tag zlib;
+  };
+
   MPlayer = import ../applications/video/MPlayer {
     inherit fetchurl stdenv freetype x11 zlib libtheora libcaca freefont_ttf libdvdnav;
     inherit (xlibs) libX11 libXv libXinerama libXrandr;
@@ -3932,11 +5017,12 @@ rec {
   };
 
   opera = import ../applications/networking/browsers/opera {
-    inherit fetchurl stdenv zlib;
+    inherit fetchurl zlib glibc;
+    stdenv = overrideGCC stdenv gcc40;
     inherit (xlibs) libX11 libSM libICE libXt libXext;
     qt = qt3;
-    #motif = lesstif;
-    libstdcpp5 = gcc33.gcc;
+    #33motif = lesstif;
+    libstdcpp5 = (if (stdenv.system == "i686-linux") then gcc33 /* stdc++ 3.8 is used */ else gcc).gcc;
   };
 
   pan = import ../applications/networking/newsreaders/pan {
@@ -3946,7 +5032,7 @@ rec {
   };
 
   pinfo = import ../applications/misc/pinfo {
-    inherit fetchurl stdenv ncurses;
+    inherit fetchurl stdenv ncurses readline;
   };
 
   # perhaps there are better apps for this task? It's how I had configured my preivous system.
@@ -3961,9 +5047,27 @@ rec {
 
   pythonmagick = import ../applications/graphics/PythonMagick {
     inherit fetchurl stdenv pkgconfig imagemagick boost;
-    python = python25;
+    python = builtins.getAttr "2.5" python_alts;
   };
 
+  qemuFun = lib.sumArgs (selectVersion ../applications/virtualization/qemu "0.9.0") {
+    inherit fetchurl;
+    stdenv = overrideGCC stdenv gcc34;
+    builderDefs = builderDefs {
+      stdenv = (overrideGCC stdenv gcc34)//{gcc=gcc34;};
+    };
+    inherit SDL zlib which;
+  };
+
+  qemu = qemuFun null;
+
+  qemuImageFun = lib.sumArgs 
+    (selectVersion ../applications/virtualization/qemu/linux-img "0.2") {
+    inherit builderDefs fetchurl stdenv;
+  };
+
+  qemuImage = qemuImageFun null;
+
   ratpoison = import ../applications/window-managers/ratpoison {
     inherit fetchurl stdenv fontconfig readline;
     inherit (xlibs) libX11 inputproto libXt libXpm libXft
@@ -3974,6 +5078,11 @@ rec {
     inherit fetchurl stdenv;
   };
 
+  rdesktop = import ../applications/networking/remote/rdesktop {
+    inherit fetchurl stdenv openssl;
+    inherit (xlibs) libX11;
+  };
+
   RealPlayer = import ../applications/video/RealPlayer {
     inherit fetchurl stdenv;
     inherit (gtkLibs) glib pango atk gtk;
@@ -3992,7 +5101,7 @@ rec {
 
   # = urxvt
   rxvt_unicode = import ../applications/misc/rxvt_unicode {
-    inherit lib fetchurl stdenv perl;
+    inherit lib fetchurl stdenv;
     inherit (xlibs) libXt libX11 libXft;
   };
 
@@ -4024,9 +5133,9 @@ rec {
   } null;
 
   # commented out because it's using the new configuration style proposal which is unstable
-  /*
-  sox = import ../applications/misc/audio/sox {
-    inherit fetchurl stdenv lib mkDerivationByConfigruation;
+  
+  sox = if builtins ? listToAttrs then  import ../applications/misc/audio/sox {
+    inherit fetchurl stdenv lib mkDerivationByConfiguration;
     # optional features 
     inherit alsaLib; # libao
     inherit libsndfile libogg flac libmad lame libsamplerate;
@@ -4035,8 +5144,8 @@ rec {
      # /tmp/nix-7957-1/sox-14.0.0/src/ffmpeg.c:130: undefined reference to `avcodec_decode_audio2
      # That's why I'v added ffmpeg_svn
     ffmpeg = ffmpeg_svn;
-  };
-  */
+  } else null;
+  
 
   spoofax = import ../applications/editors/eclipse/plugins/spoofax {
     inherit fetchurl stdenv;
@@ -4054,11 +5163,14 @@ rec {
   };
 
   subversion14 = import ../applications/version-management/subversion-1.4.x {
-    inherit fetchurl stdenv apr aprutil neon expat swig zlib;
-    bdbSupport = true;
-    httpServer = false;
-    sslSupport = true;
-    compressionSupport = true;
+    inherit fetchurl stdenv apr aprutil neon expat swig zlib jdk;
+    bdbSupport = getConfig ["subversion" "bdbSupport"] true;
+    httpServer = getConfig ["subversion" "httpServer"] false;
+    sslSupport = getConfig ["subversion" "sslSupport"] true;
+	pythonBindings = getConfig ["subversion" "pythonBindings"] false;
+    perlBindings = getConfig ["subversion" "perlBindings"] false;
+	javahlBindings = getConfig ["subversion" "javahlBindings"] false;
+    compressionSupport = getConfig ["subversion" "compressionSupport"] true;
     httpd = apacheHttpd;
   };
 
@@ -4085,17 +5197,14 @@ rec {
     inherit (xlibs) xextproto libXtst inputproto;
   };
 
-  thunderbird = thunderbird2;
-
-  thunderbird1 = import ../applications/networking/mailreaders/thunderbird-1.x {
-    inherit fetchurl stdenv pkgconfig perl zip libjpeg libpng zlib cairo;
-    inherit (gtkLibs) gtk;
-    inherit (gnome) libIDL;
-    inherit (xlibs) libXi;
-    #enableOfficialBranding = true;
+  /* does'nt work yet i686-linux only (32bit version)
+  teamspeak_client = import ../applications/networking/instant-messengers/teamspeak/client.nix {
+    inherit fetchurl stdenv;
+    inherit glibc x11;
   };
+  */
 
-  thunderbird2 = import ../applications/networking/mailreaders/thunderbird-2.x {
+  thunderbird = import ../applications/networking/mailreaders/thunderbird-2.x {
     inherit fetchurl stdenv pkgconfig perl zip libjpeg libpng zlib cairo;
     inherit (gtkLibs) gtk;
     inherit (gnome) libIDL;
@@ -4107,6 +5216,10 @@ rec {
     inherit fetchurl stdenv alsaLib;
   };
 
+  tla = import ../applications/version-management/arch {
+    inherit fetchurl stdenv diffutils gnutar gnupatch which;
+  };
+
   unison = import ../applications/networking/sync/unison {
     inherit fetchurl stdenv ocaml lablgtk makeWrapper;
     inherit (xorg) xset fontschumachermisc;
@@ -4128,13 +5241,41 @@ rec {
   }));
 
   vimHugeX = import ../applications/editors/vim {
-    inherit fetchurl stdenv lib ncurses pkgconfig;
+    inherit fetchurl stdenv lib ncurses pkgconfig
+    	perl python tcl;
     inherit (xlibs) libX11 libXext libSM libXpm
 	libXt libXaw libXau;
     inherit (gtkLibs) glib gtk;
-    flags = ["hugeFeatures" "gtkGUI" "x11Support"];
+
+    # Looks like python and perl can conflict
+    flags = ["hugeFeatures" "gtkGUI" "x11Support"
+    	/*"perlSupport"*/ "pythonSupport" "tclSupport"];
   };
 
+  vim_configurable = import ../applications/editors/vim/configurable.nix {
+    inherit fetchurl stdenv ncurses pkgconfig mkDerivationByConfiguration lib;
+    inherit (xlibs) libX11 libXext libSM libXpm
+        libXt libXaw libXau libXmu;
+    inherit (gtkLibs) glib gtk;
+    features = "huge"; # one of  tiny, small, normal, big or huge
+    # optional features by passing
+    # python 
+    # TODO mzschemeinterp perlinterp
+    inherit python /*x11*/;
+
+    # optional features by flags
+    flags = [ "X11" ]; # only flag "X11" by now
+  };
+
+  /*virtualboxFun = lib.sumArgs (selectVersion ../applications/virtualization/virtualbox "1.5.2") {
+    inherit stdenv fetchurl builderDefs bridge_utils umlutilities kernelHeaders 
+      wine jre libxslt SDL qt3 openssl zlib;
+    inherit (xorg) libXcursor;
+    inherit (gnome) libIDL;
+  };
+
+  virtualbox = virtualboxFun null;*/
+
   vlc = import ../applications/video/vlc {
     inherit fetchurl stdenv perl x11 wxGTK
             zlib mpeg2dec a52dec libmad ffmpeg
@@ -4143,6 +5284,11 @@ rec {
     alsa = alsaLib;
   };
 
+  vorbisTools = import ../applications/audio/vorbis-tools {
+    inherit fetchurl stdenv libogg libvorbis libao pkgconfig curl glibc
+    	    speex flac;
+  };
+
   w3m = import ../applications/networking/browsers/w3m {
     inherit fetchurl stdenv ncurses openssl boehmgc gettext zlib;
     graphicsSupport = false;
@@ -4164,19 +5310,23 @@ rec {
     includeUnpack = getConfig ["stdenv" "includeUnpack"] false;
   };
 
-  wrapFirefox = firefox: import ../applications/networking/browsers/firefox-wrapper {
-    inherit stdenv firefox;
+  wordnet = import ../applications/misc/wordnet {
+    inherit stdenv fetchurl tcl tk x11 makeWrapper;
+  };
+
+  wrapFirefox = firefox: nameSuffix: import ../applications/networking/browsers/firefox-wrapper {
+    inherit stdenv firefox nameSuffix;
     plugins = []
     ++ lib.optional (system == "i686-linux") flashplayer
     # RealPlayer is disabled by default for legal reasons.
     ++ lib.optional (system != "i686-linux" && getConfig ["firefox" "enableRealPlayer"] false) RealPlayer
     ++ lib.optional (getConfig ["firefox" "enableMPlayer"] true) MPlayerPlugin
-    ++ lib.optional (supportsJDK && jrePlugin ? mozillaPlugin) jrePlugin;
+    ++ lib.optional (supportsJDK && getConfig ["firefox" "jre"] true && jrePlugin ? mozillaPlugin) jrePlugin;
   };
 
   xara = import ../applications/graphics/xara {
     inherit fetchurl stdenv autoconf automake libtool gettext cvs wxGTK
-      pkgconfig libxml2 zip libpng libjpeg;
+      pkgconfig libxml2 zip libpng libjpeg shebangfix perl freetype;
     inherit (gtkLibs) gtk;
   };
 
@@ -4201,7 +5351,8 @@ rec {
   };
 
   xineUI = import ../applications/video/xine-ui {
-    inherit fetchurl stdenv pkgconfig x11 xineLib libpng;
+	inherit fetchurl stdenv pkgconfig x11 xineLib libpng readline ncurses curl;
+	inherit (xorg) libXext libXv libXxf86vm libXtst inputproto;
   };
 
   xmms = import ../applications/audio/xmms {
@@ -4211,17 +5362,39 @@ rec {
     stdenv = overrideGCC stdenv gcc34; # due to problems with gcc 4.x
   };
 
+  xmonad = import ../applications/window-managers/xmonad {
+    inherit stdenv fetchurl ghc X11;
+    inherit (xlibs) xmessage;
+  };
+
   xpdf = import ../applications/misc/xpdf {
     inherit fetchurl stdenv x11 freetype t1lib;
     motif = lesstif;
     base14Fonts = "${ghostscript}/share/ghostscript/fonts";
   };
 
+  xscreensaverFun = lib.sumArgs (selectVersion ../applications/graphics/xscreensaver "5.04") {
+    inherit stdenv fetchurl builderDefs lib pkgconfig bc perl intltool;
+    inherit (xlibs) libX11 libXmu;
+  };
+
+  xscreensaver = xscreensaverFun {
+    flags = ["GL" "gdkpixbuf" "DPMS" "gui" "jpeg"];
+    inherit mesa libxml2 libjpeg;
+    inherit (gtkLibs) gtk;
+    inherit (gnome) libglade;
+  } null;
+
   xterm = import ../applications/misc/xterm {
     inherit fetchurl stdenv ncurses;
     inherit (xlibs) libXaw xproto libXt libX11 libSM libICE;
   };
 
+  xlaunch = import ../tools/X11/xlaunch {
+    inherit stdenv;
+    inherit (xorg) xorgserver;
+  };
+
   xmacro = import ../tools/X11/xmacro {
     inherit fetchurl stdenv;
     inherit (xlibs) libX11 libXi 
@@ -4233,6 +5406,7 @@ rec {
     inherit (xlibs) libX11 libXi imake libXau;
     inherit (xorg) xauth;
   };
+
   xvidcap = import ../applications/video/xvidcap {
     inherit fetchurl stdenv perl perlXMLParser pkgconfig;
     inherit (gtkLibs) gtk;
@@ -4240,6 +5414,23 @@ rec {
     inherit (xlibs) libXmu libXext;
   };
 
+  # doesn't compile yet - in case someone else want's to continue .. 
+  /*
+  qgis_svn = import ../applications/misc/qgis_svn {
+    inherit mkDerivationByConfiguration fetchsvn stdenv flex lib
+            ncurses fetchurl perl cmake gdal geos proj x11
+            gsl libpng zlib
+            sqlite glibc fontconfig freetype / * use libc from stdenv ? - to lazy now - Marc * /;
+    inherit (xlibs) libSM libXcursor libXinerama libXrandr libXrender;
+    inherit (xorg) libICE;
+    qt = qt4;
+    bison = bison23;
+
+    # optional features
+    # grass = "not yet supported" # cmake -D WITH_GRASS=TRUE  and GRASS_PREFX=..
+  };
+  */
+
   zapping = import ../applications/video/zapping {
     inherit fetchurl stdenv pkgconfig perl python 
             gettext zvbi libjpeg libpng x11
@@ -4255,6 +5446,15 @@ rec {
 
   ### GAMES
 
+  construoFun = lib.sumArgs (selectVersion ../games/construo "0.2.2") {
+    inherit stdenv fetchurl builderDefs
+      zlib;
+    inherit (xlibs) libX11 xproto;
+  };
+
+  construo = construoFun {
+    inherit mesa freeglut;
+  } null;
 
   exult = import ../games/exult {
     inherit fetchurl SDL SDL_mixer zlib libpng unzip;
@@ -4304,6 +5504,16 @@ rec {
     inherit fetchurl stdenv SDL zlib mpeg2dec;
   };
 
+  # You still can override by passing more arguments.
+  spaceOrbitFun = lib.sumArgs (selectVersion ../games/orbit "1.01") {
+    inherit fetchurl stdenv builderDefs 
+      mesa freeglut;
+    inherit (gnome) esound;
+    inherit (xlibs) libXt libX11 libXmu libXi libXext;
+  };
+
+  spaceOrbit = spaceOrbitFun null;
+
   /*tpm = import ../games/thePenguinMachine {
     inherit stdenv fetchurl pil pygame SDL; 
     python24 = python;
@@ -4332,7 +5542,7 @@ rec {
             perl perlXMLParser docbook_xml_dtd_42 docbook_xml_dtd_412
             gettext x11 libtiff libjpeg libpng gtkLibs xlibs bzip2
             libcm python dbus_glib ncurses which libxml2Python
-            iconnamingutils;
+            iconnamingutils openssl hal samba fam;
   });
 
   kdelibs = import ../desktops/kde/kdelibs {
@@ -4344,71 +5554,29 @@ rec {
     qt = qt3;
   };
   
-  kdelibs4 = import ../desktops/kde-4/kdelibs {
+  kde4 = recurseIntoAttrs (import ../desktops/kde-4 {
     inherit
-      fetchurl stdenv zlib perl openssl pcre pkgconfig
-      libjpeg libpng libtiff libxml2 libxslt libtool
-	  expat freetype bzip2 cmake strigi shared_mime_info alsaLib libungif cups;
-	inherit (xlibs)
-	  inputproto kbproto scrnsaverproto xextproto xf86miscproto
-	  xf86vidmodeproto xineramaproto xproto libICE libX11 libXau libXcomposite
-	  libXcursor libXdamage libXdmcp libXext libXfixes libXft libXi libXpm
-	  libXrandr libXrender libXScrnSaver libXt libXtst libXv libXxf86misc
-	  libxkbfile;
-    qt = qt4;
-  };
-
-  kdepimlibs4 = import ../desktops/kde-4/kdepimlibs {
-    inherit
-      fetchurl stdenv zlib perl openssl pcre pkgconfig
-      libjpeg libpng libtiff libxml2 libxslt libtool
-	  expat freetype bzip2 cmake strigi shared_mime_info alsaLib libungif cups
-	  boost gpgme;
-	inherit (xlibs)
-	  inputproto kbproto scrnsaverproto xextproto xf86miscproto
-	  xf86vidmodeproto xineramaproto xproto libICE libX11 libXau libXcomposite
-	  libXcursor libXdamage libXdmcp libXext libXfixes libXft libXi libXpm
-	  libXrandr libXrender libXScrnSaver libXt libXtst libXv libXxf86misc
-	  libxkbfile;
-    qt = qt4;
-	kdelibs = kdelibs4;
-  };
-
-  kdepim4 = import ../desktops/kde-4/kdepim {
-    inherit
-      fetchurl stdenv zlib perl openssl pcre pkgconfig
-      libjpeg libpng libtiff libxml2 libxslt libtool libusb
-	  expat freetype bzip2 cmake strigi shared_mime_info alsaLib libungif cups
-	  mesa gpgme boost;
-	inherit (xlibs)
-	  inputproto kbproto scrnsaverproto xextproto xf86miscproto
-	  xf86vidmodeproto xineramaproto xproto libICE libX11 libXau libXcomposite
-	  libXcursor libXdamage libXdmcp libXext libXfixes libXft libXi libXpm
-	  libXrandr libXrender libXScrnSaver libXt libXtst libXv libXxf86misc
-	  libxkbfile libXinerama;
-	inherit (gtkLibs) glib;
-    qt = qt4;
-	kdelibs = kdelibs4;
-	kdepimlibs = kdepimlibs4;
-  };
-
-  kdebase4 = import ../desktops/kde-4/kdebase {
-    inherit
-      fetchurl stdenv zlib perl openssl pcre pkgconfig
-      libjpeg libpng libtiff libxml2 libxslt libtool libusb
-	  expat freetype bzip2 cmake strigi shared_mime_info alsaLib libungif cups
-	  mesa;
-	inherit (xlibs)
-	  inputproto kbproto scrnsaverproto xextproto xf86miscproto
-	  xf86vidmodeproto xineramaproto xproto libICE libX11 libXau libXcomposite
-	  libXcursor libXdamage libXdmcp libXext libXfixes libXft libXi libXpm
-	  libXrandr libXrender libXScrnSaver libXt libXtst libXv libXxf86misc
-	  libxkbfile libXinerama;
-	inherit (gtkLibs) glib;
+      fetchurl fetchsvn zlib perl openssl pcre pkgconfig libjpeg libpng libtiff
+      libxml2 libxslt libtool libusb expat freetype bzip2 cmake cluceneCore libgcrypt gnupg
+	  cppunit cyrus_sasl openldap enchant exiv2 samba nss log4cxx aspell
+      shared_mime_info alsaLib libungif cups mesa boost gpgme gettext redland
+	  xineLib libgphoto2 djvulibre libogg flac lame libvorbis poppler readline
+	  saneBackends chmlib python libzip gmp sqlite libidn runCommand lib
+	  openbabel ocaml facile stdenv jasper fam indilib libnova
+	  libarchive dbus;
+	#flac = builtins.getAttr "1.1.2" flacAlts;
+	cdparanoia = cdparanoiaIII;
+    inherit (xlibs)
+      inputproto kbproto scrnsaverproto xextproto xf86miscproto
+      xf86vidmodeproto xineramaproto xproto libICE libX11 libXau libXcomposite
+      libXcursor libXdamage libXdmcp libXext libXfixes libXft libXi libXpm
+      libXrandr libXrender libXScrnSaver libXt libXtst libXv libXxf86misc
+      libxkbfile libXinerama;
+    inherit (gtkLibs) glib;
     qt = qt4;
-	kdelibs = kdelibs4;
-	kdepimlibs = kdepimlibs4;
-  };
+	bison = bison23;
+    openexr = openexr_1_6_1 ;
+  });
 
   kdebase = import ../desktops/kde/kdebase {
     inherit
@@ -4501,10 +5669,16 @@ rec {
     inherit stdenv fetchurl jdk;
   };
 
+  # don't have time for the source build right now
+  # maven2
+  mvn_bin = import ../misc/maven/maven-2.nix {
+    inherit fetchurl stdenv;
+  };
+
   nix = import ../tools/package-management/nix {
-    inherit fetchurl stdenv perl curl bzip2;
+    inherit fetchurl stdenv perl curl bzip2 openssl;
     aterm = aterm242fixes;
-    db4 = db44;
+    db4 = db45;
   };
 
   nixStatic = import ../tools/package-management/nix-static {
@@ -4520,10 +5694,31 @@ rec {
     db4 = db45;
   };
 
+  nixCustomFun = src: preConfigure: configureFlags :
+  (import ../tools/package-management/nix/custom.nix {
+    inherit fetchurl stdenv perl curl bzip2 openssl src preConfigure automake 
+        autoconf libtool configureFlags;
+    bison = bison23;
+    flex = flex2533;
+    aterm = aterm242fixes;
+    db4 = db45;
+    inherit docbook5_xsl libxslt docbook5 docbook_xml_dtd_43 w3m;
+
+  });
+
   ntfs3g = import ../misc/ntfs-3g {
     inherit fetchurl stdenv fuse pkgconfig;
   };
 
+  ntfsprogs = import ../misc/ntfsprogs {
+    inherit fetchurl stdenv;
+  };
+
+  pgadmin = import ../applications/misc/pgadmin {
+    inherit fetchurl stdenv postgresql libxml2 libxslt openssl;
+    wxGTK = wxGTK28;
+  };
+
   pgf = import ../misc/tex/pgf {
     inherit fetchurl stdenv;
   };
@@ -4541,6 +5736,10 @@ rec {
     inherit fetchurl stdenv x11 mesa;
   };
 
+  xlockmore = import ../misc/screensavers/xlockmore {
+    inherit fetchurl stdenv pam x11 freetype;
+  };
+
   saneBackends = import ../misc/sane-backends {
     inherit fetchurl stdenv libusb;
 	gt68xxFirmware = 
@@ -4554,6 +5753,16 @@ rec {
     inherit (xlibs) libX11;
   };
 
+  # State Nix
+  snix = import ../tools/package-management/snix {
+    inherit fetchurl stdenv perl curl bzip2 openssl;
+    aterm = aterm242fixes;
+    db4 = db45;
+
+    inherit ext3cowtools e3cfsprogs rsync;
+    ext3cow_kernel = kernel;
+  };
+
   synaptics = import ../misc/synaptics {
     inherit fetchurl stdenv pkgconfig;
     inherit (xlibs) libX11 libXi libXext pixman xf86inputevdev;
@@ -4564,6 +5773,13 @@ rec {
     inherit fetchurl stdenv flex bison zlib libpng ncurses ed;
   };
 
+  /*tetexX11 = import ../misc/tex/tetex {
+    inherit fetchurl stdenv flex bison zlib libpng ncurses ed;
+    inherit (xlibs) libX11 libXext libXmu libXaw libXt libXpm;
+    inherit freetype t1lib;
+    builderX11 = true;
+  };*/
+
   texFunctions = import ../misc/tex/nix {
     inherit stdenv perl tetex graphviz ghostscript;
   };
@@ -4591,10 +5807,9 @@ rec {
   };
 
   wine = import ../misc/emulators/wine {
-    stdenv = overrideGCC stdenv gcc41NPTL;
-    inherit fetchurl flex bison mesa ncurses
+    inherit fetchurl stdenv flex bison mesa ncurses
       libpng libjpeg alsaLib lcms xlibs freetype
-      fontconfig fontforge;
+      fontconfig fontforge libxml2 libxslt openssl;
   };
 
   xsane = import ../misc/xsane {
diff --git a/pkgs/top-level/build-for-release.nix b/pkgs/top-level/build-for-release.nix
index 9f9ab69e49a..bb892735edd 100644
--- a/pkgs/top-level/build-for-release.nix
+++ b/pkgs/top-level/build-for-release.nix
@@ -29,7 +29,7 @@ let {
     cdrkit
     chatzilla
     cksfv
-    compiz
+    #compiz
     coreutils
     cpio
     cron
@@ -62,6 +62,7 @@ let {
     gcc42
     gdb
     ghc
+    ghc68
     ghostscript
     gimp
     gnugrep
@@ -79,6 +80,7 @@ let {
     iana_etc
     iputils
     irssi
+    iwlwifi
     jakartaregexp
     jdkPlugin
     jetty
@@ -230,6 +232,7 @@ let {
     bison23
     gcc
     hello
+    iwlwifi
     kernel
     libtool
     nixUnstable
@@ -237,10 +240,6 @@ let {
     ;    
   };
   
-  powerpcLinuxPkgs = {inherit (allPackages {system = "powerpc-linux";})
-    aterm
-  ;};
-  
   i686FreeBSDPkgs = {inherit (allPackages {system = "i686-freebsd";})
     aterm
     autoconf
@@ -303,7 +302,7 @@ let {
     powerpcLinuxPkgs
     i686FreeBSDPkgs
     powerpcDarwinPkgs
-#    i686DarwinPkgs
+    i686DarwinPkgs
     cygwinPkgs
   ];
 }
diff --git a/pkgs/top-level/builder-defs.nix b/pkgs/top-level/builder-defs.nix
index 3337d6dc8a2..6b53ba76fd4 100644
--- a/pkgs/top-level/builder-defs.nix
+++ b/pkgs/top-level/builder-defs.nix
@@ -1,8 +1,10 @@
 args: with args; with stringsWithDeps; with lib;
-rec
+(rec
 {
 	inherit writeScript; 
 
+	addSbinPath = getAttr ["addSbinPath"] false args;
+
 	forceShare = if args ? forceShare then args.forceShare else ["man" "doc" "info"];
 
 	archiveType = s: 
@@ -10,32 +12,37 @@ rec
 		else if (hasSuffixHack ".tar.gz" s) || (hasSuffixHack ".tgz" s) then "tgz" 
 		else if (hasSuffixHack ".tar.bz2" s) || (hasSuffixHack ".tbz2" s) then "tbz2"
 		else if (hasSuffixHack ".zip" s) || (hasSuffixHack ".ZIP" s) then "zip"
-		else (abort "unknown archive type : ${s}"));
+		else if (hasSuffixHack "-cvs-export" s) then "cvs-dir"
+		else if (hasSuffixHack ".nar.bz2" s) then "narbz2"
 
-	minInit = noDepEntry ("
-		set -e
-		NIX_GCC=${stdenv.gcc}
-		export SHELL=${stdenv.shell}
-		# Set up the initial path.
-		PATH=
-		for i in \$NIX_GCC ${toString stdenv.initialPath}; do
-		    PATH=\$PATH\${PATH:+:}\$i/bin
-		done
-	" + (if ((stdenv ? preHook) && (stdenv.preHook != null) && 
-			((toString stdenv.preHook) != "")) then 
-		"
-		param1=${stdenv.param1}
-		param2=${stdenv.param2}
-		param3=${stdenv.param3}
-		param4=${stdenv.param4}
-		param5=${stdenv.param5}
-		source ${stdenv.preHook}
+		# Last block - for single files!! It should be always after .tar.*
+		else if (hasSuffixHack ".bz2" s) then "plain-bz2"
 
-		export TZ=UTC
+		else (abort "unknown archive type : ${s}"));
 
-		prefix=${if args ? prefix then (toString args.prefix) else "\$out"}
+	defAddToSearchPath = FullDepEntry ("
+		addToSearchPathWithCustomDelimiter() {
+			local delimiter=\$1
+			local varName=\$2
+			local needDir=\$3
+			local addDir=\${4:-\$needDir}
+			local prefix=\$5
+			if [ -d \$prefix\$needDir ]; then
+				if [ -z \${!varName} ]; then
+					eval export \${varName}=\${prefix}\$addDir
+				else
+					eval export \${varName}=\${!varName}\${delimiter}\${prefix}\$addDir
+				fi
+			fi
+		}
 
+		addToSearchPath()
+		{
+			addToSearchPathWithCustomDelimiter \"\${PATH_DELIMITER}\" \"\$@\"
+		}
+	") ["defNest"];
 
+	defNest = noDepEntry ("
 		nestingLevel=0
 
 		startNest() {
@@ -62,10 +69,33 @@ rec
 		}
 
 		trap \"closeNest\" EXIT
+	");
 
+	minInit = FullDepEntry ("
+		set -e
+		NIX_GCC=${stdenv.gcc}
+		export SHELL=${stdenv.shell}
+		# Set up the initial path.
+		PATH=
+		for i in \$NIX_GCC ${toString stdenv.initialPath}; do
+		    PATH=\$PATH\${PATH:+:}\$i/bin
+		done
+	" + (if ((stdenv ? preHook) && (stdenv.preHook != null) && 
+			((toString stdenv.preHook) != "")) then 
+		"
+		param1=${stdenv.param1}
+		param2=${stdenv.param2}
+		param3=${stdenv.param3}
+		param4=${stdenv.param4}
+		param5=${stdenv.param5}
+		source ${stdenv.preHook}
+
+		export TZ=UTC
+
+		prefix=${if args ? prefix then (toString args.prefix) else "\$out"}
 
 		"
-	else ""));
+	else "")) ["defNest" "defAddToSearchPath"];
 		
 	addInputs = FullDepEntry ("
 		# Recursively find all build inputs.
@@ -85,18 +115,10 @@ rec
 		    if test -f \$pkg/nix-support/setup-hook; then
 			source \$pkg/nix-support/setup-hook
 		    fi
-		    
-		    if test -f \$pkg/nix-support/propagated-build-inputs; then
-			for i in \$(cat \$pkg/nix-support/propagated-build-inputs); do
-			    findInputs \$i
-			done
-		    fi
 		}
 
 		pkgs=\"\"
-		for i in \$NIX_GCC ${toString buildInputs} ${toString 
-		(if (args ? propagatedBuildInputs) then 
-		args.propagatedBuildInputs else "")}; do
+		for i in \$NIX_GCC ${toString buildInputs}; do
 		    findInputs \$i
 		done
 
@@ -113,6 +135,11 @@ rec
 			fail
 		    fi
 		" else "")
+		+(if addSbinPath then "
+		    if test -d \$1/sbin; then
+			export _PATH=\$_PATH\${_PATH:+:}\$1/sbin
+		    fi
+		" else "")
 		+"
 		    if test -d \$1/bin; then
 			export _PATH=\$_PATH\${_PATH:+:}\$1/bin
@@ -134,7 +161,7 @@ rec
 		fi
 
 		PATH=\$_PATH\${_PATH:+:}\$PATH
-	") [minInit];
+	") ["minInit"];
 	
 	defEnsureDir = FullDepEntry ("
 		# Ensure that the given directories exists.
@@ -144,7 +171,7 @@ rec
 			if ! test -x \"\$dir\"; then mkdir -p \"\$dir\"; fi
 		    done
 		}
-	") [minInit];
+	") ["minInit"];
 
 	toSrcDir = s : FullDepEntry ((if (archiveType s) == "tar" then "
 		tar xvf '${s}'
@@ -159,13 +186,26 @@ rec
 		unzip '${s}'
 		cd \"$( unzip -lqq '${s}' | tail -1 | 
 			sed -e 's@^\\(\\s\\+[-0-9:]\\+\\)\\{3,3\\}\\s\\+\\([^/]\\+\\)/.*@\\2@' )\"
+	" else if (archiveType s) == "cvs-dir" then "
+		cp -r '${s}' .
+		cd \$(basename ${s})
+		chmod u+rwX -R .
+	" else if (archiveType s) == "narbz2" then "
+		bzip2 <${s} | nix-store --restore \$PWD/\$(basename ${s} .nar.bz2)
+		cd \$(basename ${s} .nar.bz2)
+	" else if (archiveType s) == "plain-bz2" then "
+		mkdir \$PWD/\$(basename ${s} .bz2)
+		NAME=\$(basename ${s} .bz2)
+		bzip2 -d <${s} > \$PWD/\$(basename ${s} .bz2)/\${NAME#*-}
+		cd \$(basename ${s} .bz2)
 	" else (abort "unknown archive type : ${s}"))+
+                # goSrcDir is typically something like "cd mysubdir" .. but can be anything else 
 		(if args ? goSrcDir then args.goSrcDir else "")
-	) [minInit];
+	) ["minInit"];
 
 	doConfigure = FullDepEntry ("
-		./configure --prefix=\"\$prefix\" ${toString (getAttr ["configureFlags"] "" args)}
-	") [minInit addInputs doUnpack];
+		./configure --prefix=\"\$prefix\" ${toString configureFlags}
+	") ["minInit" "addInputs" "doUnpack"];
 
 	doAutotools = FullDepEntry ("
 		mkdir -p config
@@ -175,21 +215,21 @@ rec
 		autoheader || true; 
 		automake --add-missing --copy
 		autoconf
-	")[minInit addInputs doUnpack];
+	")["minInit" "addInputs" "doUnpack"];
 
 	doMake = FullDepEntry ("	
-		make ${toString (getAttr ["makeFlags"] "" args)}
-	") [minInit addInputs doUnpack];
+		make ${toString makeFlags}
+	") ["minInit" "addInputs" "doUnpack"];
 
 	doUnpack = toSrcDir (toString src);
 
 	installPythonPackage = FullDepEntry ("
 		python setup.py install --prefix=\"\$prefix\" 
-		") [minInit addInputs doUnpack];
+		") ["minInit" "addInputs" "doUnpack"];
 
 	doMakeInstall = FullDepEntry ("
 		make ${toString (getAttr ["makeFlags"] "" args)} "+
-			"${toString (getAttr ["installFlags"] "" args)} install") [doMake];
+			"${toString (getAttr ["installFlags"] "" args)} install") ["doMake"];
 
 	doForceShare = FullDepEntry (" 
 		ensureDir \"\$prefix/share\"
@@ -199,7 +239,7 @@ rec
 				ln -sv share/\$d \"\$prefix\"
 			fi;
 		done;
-	") [minInit defEnsureDir];
+	") ["minInit" "defEnsureDir"];
 
 	doDump = n: noDepEntry "echo Dump number ${n}; set";
 
@@ -211,7 +251,7 @@ rec
 
 	doPatch = FullDepEntry (concatStringsSep ";"
 		(map toPatchCommand patches)
-	) [minInit doUnpack];
+	) ["minInit" "doUnpack"];
 
 	envAdderInner = s: x: if x==null then s else y: 
 		a: envAdderInner (s+"echo export ${x}='\"'\"\$${x}:${y}\";'\"'\n") a;
@@ -229,12 +269,12 @@ rec
 		(${envAdderList env}
 		echo '\"'\"${cmd}-orig\"'\"' '\"'\\\$@'\"' \n)  > \"${cmd}\"";
 
-	doWrap = cmd: FullDepEntry (wrapEnv cmd (getAttr ["wrappedEnv"] [] args)) [minInit];
+	doWrap = cmd: FullDepEntry (wrapEnv cmd (getAttr ["wrappedEnv"] [] args)) ["minInit"];
 
 	doPropagate = FullDepEntry ("
 		ensureDir \$out/nix-support
 		echo '${toString (getAttr ["propagatedBuildInputs"] [] args)}' >\$out/nix-support/propagated-build-inputs
-	") [minInit defEnsureDir];
+	") ["minInit" "defEnsureDir"];
 
 	/*debug = x:(__trace x x);
 	debugX = x:(__trace (__toXML x) x);*/
@@ -243,8 +283,103 @@ rec
 	replaceInScript = file: l: (concatStringsSep "\n" ((pairMap (replaceScriptVar file) l)));
 	replaceScripts = l:(concatStringsSep "\n" (pairMap replaceInScript l));
 	doReplaceScripts = FullDepEntry (replaceScripts (getAttr ["shellReplacements"] [] args)) [minInit];
-	makeNest = x:(if x==minInit.text then x else "startNest\n" + x + "\nstopNest\n");
-	textClosure = textClosureMap makeNest;
+	makeNest = x:(if x==defNest.text then x else "startNest\n" + x + "\nstopNest\n");
+        textClosure = a : steps : textClosureMapOveridable makeNest a (["defNest"] ++ steps);
 
 	inherit noDepEntry FullDepEntry PackEntry;
-}
+
+	defList = (getAttr ["defList"] [] args);
+	getVal = getValue args defList;
+	check = checkFlag args;
+	reqsList = getAttr ["reqsList"] [] args;
+	buildInputsNames = filter (x: (null != getVal x))
+		(uniqList {inputList = 
+		(concatLists (map 
+		(x:(if (x==[]) then [] else builtins.tail x)) 
+		reqsList));});
+	configFlags = getAttr ["configFlags"] [] args;
+	buildFlags = getAttr ["buildFlags"] [] args;
+	nameSuffixes = getAttr ["nameSuffixes"] [] args;
+	autoBuildInputs = assert (checkReqs args defList reqsList);
+		filter (x: x!=null) (map getVal buildInputsNames);
+	autoConfigureFlags = condConcat "" configFlags check;
+	autoMakeFlags = condConcat "" buildFlags check;
+	useConfig = getAttr ["useConfig"] false args;
+	buildInputs = 
+		lib.closePropagation ((if useConfig then 
+			autoBuildInputs else 
+			getAttr ["buildInputs"] [] args)++
+			(getAttr ["propagatedBuildInputs"] [] args));
+	configureFlags = if useConfig then autoConfigureFlags else 
+	    getAttr ["configureFlags"] "" args;
+	makeFlags = if useConfig then autoMakeFlags else getAttr ["makeFlags"] "" args;
+
+	inherit lib;
+
+	surroundWithCommands = x : before : after : {deps=x.deps; text = before + "\n" +
+		x.text + "\n" + after ;};
+
+
+        # some haskell stuff  - untested!
+        # --------------------------------------------------------
+        # creates a setup hook
+        # adding the package database 
+        # nix-support/package.conf to GHC_PACKAGE_PATH
+        # if not already contained
+        # using nix-support because user does'nt want to have it in it's
+        # nix-profile I think?
+        defSetupHookRegisteringPackageDatabase = noDepEntry (
+          "\nsetupHookRegisteringPackageDatabase(){" +
+          "\n  ensureDir $out/nix-support;" +
+          "\n  if test -n \"$1\"; then" +
+          "\n    local pkgdb=$1" +
+          "\n  else" +
+          "\n    local pkgdb=$out/nix-support/package.conf" +
+          "\n  fi" +
+          "\n  cat >> $out/nix-support/setup-hook << EOF" +
+          "\n    " +
+          "\n    echo \$GHC_PACKAGE_PATH | grep -l $pkgdb &> /dev/null || \" "+
+          "\n      export GHC_PACKAGE_PATH=\$GHC_PACKAGE_PATH\${GHC_PACKAGE_PATH:+$PATH_DELIMITER}$pkgdb;" +
+          "\nEOF" +
+          "\n}");
+
+        # Either rungghc or compile setup.hs 
+        # / which one is better ? runghc had some trouble with ghc-6.6.1
+        defCabalSetupCmd = noDepEntry "
+          CABAL_SETUP=\"runghc setup.hs\"
+        ";
+        
+        # create an empty package database in which the new library can be registered. 
+        defCreateEmptyPackageDatabaseAndSetupHook = FullDepEntry "
+          createEmptyPackageDatabaseAndSetupHook(){
+            ensureDir $out/nix-support;
+            PACKAGE_DB=$out/nix-support/package.conf;
+            echo '[]' > \"$PACKAGE_DB\";
+            setupHookRegisteringPackageDatabase
+        }" ["defSetupHookRegisteringPackageDatabase" "defEnsureDir"];
+
+        # Cabal does only support --user ($HOME/.ghc/** ) and --global (/nix/store/*-ghc/lib/...) 
+        # But we need kind of --custom=my-package-db
+        # by accident cabal does support using multiple databases passed by GHC_PACKAGE_PATH
+        # 
+        # Options:
+        # 1) create a local package db containing all dependencies
+        # 2) create a single db file for each package merging them using GHC_PACKAGE_PATH=db1:db2 
+        # (no trailing : which would mean add global and user db)
+        # I prefer 2) (Marc Weber) so the most convinient way is
+        # using ./setup copy to install
+        # and   ./setup register --gen-script to install to our local database 
+        # after replacing /usr/lib etc with our pure $out path
+        cabalBuild = FullDepEntry 
+          " createEmptyPackageDatabaseAndSetupHook
+          ghc --make setup.hs -o setup
+          \$CABAL_SETUP configure
+          \$CABAL_SETUP build
+          \$CABAL_SETUP copy --dest-dir=\$out
+          \$CABAL_SETUP register --gen-script
+          sed -e 's=/usr/local/lib=\$out=g' \\
+              -i register.sh
+          GHC_PACKAGE_PATH=\$PACKAGE_DB ./register.sh
+        " ["defCreateEmptyPackageDatabaseAndSetupHook" "defCabalSetupCmd"];
+
+}) // args
diff --git a/pkgs/top-level/template-composing+config.nix b/pkgs/top-level/template-composing+config.nix
new file mode 100644
index 00000000000..172cd9c4797
--- /dev/null
+++ b/pkgs/top-level/template-composing+config.nix
@@ -0,0 +1,23 @@
+args : with args; let localDefs = builderDefs (args // rec {
+		src = /* put a fetchurl here */
+		(abort "Specify source");
+		useConfig = true;
+		reqsList = [
+			["true" ]
+			["false"]
+		];
+		/* List consisiting of an even number of strings; "key" "value" */
+		configFlags = [
+		];
+	}) null; /* null is a terminator for sumArgs */
+	in with localDefs;
+stdenv.mkDerivation rec {
+	name = "${(abort "Specify name")}"+version;
+	builder = writeScript (name + "-builder")
+		(textClosure localDefs [(abort "Check phases") doMakeInstall doForceShare doPropagate]);
+	meta = {
+		description = "
+	${(abort "Specify description")}
+";
+	};
+}
diff --git a/pkgs/top-level/template-composing-builder.nix b/pkgs/top-level/template-composing-builder.nix
index 8117b156879..88bf2b63cfa 100644
--- a/pkgs/top-level/template-composing-builder.nix
+++ b/pkgs/top-level/template-composing-builder.nix
@@ -1,14 +1,16 @@
-args : with args;
-	with builderDefs {
+args : with args; with builderDefs {src="";} null;
+	let localDefs = builderDefs (rec {
 		src = /* put a fetchurl here */
 
 		buildInputs = [];
 		configureFlags = [];
-	} null; /* null is a terminator for sumArgs */
+	}) null; /* null is a terminator for sumArgs */
+	in with localDefs;
 stdenv.mkDerivation rec {
-	name = "${abort "Specify name"}";
+	name = "${abort "Specify name"}-"+version;
 	builder = writeScript (name + "-builder")
-		(textClosure [(abort "Specify phases - defined here or in builderDefs") doForceShare doPropagate]);
+		(textClosure localDefs 
+			[(abort "Specify phases - defined here or in builderDefs") doForceShare doPropagate]);
 	meta = {
 		description = "
 		${abort "Write a description"}
diff --git a/pkgs/top-level/template.nix b/pkgs/top-level/template.nix
deleted file mode 100644
index fabd6de584a..00000000000
--- a/pkgs/top-level/template.nix
+++ /dev/null
@@ -1,45 +0,0 @@
-args:
-let 
-	defList = [
-(assert false) - correct it; List element is of form ["name" default]
-	];
-	#stdenv and fetchurl are added automatically
-	getVal = (args.lib.getValue args defList);
-	check = args.lib.checkFlag args;
-	reqsList = [
-(assert false) - correct it; List element is of form ["name" "requirement-name" ... ]
-		["true"]
-		["false"]
-	];
-	buildInputsNames = args.lib.filter (x: (null!=getVal x)) 
-		(args.lib.uniqList {inputList = 
-		(args.lib.concatLists (map 
-		(x:(if (x==[]) then [] else builtins.tail x)) 
-		reqsList));});
-	configFlags = [
-		"true" ""
-(assert false) - fill it; list consists of pairs "condition" "flags". "True" means always.
-	];
-	nameSuffixes = [
-(assert false) - fill it if needed, or blank it.
-	];
-in
-	assert args.lib.checkReqs args defList reqsList;
-with args; 
-args.stdenv.mkDerivation {
-  name = args.lib.condConcat "
-#Fill the name //
-" nameSuffixes check;
- 
-  src = args.
-#Put fetcher here 
- 
-  buildInputs = args.lib.filter (x: x!=null) (map getVal buildInputsNames);
-  configureFlags = args.lib.condConcat "" configFlags check;
-
-  meta = {
-    description = "
-#Fill description here
-";
-  };
-}
diff --git a/pkgs/top-level/version-stub.nix b/pkgs/top-level/version-stub.nix
deleted file mode 100644
index c8e4bcf9545..00000000000
--- a/pkgs/top-level/version-stub.nix
+++ /dev/null
@@ -1,2 +0,0 @@
-args : 
-(import (__toPath ((toString ./JustNothing/.. )+"/"+args.version+".nix"))) args