Index: boot/Makefile.common
===================================================================
--- boot/Makefile.common	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ boot/Makefile.common	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -168,4 +168,5 @@
 
 RD_APPS_NON_ESSENTIAL = \
+	$(USPACE_PATH)/app/barber/barber \
 	$(USPACE_PATH)/app/bithenge/bithenge \
 	$(USPACE_PATH)/app/blkdump/blkdump \
Index: kernel/generic/src/sysinfo/stats.c
===================================================================
--- kernel/generic/src/sysinfo/stats.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ kernel/generic/src/sysinfo/stats.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -80,18 +80,4 @@
 static mutex_t load_lock;
 
-/** Get system uptime
- *
- * @param item Sysinfo item (unused).
- * @param data Unused.
- *
- * @return System uptime (in secords).
- *
- */
-static sysarg_t get_stats_uptime(struct sysinfo_item *item, void *data)
-{
-	/* This doesn't have to be very accurate */
-	return uptime->seconds1;
-}
-
 /** Get statistics of all CPUs
  *
@@ -818,5 +804,4 @@
 	mutex_initialize(&load_lock, MUTEX_PASSIVE);
 	
-	sysinfo_set_item_gen_val("system.uptime", NULL, get_stats_uptime, NULL);
 	sysinfo_set_item_gen_data("system.cpus", NULL, get_stats_cpus, NULL);
 	sysinfo_set_item_gen_data("system.physmem", NULL, get_stats_physmem, NULL);
Index: uspace/Makefile
===================================================================
--- uspace/Makefile	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/Makefile	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -34,4 +34,5 @@
 
 DIRS = \
+	app/barber \
 	app/bdsh \
 	app/bithenge \
@@ -211,4 +212,5 @@
 	lib/fmtutil \
 	lib/scsi \
+	lib/compress \
 	lib/softint \
 	lib/softfloat \
Index: uspace/Makefile.common
===================================================================
--- uspace/Makefile.common	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/Makefile.common	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -144,4 +144,5 @@
 LIBNIC_PREFIX = $(LIB_PREFIX)/nic
 LIBMINIX_PREFIX = $(LIB_PREFIX)/minix
+LIBCOMPRESS_PREFIX = $(LIB_PREFIX)/compress
 
 LIBSCSI_PREFIX = $(LIB_PREFIX)/scsi
Index: uspace/app/barber/Makefile
===================================================================
--- uspace/app/barber/Makefile	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/app/barber/Makefile	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,88 @@
+#
+# Copyright (c) 2014 Martin Decky
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+# - Redistributions in binary form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in the
+#   documentation and/or other materials provided with the distribution.
+# - The name of the author may not be used to endorse or promote products
+#   derived from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+USPACE_PREFIX = ../..
+
+LIBS = \
+	$(LIBGUI_PREFIX)/libgui.a \
+	$(LIBDRAW_PREFIX)/libdraw.a \
+	$(LIBCOMPRESS_PREFIX)/libcompress.a \
+	$(LIBSOFTREND_PREFIX)/libsoftrend.a \
+	$(LIBSOFTFLOAT_PREFIX)/libsoftfloat.a
+
+EXTRA_CFLAGS += \
+	-I$(LIBGUI_PREFIX) \
+	-I$(LIBDRAW_PREFIX) \
+	-I$(LIBSOFTREND_PREFIX)
+
+BINARY = barber
+MATH = y
+
+SOURCES = \
+	barber.c \
+	images.c
+
+IMAGES = \
+	gfx/frame01.tga.gz \
+	gfx/frame02.tga.gz \
+	gfx/frame03.tga.gz \
+	gfx/frame04.tga.gz \
+	gfx/frame05.tga.gz \
+	gfx/frame06.tga.gz \
+	gfx/frame07.tga.gz \
+	gfx/frame08.tga.gz \
+	gfx/frame09.tga.gz \
+	gfx/frame10.tga.gz \
+	gfx/frame11.tga.gz \
+	gfx/frame12.tga.gz \
+	gfx/frame13.tga.gz \
+	gfx/frame14.tga.gz \
+	gfx/frame15.tga.gz \
+	gfx/frame16.tga.gz \
+	gfx/frame17.tga.gz \
+	gfx/frame18.tga.gz \
+	gfx/frame19.tga.gz \
+	gfx/frame20.tga.gz \
+	gfx/frame21.tga.gz \
+	gfx/frame22.tga.gz \
+	gfx/frame23.tga.gz \
+	gfx/frame24.tga.gz \
+	gfx/frame25.tga.gz \
+	gfx/frame26.tga.gz \
+	gfx/frame27.tga.gz \
+	gfx/frame28.tga.gz \
+	gfx/frame29.tga.gz \
+	gfx/frame30.tga.gz
+
+PRE_DEPEND = images.c images.h
+EXTRA_CLEAN = images.c images.h
+
+include $(USPACE_PREFIX)/Makefile.common
+
+images.c images.h: $(IMAGES)
+	$(ROOT_PATH)/tools/mkarray.py images COMPOSITOR_IMAGES $^
Index: uspace/app/barber/barber.c
===================================================================
--- uspace/app/barber/barber.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/app/barber/barber.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,339 @@
+/*
+ * Copyright (c) 2014 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup barber
+ * @{
+ */
+/** @file
+ */
+
+#include <unistd.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <stdio.h>
+#include <malloc.h>
+#include <task.h>
+#include <loc.h>
+#include <stats.h>
+#include <fibril_synch.h>
+#include <io/pixel.h>
+#include <device/led_dev.h>
+#include <window.h>
+#include <canvas.h>
+#include <surface.h>
+#include <codec/tga.gz.h>
+#include "images.h"
+
+#define NAME  "barber"
+
+#define FRAMES  30
+
+#define MIN_FPS  1
+#define MAX_FPS  25
+
+#define MIN_LOAD  (LOAD_UNIT / 4)
+#define MAX_LOAD  (LOAD_UNIT / 3)
+
+#define FRAME_WIDTH   59
+#define FRAME_HEIGHT  192
+
+#define LED_PERIOD  1000000
+#define LED_COLORS  7
+
+typedef struct {
+	link_t link;
+	service_id_t svc_id;
+	async_sess_t *sess;
+} led_dev_t;
+
+static char *winreg = NULL;
+
+static fibril_timer_t *led_timer = NULL;
+static list_t led_devs;
+static unsigned int led_color = 0;
+
+static pixel_t led_colors[LED_COLORS] = {
+	PIXEL(0xff, 0xff, 0x00, 0x00),
+	PIXEL(0xff, 0x00, 0xff, 0x00),
+	PIXEL(0xff, 0x00, 0x00, 0xff),
+	PIXEL(0xff, 0xff, 0xff, 0x00),
+	PIXEL(0xff, 0xff, 0x00, 0xff),
+	PIXEL(0xff, 0x00, 0xff, 0xff),
+	PIXEL(0xff, 0xff, 0xff, 0xff)
+};
+
+static fibril_timer_t *frame_timer = NULL;
+static canvas_t *frame_canvas;
+static surface_t *frames[FRAMES];
+
+static unsigned int frame = 0;
+static unsigned int fps = MIN_FPS;
+
+static void led_timer_callback(void *);
+static void frame_timer_callback(void *);
+
+static bool decode_frames(void)
+{
+	frames[0] = decode_tga_gz((void *) frame01_tga_gz, frame01_tga_gz_size, 0);
+	frames[1] = decode_tga_gz((void *) frame02_tga_gz, frame02_tga_gz_size, 0);
+	frames[2] = decode_tga_gz((void *) frame03_tga_gz, frame03_tga_gz_size, 0);
+	frames[3] = decode_tga_gz((void *) frame04_tga_gz, frame04_tga_gz_size, 0);
+	frames[4] = decode_tga_gz((void *) frame05_tga_gz, frame05_tga_gz_size, 0);
+	frames[5] = decode_tga_gz((void *) frame06_tga_gz, frame06_tga_gz_size, 0);
+	frames[6] = decode_tga_gz((void *) frame07_tga_gz, frame07_tga_gz_size, 0);
+	frames[7] = decode_tga_gz((void *) frame08_tga_gz, frame08_tga_gz_size, 0);
+	frames[8] = decode_tga_gz((void *) frame09_tga_gz, frame09_tga_gz_size, 0);
+	frames[9] = decode_tga_gz((void *) frame10_tga_gz, frame10_tga_gz_size, 0);
+	frames[10] = decode_tga_gz((void *) frame11_tga_gz, frame11_tga_gz_size, 0);
+	frames[11] = decode_tga_gz((void *) frame12_tga_gz, frame12_tga_gz_size, 0);
+	frames[12] = decode_tga_gz((void *) frame13_tga_gz, frame13_tga_gz_size, 0);
+	frames[13] = decode_tga_gz((void *) frame14_tga_gz, frame14_tga_gz_size, 0);
+	frames[14] = decode_tga_gz((void *) frame15_tga_gz, frame15_tga_gz_size, 0);
+	frames[15] = decode_tga_gz((void *) frame16_tga_gz, frame16_tga_gz_size, 0);
+	frames[16] = decode_tga_gz((void *) frame17_tga_gz, frame17_tga_gz_size, 0);
+	frames[17] = decode_tga_gz((void *) frame18_tga_gz, frame18_tga_gz_size, 0);
+	frames[18] = decode_tga_gz((void *) frame19_tga_gz, frame19_tga_gz_size, 0);
+	frames[19] = decode_tga_gz((void *) frame20_tga_gz, frame20_tga_gz_size, 0);
+	frames[20] = decode_tga_gz((void *) frame21_tga_gz, frame21_tga_gz_size, 0);
+	frames[21] = decode_tga_gz((void *) frame22_tga_gz, frame22_tga_gz_size, 0);
+	frames[22] = decode_tga_gz((void *) frame23_tga_gz, frame23_tga_gz_size, 0);
+	frames[23] = decode_tga_gz((void *) frame24_tga_gz, frame24_tga_gz_size, 0);
+	frames[24] = decode_tga_gz((void *) frame25_tga_gz, frame25_tga_gz_size, 0);
+	frames[25] = decode_tga_gz((void *) frame26_tga_gz, frame26_tga_gz_size, 0);
+	frames[26] = decode_tga_gz((void *) frame27_tga_gz, frame27_tga_gz_size, 0);
+	frames[27] = decode_tga_gz((void *) frame28_tga_gz, frame28_tga_gz_size, 0);
+	frames[28] = decode_tga_gz((void *) frame29_tga_gz, frame29_tga_gz_size, 0);
+	frames[29] = decode_tga_gz((void *) frame30_tga_gz, frame30_tga_gz_size, 0);
+	
+	for (unsigned int frame = 0; frame < FRAMES; frame++) {
+		if (frames[frame] == NULL) {
+			printf("Unable to decode frame %u.\n", frame);
+			return false;
+		}
+	}
+	
+	return true;
+}
+
+static void plan_led_timer(void)
+{
+	fibril_timer_set(led_timer, LED_PERIOD, led_timer_callback, NULL);
+}
+
+static load_t get_load(void)
+{
+	size_t count;
+	load_t *load = stats_get_load(&count);
+	load_t load_val;
+	
+	if ((load != NULL) && (count > 0)) {
+		load_val = load[0];
+		free(load);
+	} else
+		load_val = 0;
+	
+	return load_val;
+}
+
+static void plan_frame_timer(suseconds_t render_time)
+{
+	/*
+	 * Crank up the FPS unless we lack
+	 * behind with the rendering and
+	 * unless the load is not above
+	 * a lower threshold.
+	 */
+	
+	suseconds_t delta = 1000000 / fps;
+	load_t load = get_load();
+	
+	if ((delta >= render_time) && (load < MIN_LOAD))
+		fps++;
+	
+	if (fps > MAX_FPS)
+		fps = MAX_FPS;
+	
+	/*
+	 * If we lack behind then immediately
+	 * go to the lowest FPS.
+	 */
+	
+	if (delta < render_time)
+		fps = MIN_FPS;
+	
+	/*
+	 * Crank down the FPS if the current
+	 * load is above an upper threshold.
+	 */
+	
+	if (load > MAX_LOAD)
+		fps--;
+	
+	if (fps < MIN_FPS)
+		fps = MIN_FPS;
+	
+	delta = 1000000 / fps;
+	
+	fibril_timer_set(frame_timer, delta, frame_timer_callback, NULL);
+}
+
+static void led_timer_callback(void *data)
+{
+	pixel_t next_led_color = led_colors[led_color];
+	
+	led_color++;
+	if (led_color >= LED_COLORS)
+		led_color = 0;
+	
+	list_foreach(led_devs, link, led_dev_t, dev) {
+		if (dev->sess)
+			led_dev_color_set(dev->sess, next_led_color);
+	}
+	
+	plan_led_timer();
+}
+
+static void frame_timer_callback(void *data)
+{
+	struct timeval prev;
+	getuptime(&prev);
+	
+	frame++;
+	if (frame >= FRAMES)
+		frame = 0;
+	
+	update_canvas(frame_canvas, frames[frame]);
+	
+	struct timeval cur;
+	getuptime(&cur);
+	
+	plan_frame_timer(tv_sub(&cur, &prev));
+}
+
+static void loc_callback(void)
+{
+	category_id_t led_cat;
+	int rc = loc_category_get_id("led", &led_cat, IPC_FLAG_BLOCKING);
+	if (rc != EOK)
+		return;
+	
+	service_id_t *svcs;
+	size_t count;
+	rc = loc_category_get_svcs(led_cat, &svcs, &count);
+	if (rc != EOK)
+		return;
+	
+	for (size_t i = 0; i < count; i++) {
+		bool known = false;
+		
+		/* Determine whether we already know this device. */
+		list_foreach(led_devs, link, led_dev_t, dev) {
+			if (dev->svc_id == svcs[i]) {
+				known = true;
+				break;
+			}
+		}
+		
+		if (!known) {
+			led_dev_t *dev = (led_dev_t *) calloc(1, sizeof(led_dev_t));
+			if (!dev)
+				continue;
+			
+			link_initialize(&dev->link);
+			dev->svc_id = svcs[i];
+			dev->sess = loc_service_connect(EXCHANGE_SERIALIZE, svcs[i], 0);
+			
+			list_append(&dev->link, &led_devs);
+		}
+	}
+	
+	// FIXME: Handle LED device removal
+	
+	free(svcs);
+}
+
+int main(int argc, char *argv[])
+{
+	if (argc < 2) {
+		printf("Compositor server not specified.\n");
+		return 1;
+	}
+	
+	list_initialize(&led_devs);
+	int rc = loc_register_cat_change_cb(loc_callback);
+	if (rc != EOK) {
+		printf("Unable to register callback for device discovery.\n");
+		return 1;
+	}
+	
+	led_timer = fibril_timer_create(NULL);
+	if (!led_timer) {
+		printf("Unable to create LED timer.\n");
+		return 1;
+	}
+	
+	frame_timer = fibril_timer_create(NULL);
+	if (!frame_timer) {
+		printf("Unable to create frame timer.\n");
+		return 1;
+	}
+	
+	if (!decode_frames())
+		return 1;
+	
+	winreg = argv[1];
+	window_t *main_window = window_open(argv[1], true, true, "barber");
+	if (!main_window) {
+		printf("Cannot open main window.\n");
+		return 1;
+	}
+	
+	frame_canvas = create_canvas(window_root(main_window),
+	    FRAME_WIDTH, FRAME_HEIGHT, frames[frame]);
+	
+	if (!frame_canvas) {
+		window_close(main_window);
+		printf("Cannot create widgets.\n");
+		return 1;
+	}
+	
+	window_resize(main_window, 0, 0, FRAME_WIDTH + 8, FRAME_HEIGHT + 28,
+	    WINDOW_PLACEMENT_RIGHT | WINDOW_PLACEMENT_BOTTOM);
+	window_exec(main_window);
+	
+	plan_led_timer();
+	plan_frame_timer(0);
+	
+	task_retval(0);
+	async_manager();
+	
+	return 0;
+}
+
+/** @}
+ */
Index: uspace/app/bnchmark/bnchmark.c
===================================================================
--- uspace/app/bnchmark/bnchmark.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/bnchmark/bnchmark.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -62,23 +62,14 @@
 {
 	struct timeval start_time;
-	int rc;
-	rc = gettimeofday(&start_time, NULL);
-	if (rc != EOK) {
-		fprintf(stderr, "gettimeofday failed\n");
-		return rc;
-	}
-	
-	rc = fn(data);
+	gettimeofday(&start_time, NULL);
+	
+	int rc = fn(data);
 	if (rc != EOK) {
 		fprintf(stderr, "measured function failed\n");
 		return rc;
 	}
-
+	
 	struct timeval final_time;
-	rc = gettimeofday(&final_time, NULL);
-	if (rc != EOK) {
-		fprintf(stderr, "gettimeofday failed\n");
-		return rc;
-	}
+	gettimeofday(&final_time, NULL);
 	
 	/* Calculate time difference in milliseconds */
@@ -92,8 +83,7 @@
 	char *path = (char *) data;
 	char *buf = malloc(BUFSIZE);
-
-	if (buf == NULL) {
+	
+	if (buf == NULL)
 		return ENOMEM;
-	}
 	
 	FILE *file = fopen(path, "r");
Index: uspace/app/init/init.c
===================================================================
--- uspace/app/init/init.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/init/init.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -355,4 +355,5 @@
 	int rc = compositor(HID_INPUT, HID_COMPOSITOR_SERVER);
 	if (rc == EOK) {
+		gui_start("/app/barber", HID_COMPOSITOR_SERVER);
 		gui_start("/app/vlaunch", HID_COMPOSITOR_SERVER);
 		gui_start("/app/vterm", HID_COMPOSITOR_SERVER);
Index: uspace/app/modplay/modplay.c
===================================================================
--- uspace/app/modplay/modplay.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/modplay/modplay.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -40,5 +40,4 @@
 #include <stdio.h>
 #include <stdlib.h>
-#include <protracker.h>
 #include <trackmod.h>
 
@@ -88,5 +87,5 @@
 	con = console_init(stdin, stdout);
 
-	rc = trackmod_protracker_load(argv[1], &mod);
+	rc = trackmod_module_load(argv[1], &mod);
 	if (rc != EOK) {
 		printf("Error loading %s.\n", argv[1]);
Index: uspace/app/nettest1/nettest1.c
===================================================================
--- uspace/app/nettest1/nettest1.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/nettest1/nettest1.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -402,9 +402,5 @@
 	
 	struct timeval time_before;
-	rc = gettimeofday(&time_before, NULL);
-	if (rc != EOK) {
-		fprintf(stderr, "Get time of day error %d\n", rc);
-		return rc;
-	}
+	gettimeofday(&time_before, NULL);
 	
 	nettest1_test(socket_ids,       1,        1);
@@ -414,9 +410,5 @@
 	
 	struct timeval time_after;
-	rc = gettimeofday(&time_after, NULL);
-	if (rc != EOK) {
-		fprintf(stderr, "Get time of day error %d\n", rc);
-		return rc;
-	}
+	gettimeofday(&time_after, NULL);
 	
 	printf("Tested in %ld microseconds\n", tv_sub(&time_after,
Index: uspace/app/nettest2/nettest2.c
===================================================================
--- uspace/app/nettest2/nettest2.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/nettest2/nettest2.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -356,9 +356,5 @@
 	
 	struct timeval time_before;
-	rc = gettimeofday(&time_before, NULL);
-	if (rc != EOK) {
-		fprintf(stderr, "Get time of day error %d\n", rc);
-		return rc;
-	}
+	gettimeofday(&time_before, NULL);
 	
 	rc = sockets_sendto_recvfrom(verbose, socket_ids, sockets, address,
@@ -368,9 +364,5 @@
 	
 	struct timeval time_after;
-	rc = gettimeofday(&time_after, NULL);
-	if (rc != EOK) {
-		fprintf(stderr, "Get time of day error %d\n", rc);
-		return rc;
-	}
+	gettimeofday(&time_after, NULL);
 	
 	if (verbose)
@@ -380,9 +372,5 @@
 	    tv_sub(&time_after, &time_before));
 	
-	rc = gettimeofday(&time_before, NULL);
-	if (rc != EOK) {
-		fprintf(stderr, "Get time of day error %d\n", rc);
-		return rc;
-	}
+	gettimeofday(&time_before, NULL);
 	
 	rc = sockets_sendto(verbose, socket_ids, sockets, address, addrlen,
@@ -396,9 +384,5 @@
 		return rc;
 	
-	rc = gettimeofday(&time_after, NULL);
-	if (rc != EOK) {
-		fprintf(stderr, "Get time of day error %d\n", rc);
-		return rc;
-	}
+	gettimeofday(&time_after, NULL);
 	
 	if (verbose)
Index: uspace/app/stats/stats.c
===================================================================
--- uspace/app/stats/stats.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/stats/stats.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -191,9 +191,10 @@
 static void print_uptime(void)
 {
-	sysarg_t uptime = stats_get_uptime();
-	printf("%s: Up %" PRIun " days, %" PRIun " hours, "
-	    "%" PRIun " minutes, %" PRIun " seconds\n", NAME,
-	    uptime / DAY, (uptime % DAY) / HOUR,
-	    (uptime % HOUR) / MINUTE, uptime % MINUTE);
+	struct timeval uptime;
+	getuptime(&uptime);
+	
+	printf("%s: Up %ld days, %ld hours, %ld minutes, %ld seconds\n",
+	    NAME, uptime.tv_sec / DAY, (uptime.tv_sec % DAY) / HOUR,
+	    (uptime.tv_sec % HOUR) / MINUTE, uptime.tv_sec % MINUTE);
 }
 
Index: uspace/app/tester/ipc/ping_pong.c
===================================================================
--- uspace/app/tester/ipc/ping_pong.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/tester/ipc/ping_pong.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -43,16 +43,10 @@
 	
 	struct timeval start;
-	if (gettimeofday(&start, NULL) != 0) {
-		TPRINTF("\n");
-		return "Failed getting the time";
-	}
+	gettimeofday(&start, NULL);
 	
 	uint64_t count = 0;
 	while (true) {
 		struct timeval now;
-		if (gettimeofday(&now, NULL) != 0) {
-			TPRINTF("\n");
-			return "Failed getting the time";
-		}
+		gettimeofday(&now, NULL);
 		
 		if (tv_sub(&now, &start) >= DURATION_SECS * 1000000L)
Index: uspace/app/tester/ipc/starve.c
===================================================================
--- uspace/app/tester/ipc/starve.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/tester/ipc/starve.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -40,13 +40,9 @@
 	const char *err = NULL;
 	console_ctrl_t *console = console_init(stdin, stdout);
-	if (console == NULL) {
+	if (console == NULL)
 		return "Failed to init connection with console.";
-	}
 	
 	struct timeval start;
-	if (gettimeofday(&start, NULL) != 0) {
-		err = "Failed getting the time";
-		goto leave;
-	}
+	gettimeofday(&start, NULL);
 	
 	TPRINTF("Intensive computation shall be imagined (for %ds)...\n", DURATION_SECS);
@@ -54,8 +50,5 @@
 	while (true) {
 		struct timeval now;
-		if (gettimeofday(&now, NULL) != 0) {
-			err = "Failed getting the time";
-			goto leave;
-		}
+		gettimeofday(&now, NULL);
 		
 		if (tv_sub(&now, &start) >= DURATION_SECS * 1000000L)
@@ -70,15 +63,14 @@
 		}
 	}
-
+	
 	// FIXME - unless a key was pressed, the answer leaked as no one
 	// will wait for it.
 	// We cannot use async_forget() directly, though. Something like
 	// console_forget_pending_kbd_event() shall come here.
-
+	
 	TPRINTF("Terminating...\n");
-
-leave:
+	
 	console_done(console);
-
+	
 	return err;
 }
Index: uspace/app/testread/testread.c
===================================================================
--- uspace/app/testread/testread.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/testread/testread.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -123,12 +123,5 @@
 	struct timeval prev_time;
 	struct timeval start_time;
-	int rc;
-	rc = gettimeofday(&start_time, NULL);
-	if (rc != EOK) {
-		printf("gettimeofday failed\n");
-		fclose(file);
-		free(buf);
-		return 1;
-	}
+	gettimeofday(&start_time, NULL);
 	prev_time = start_time;
 	
@@ -155,11 +148,6 @@
 		if (progress && offset >= next_mark) {
 			struct timeval cur_time;
-			rc = gettimeofday(&cur_time, NULL);
-			if (rc != EOK) {
-				printf("gettimeofday failed\n");
-				fclose(file);
-				free(buf);
-				return 1;
-			}
+			gettimeofday(&cur_time, NULL);
+			
 			uint32_t last_run = cur_time.tv_sec - prev_time.tv_sec;
 			uint32_t total_time = cur_time.tv_sec - start_time.tv_sec;
@@ -178,11 +166,5 @@
 	
 	struct timeval final_time;
-	rc = gettimeofday(&final_time, NULL);
-	if (rc != EOK) {
-		printf("gettimeofday failed\n");
-		fclose(file);
-		free(buf);
-		return 1;
-	}
+	gettimeofday(&final_time, NULL);
 	
 	uint32_t total_run_time = final_time.tv_sec - start_time.tv_sec;
Index: uspace/app/top/top.c
===================================================================
--- uspace/app/top/top.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/top/top.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -156,6 +156,5 @@
 	/* Get current time */
 	struct timeval time;
-	if (gettimeofday(&time, NULL) != EOK)
-		return "Cannot get time of day";
+	gettimeofday(&time, NULL);
 	
 	target->hours = (time.tv_sec % DAY) / HOUR;
@@ -164,9 +163,11 @@
 	
 	/* Get uptime */
-	sysarg_t uptime = stats_get_uptime();
-	target->udays = uptime / DAY;
-	target->uhours = (uptime % DAY) / HOUR;
-	target->uminutes = (uptime % HOUR) / MINUTE;
-	target->useconds = uptime % MINUTE;
+	struct timeval uptime;
+	getuptime(&uptime);
+	
+	target->udays = uptime.tv_sec / DAY;
+	target->uhours = (uptime.tv_sec % DAY) / HOUR;
+	target->uminutes = (uptime.tv_sec % HOUR) / MINUTE;
+	target->useconds = uptime.tv_sec % MINUTE;
 	
 	/* Get load */
Index: uspace/app/vlaunch/vlaunch.c
===================================================================
--- uspace/app/vlaunch/vlaunch.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/app/vlaunch/vlaunch.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -37,12 +37,6 @@
 #include <stdio.h>
 #include <malloc.h>
-#include <io/pixel.h>
 #include <task.h>
-#include <str.h>
 #include <str_error.h>
-#include <loc.h>
-#include <fibril_synch.h>
-#include <io/pixel.h>
-#include <device/led_dev.h>
 
 #include <window.h>
@@ -64,28 +58,5 @@
 #define LOGO_HEIGHT  66
 
-#define PERIOD  1000000
-#define COLORS  7
-
 static char *winreg = NULL;
-static fibril_timer_t *timer = NULL;
-static list_t led_devs;
-
-static pixel_t colors[COLORS] = {
-	PIXEL(0xff, 0xff, 0x00, 0x00),
-	PIXEL(0xff, 0x00, 0xff, 0x00),
-	PIXEL(0xff, 0x00, 0x00, 0xff),
-	PIXEL(0xff, 0xff, 0xff, 0x00),
-	PIXEL(0xff, 0xff, 0x00, 0xff),
-	PIXEL(0xff, 0x00, 0xff, 0xff),
-	PIXEL(0xff, 0xff, 0xff, 0xff)
-};
-
-static unsigned int color = 0;
-
-typedef struct {
-	link_t link;
-	service_id_t svc_id;
-	async_sess_t *sess;
-} led_dev_t;
 
 static int app_launch(const char *app)
@@ -129,79 +100,8 @@
 }
 
-static void timer_callback(void *data)
-{
-	pixel_t next_color = colors[color];
-	
-	color++;
-	if (color >= COLORS)
-		color = 0;
-	
-	list_foreach(led_devs, link, led_dev_t, dev) {
-		if (dev->sess)
-			led_dev_color_set(dev->sess, next_color);
-	}
-	
-	fibril_timer_set(timer, PERIOD, timer_callback, NULL);
-}
-
-static void loc_callback(void)
-{
-	category_id_t led_cat;
-	int rc = loc_category_get_id("led", &led_cat, IPC_FLAG_BLOCKING);
-	if (rc != EOK)
-		return;
-	
-	service_id_t *svcs;
-	size_t count;
-	rc = loc_category_get_svcs(led_cat, &svcs, &count);
-	if (rc != EOK)
-		return;
-	
-	for (size_t i = 0; i < count; i++) {
-		bool known = false;
-		
-		/* Determine whether we already know this device. */
-		list_foreach(led_devs, link, led_dev_t, dev) {
-			if (dev->svc_id == svcs[i]) {
-				known = true;
-				break;
-			}
-		}
-		
-		if (!known) {
-			led_dev_t *dev = (led_dev_t *) calloc(1, sizeof(led_dev_t));
-			if (!dev)
-				continue;
-			
-			link_initialize(&dev->link);
-			dev->svc_id = svcs[i];
-			dev->sess = loc_service_connect(EXCHANGE_SERIALIZE, svcs[i], 0);
-			
-			list_append(&dev->link, &led_devs);
-		}
-	}
-	
-	// FIXME: Handle LED device removal
-	
-	free(svcs);
-}
-
 int main(int argc, char *argv[])
 {
 	if (argc < 2) {
 		printf("Compositor server not specified.\n");
-		return 1;
-	}
-	
-	list_initialize(&led_devs);
-	int rc = loc_register_cat_change_cb(loc_callback);
-	if (rc != EOK) {
-		printf("Unable to register callback for device discovery.\n");
-		return 1;
-	}
-	
-	timer = fibril_timer_create(NULL);
-	if (!timer) {
-		printf("Unable to create timer.\n");
 		return 1;
 	}
@@ -262,6 +162,4 @@
 	window_exec(main_window);
 	
-	fibril_timer_set(timer, PERIOD, timer_callback, NULL);
-	
 	task_retval(0);
 	async_manager();
Index: uspace/dist/src/c/demos/tetris/shapes.c
===================================================================
--- uspace/dist/src/c/demos/tetris/shapes.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/dist/src/c/demos/tetris/shapes.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -69,23 +69,23 @@
 
 const struct shape shapes[] = {
-	/*  0 */  {  7,  7, { TL, TC, MR }, 0xff042d},
-	/*  1 */  {  8,  8, { TC, TR, ML }, 0xff9304},
-	/*  2 */  {  9, 11, { ML, MR, BC }, 0xbeff04},
-	/*  3 */  {  3,  3, { TL, TC, ML }, 0x63ff04},
-	/*  4 */  { 12, 14, { ML, BL, MR }, 0xce04ff},
-	/*  5 */  { 15, 17, { ML, BR, MR }, 0xff04cf},
-	/*  6 */  { 18, 18, { ML, MR, 2  }, 0x7604ff},  /* sticks out */
-	/*  7 */  {  0,  0, { TC, ML, BL }, 0xff042d},
-	/*  8 */  {  1,  1, { TC, MR, BR }, 0xff9304},
-	/*  9 */  { 10,  2, { TC, MR, BC }, 0xbeff04},
-	/* 10 */  { 11,  9, { TC, ML, MR }, 0xbeff04},
-	/* 11 */  {  2, 10, { TC, ML, BC }, 0xbeff04},
-	/* 12 */  { 13,  4, { TC, BC, BR }, 0xce04ff},
-	/* 13 */  { 14, 12, { TR, ML, MR }, 0xce04ff},
-	/* 14 */  {  4, 13, { TL, TC, BC }, 0xce04ff},
-	/* 15 */  { 16,  5, { TR, TC, BC }, 0xff04cf},
-	/* 16 */  { 17, 15, { TL, MR, ML }, 0xff04cf},
-	/* 17 */  {  5, 16, { TC, BC, BL }, 0xff04cf},
-	/* 18 */  {  6,  6, { TC, BC, 2 * B_COLS }, 0x7604ff}  /* sticks out */
+	/*  0 */  {  7,  7, { TL, TC, MR }, 0x00aaaa},
+	/*  1 */  {  8,  8, { TC, TR, ML }, 0x00aa00},
+	/*  2 */  {  9, 11, { ML, MR, BC }, 0xaa5500},
+	/*  3 */  {  3,  3, { TL, TC, ML }, 0x0000aa},
+	/*  4 */  { 12, 14, { ML, BL, MR }, 0xaa00aa},
+	/*  5 */  { 15, 17, { ML, BR, MR }, 0xffa500},
+	/*  6 */  { 18, 18, { ML, MR, 2  }, 0xaa0000},  /* sticks out */
+	/*  7 */  {  0,  0, { TC, ML, BL }, 0x00aaaa},
+	/*  8 */  {  1,  1, { TC, MR, BR }, 0x00aa00},
+	/*  9 */  { 10,  2, { TC, MR, BC }, 0xaa5500},
+	/* 10 */  { 11,  9, { TC, ML, MR }, 0xaa5500},
+	/* 11 */  {  2, 10, { TC, ML, BC }, 0xaa5500},
+	/* 12 */  { 13,  4, { TC, BC, BR }, 0xaa00aa},
+	/* 13 */  { 14, 12, { TR, ML, MR }, 0xaa00aa},
+	/* 14 */  {  4, 13, { TL, TC, BC }, 0xaa00aa},
+	/* 15 */  { 16,  5, { TR, TC, BC }, 0xffa500},
+	/* 16 */  { 17, 15, { TL, MR, ML }, 0xffa500},
+	/* 17 */  {  5, 16, { TC, BC, BL }, 0xffa500},
+	/* 18 */  {  6,  6, { TC, BC, 2 * B_COLS }, 0xaa0000}  /* sticks out */
 };
 
Index: uspace/dist/src/c/demos/top/screen.c
===================================================================
--- uspace/dist/src/c/demos/top/screen.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/dist/src/c/demos/top/screen.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -37,4 +37,5 @@
 
 #include <stdio.h>
+#include <stdlib.h>
 #include <io/console.h>
 #include <io/style.h>
@@ -43,4 +44,5 @@
 #include <stats.h>
 #include <inttypes.h>
+#include <macros.h>
 #include "screen.h"
 #include "top.h"
@@ -48,10 +50,13 @@
 #define USEC_COUNT  1000000
 
-static sysarg_t warn_col = 0;
-static sysarg_t warn_row = 0;
 static suseconds_t timeleft = 0;
 
 console_ctrl_t *console;
 
+static sysarg_t warning_col = 0;
+static sysarg_t warning_row = 0;
+static suseconds_t warning_timeleft = 0;
+static char *warning_text = NULL;
+
 static void screen_style_normal(void)
 {
@@ -64,4 +69,10 @@
 	console_flush(console);
 	console_set_style(console, STYLE_INVERTED);
+}
+
+static void screen_style_emphasis(void)
+{
+	console_flush(console);
+	console_set_style(console, STYLE_EMPHASIS);
 }
 
@@ -126,4 +137,7 @@
 void screen_done(void)
 {
+	free(warning_text);
+	warning_text = NULL;
+
 	screen_restart(true);
 	
@@ -277,18 +291,51 @@
 }
 
-static inline void print_tasks_head(void)
+static inline void print_help_head(void)
 {
 	screen_style_inverted();
-	printf("[taskid] [thrds] [resident] [%%resi] [virtual] [%%virt]"
-	    " [%%user] [%%kern] [name");
+	printf("Help");
 	screen_newline();
 	screen_style_normal();
 }
 
-static inline void print_tasks(data_t *data)
-{
-	sysarg_t cols;
-	sysarg_t rows;
-	screen_get_size(&cols, &rows);
+static inline void print_help(void)
+{
+	sysarg_t cols;
+	sysarg_t rows;
+	screen_get_size(&cols, &rows);
+	
+	screen_newline();
+	
+	printf("Operation modes:");
+	screen_newline();
+	
+	printf(" t .. tasks statistics");
+	screen_newline();
+	
+	printf(" i .. IPC statistics");
+	screen_newline();
+	
+	printf(" e .. exceptions statistics");
+	screen_newline();
+	
+	printf("      a .. toggle display of all/hot exceptions");
+	screen_newline();
+
+	printf(" h .. toggle this help screen");
+	screen_newline();
+
+	screen_newline();
+
+	printf("Other keys:");
+	screen_newline();
+	
+	printf(" s .. choose column to sort by");
+	screen_newline();
+	
+	printf(" r .. toggle reversed sorting");
+	screen_newline();
+	
+	printf(" q .. quit");
+	screen_newline();
 	
 	sysarg_t col;
@@ -296,32 +343,4 @@
 	screen_get_pos(&col, &row);
 	
-	size_t i;
-	for (i = 0; (i < data->tasks_count) && (row < rows); i++, row++) {
-		stats_task_t *task = data->tasks + data->tasks_map[i];
-		perc_task_t *perc = data->tasks_perc + data->tasks_map[i];
-		
-		uint64_t resmem;
-		const char *resmem_suffix;
-		bin_order_suffix(task->resmem, &resmem, &resmem_suffix, true);
-		
-		uint64_t virtmem;
-		const char *virtmem_suffix;
-		bin_order_suffix(task->virtmem, &virtmem, &virtmem_suffix, true);
-		
-		printf("%-8" PRIu64 " %7zu %7" PRIu64 "%s ",
-		    task->task_id, task->threads, resmem, resmem_suffix);
-		print_percent(perc->resmem, 2);
-		printf(" %6" PRIu64 "%s ", virtmem, virtmem_suffix);
-		print_percent(perc->virtmem, 2);
-		puts(" ");
-		print_percent(perc->ucycles, 2);
-		puts(" ");
-		print_percent(perc->kcycles, 2);
-		puts(" ");
-		print_string(task->name);
-		
-		screen_newline();
-	}
-	
 	while (row < rows) {
 		screen_newline();
@@ -330,14 +349,30 @@
 }
 
-static inline void print_ipc_head(void)
-{
+static inline void print_table_head(const table_t *table)
+{
+	sysarg_t cols;
+	sysarg_t rows;
+	screen_get_size(&cols, &rows);
+
 	screen_style_inverted();
-	printf("[taskid] [cls snt] [cls rcv] [ans snt]"
-	    " [ans rcv] [irq rcv] [forward] [name");
+	for (size_t i = 0; i < table->num_columns; i++) {
+		const char *name = table->columns[i].name;
+		int width = table->columns[i].width;
+		if (i != 0) {
+			puts(" ");
+		}
+		if (width == 0) {
+			sysarg_t col;
+			sysarg_t row;
+			screen_get_pos(&col, &row);
+			width = cols - col - 1;
+		}
+		printf("[%-*.*s]", width - 2, width - 2, name);
+	}
 	screen_newline();
 	screen_style_normal();
 }
 
-static inline void print_ipc(data_t *data)
+static inline void print_table(const table_t *table)
 {
 	sysarg_t cols;
@@ -350,44 +385,58 @@
 	
 	size_t i;
-	for (i = 0; (i < data->tasks_count) && (row < rows); i++, row++) {
-		uint64_t call_sent;
-		uint64_t call_received;
-		uint64_t answer_sent;
-		uint64_t answer_received;
-		uint64_t irq_notif_received;
-		uint64_t forwarded;
-		
-		char call_sent_suffix;
-		char call_received_suffix;
-		char answer_sent_suffix;
-		char answer_received_suffix;
-		char irq_notif_received_suffix;
-		char forwarded_suffix;
-		
-		order_suffix(data->tasks[i].ipc_info.call_sent, &call_sent,
-		    &call_sent_suffix);
-		order_suffix(data->tasks[i].ipc_info.call_received,
-		    &call_received, &call_received_suffix);
-		order_suffix(data->tasks[i].ipc_info.answer_sent,
-		    &answer_sent, &answer_sent_suffix);
-		order_suffix(data->tasks[i].ipc_info.answer_received,
-		    &answer_received, &answer_received_suffix);
-		order_suffix(data->tasks[i].ipc_info.irq_notif_received,
-		    &irq_notif_received, &irq_notif_received_suffix);
-		order_suffix(data->tasks[i].ipc_info.forwarded, &forwarded,
-		    &forwarded_suffix);
-		
-		printf("%-8" PRIu64 " %8" PRIu64 "%c %8" PRIu64 "%c"
-		     " %8" PRIu64 "%c %8" PRIu64 "%c %8" PRIu64 "%c"
-		     " %8" PRIu64 "%c ", data->tasks[i].task_id,
-		     call_sent, call_sent_suffix,
-		     call_received, call_received_suffix,
-		     answer_sent, answer_sent_suffix,
-		     answer_received, answer_received_suffix,
-		     irq_notif_received, irq_notif_received_suffix,
-		     forwarded, forwarded_suffix);
-		print_string(data->tasks[i].name);
-		
-		screen_newline();
+	for (i = 0; (i < table->num_fields) && (row < rows); i++) {
+		size_t column_index = i % table->num_columns;
+		int width = table->columns[column_index].width;
+		field_t *field = &table->fields[i];
+
+		if (column_index != 0) {
+			puts(" ");
+		}
+
+		if (width == 0) {
+			screen_get_pos(&col, &row);
+			width = cols - col - 1;
+		}
+
+		switch (field->type) {
+		case FIELD_EMPTY:
+			printf("%*s", width, "");
+			break;
+		case FIELD_UINT:
+			printf("%*" PRIu64, width, field->uint);
+			break;
+		case FIELD_UINT_SUFFIX_BIN: {
+			uint64_t val = field->uint;
+			const char *suffix;
+			width -= 3;
+			bin_order_suffix(val, &val, &suffix, true);
+			printf("%*" PRIu64 "%s", width, val, suffix);
+			break;
+		}
+		case FIELD_UINT_SUFFIX_DEC: {
+			uint64_t val = field->uint;
+			char suffix;
+			width -= 1;
+			order_suffix(val, &val, &suffix);
+			printf("%*" PRIu64 "%c", width, val, suffix);
+			break;
+		}
+		case FIELD_PERCENT:
+			width -= 5; /* nnn.% */
+			if (width > 2) {
+				printf("%*s", width - 2, "");
+				width = 2;
+			}
+			print_percent(field->fixed, width);
+			break;
+		case FIELD_STRING:
+			printf("%-*.*s", width, width, field->string);
+			break;
+		}
+
+		if (column_index == table->num_columns - 1) {
+			screen_newline();
+			row++;
+		}
 	}
 	
@@ -398,13 +447,5 @@
 }
 
-static inline void print_excs_head(void)
-{
-	screen_style_inverted();
-	printf("[exc   ] [count   ] [%%count] [cycles  ] [%%cycles] [description");
-	screen_newline();
-	screen_style_normal();
-}
-
-static inline void print_excs(data_t *data)
+static inline void print_sort(table_t *table)
 {
 	sysarg_t cols;
@@ -415,28 +456,8 @@
 	sysarg_t row;
 	screen_get_pos(&col, &row);
-	
-	size_t i;
-	for (i = 0; (i < data->exceptions_count) && (row < rows); i++) {
-		/* Filter-out cold exceptions if not instructed otherwise */
-		if ((!excs_all) && (!data->exceptions[i].hot))
-			continue;
-		
-		uint64_t count;
-		uint64_t cycles;
-		
-		char count_suffix;
-		char cycles_suffix;
-		
-		order_suffix(data->exceptions[i].count, &count, &count_suffix);
-		order_suffix(data->exceptions[i].cycles, &cycles, &cycles_suffix);
-		
-		printf("%-8u %9" PRIu64 "%c  ",
-		     data->exceptions[i].id, count, count_suffix);
-		print_percent(data->exceptions_perc[i].count, 2);
-		printf(" %9" PRIu64 "%c   ", cycles, cycles_suffix);
-		print_percent(data->exceptions_perc[i].cycles, 2);
-		puts(" ");
-		print_string(data->exceptions[i].desc);
-		
+
+	size_t num = min(table->num_columns, rows - row);
+	for (size_t i = 0; i < num; i++) {
+		printf("%c - %s", table->columns[i].key, table->columns[i].name);
 		screen_newline();
 		row++;
@@ -449,37 +470,16 @@
 }
 
-static void print_help(void)
-{
-	sysarg_t cols;
-	sysarg_t rows;
-	screen_get_size(&cols, &rows);
-	
-	sysarg_t col;
-	sysarg_t row;
-	screen_get_pos(&col, &row);
-	
-	screen_newline();
-	
-	printf("Operation modes:");
-	screen_newline();
-	
-	printf(" t .. tasks statistics");
-	screen_newline();
-	
-	printf(" i .. IPC statistics");
-	screen_newline();
-	
-	printf(" e .. exceptions statistics");
-	screen_newline();
-	
-	printf("      a .. toggle display of all/hot exceptions");
-	screen_newline();
-	
-	row += 6;
-	
-	while (row < rows) {
-		screen_newline();
-		row++;
-	}
+static inline void print_warning(void)
+{
+	screen_get_pos(&warning_col, &warning_row);
+	if (warning_timeleft > 0) {
+		screen_style_emphasis();
+		print_string(warning_text);
+		screen_style_normal();
+	} else {
+		free(warning_text);
+		warning_text = NULL;
+	}
+	screen_newline();
 }
 
@@ -492,24 +492,16 @@
 	print_cpu_info(data);
 	print_physmem_info(data);
-	
-	/* Empty row for warnings */
-	screen_get_pos(&warn_col, &warn_row);
-	screen_newline();
-	
-	switch (op_mode) {
-	case OP_TASKS:
-		print_tasks_head();
-		print_tasks(data);
+	print_warning();
+	
+	switch (screen_mode) {
+	case SCREEN_TABLE:
+		print_table_head(&data->table);
+		print_table(&data->table);
 		break;
-	case OP_IPC:
-		print_ipc_head();
-		print_ipc(data);
+	case SCREEN_SORT:
+		print_sort(&data->table);
 		break;
-	case OP_EXCS:
-		print_excs_head();
-		print_excs(data);
-		break;
-	case OP_HELP:
-		print_tasks_head();
+	case SCREEN_HELP:
+		print_help_head();
 		print_help();
 	}
@@ -518,14 +510,25 @@
 }
 
-void print_warning(const char *fmt, ...)
-{
-	screen_moveto(warn_col, warn_row);
-	
+void show_warning(const char *fmt, ...)
+{
+	sysarg_t cols;
+	sysarg_t rows;
+	screen_get_size(&cols, &rows);
+
+	size_t warning_text_size = 1 + cols * sizeof(*warning_text);
+	free(warning_text);
+	warning_text = malloc(warning_text_size);
+	if (!warning_text)
+		return;
+
 	va_list args;
 	va_start(args, fmt);
-	vprintf(fmt, args);
+	vsnprintf(warning_text, warning_text_size, fmt, args);
 	va_end(args);
 	
-	screen_newline();
+	warning_timeleft = 2 * USEC_COUNT;
+
+	screen_moveto(warning_col, warning_row);
+	print_warning();
 	console_flush(console);
 }
@@ -555,8 +558,10 @@
 		cons_event_t event;
 		
+		warning_timeleft -= timeleft;
 		if (!console_get_event_timeout(console, &event, &timeleft)) {
 			timeleft = 0;
 			return -1;
 		}
+		warning_timeleft += timeleft;
 		
 		if (event.type == CEV_KEY && event.ev.key.type == KEY_PRESS)
Index: uspace/dist/src/c/demos/top/screen.h
===================================================================
--- uspace/dist/src/c/demos/top/screen.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/dist/src/c/demos/top/screen.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -44,5 +44,5 @@
 extern void screen_done(void);
 extern void print_data(data_t *);
-extern void print_warning(const char *, ...)
+extern void show_warning(const char *, ...)
     PRINTF_ATTRIBUTE(1, 2);
 
Index: uspace/dist/src/c/demos/top/top.c
===================================================================
--- uspace/dist/src/c/demos/top/top.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/dist/src/c/demos/top/top.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -55,7 +55,80 @@
 #define MINUTE  60
 
-op_mode_t op_mode = OP_TASKS;
-sort_mode_t sort_mode = SORT_TASK_CYCLES;
-bool excs_all = false;
+typedef enum {
+	OP_TASKS,
+	OP_IPC,
+	OP_EXCS,
+} op_mode_t;
+
+static const column_t task_columns[] = {
+	{"taskid",   't',  8},
+	{"thrds",    'h',  7},
+	{"resident", 'r', 10},
+	{"%resi",    'R',  7},
+	{"virtual",  'v',  9},
+	{"%virt",    'V',  7},
+	{"%user",    'U',  7},
+	{"%kern",    'K',  7},
+	{"name",     'd',  0},
+};
+
+enum {
+	TASK_COL_ID = 0,
+	TASK_COL_NUM_THREADS,
+	TASK_COL_RESIDENT,
+	TASK_COL_PERCENT_RESIDENT,
+	TASK_COL_VIRTUAL,
+	TASK_COL_PERCENT_VIRTUAL,
+	TASK_COL_PERCENT_USER,
+	TASK_COL_PERCENT_KERNEL,
+	TASK_COL_NAME,
+	TASK_NUM_COLUMNS,
+};
+
+static const column_t ipc_columns[] = {
+	{"taskid",  't', 8},
+	{"cls snt", 'c', 9},
+	{"cls rcv", 'C', 9},
+	{"ans snt", 'a', 9},
+	{"ans rcv", 'A', 9},
+	{"forward", 'f', 9},
+	{"name",    'd', 0},
+};
+
+enum {
+	IPC_COL_TASKID = 0,
+	IPC_COL_CLS_SNT,
+	IPC_COL_CLS_RCV,
+	IPC_COL_ANS_SNT,
+	IPC_COL_ANS_RCV,
+	IPC_COL_FORWARD,
+	IPC_COL_NAME,
+	IPC_NUM_COLUMNS,
+};
+
+static const column_t exception_columns[] = {
+	{"exc",         'e',  8},
+	{"count",       'n', 10},
+	{"%count",      'N',  8},
+	{"cycles",      'c', 10},
+	{"%cycles",     'C',  9},
+	{"description", 'd',  0},
+};
+
+enum {
+	EXCEPTION_COL_ID = 0,
+	EXCEPTION_COL_COUNT,
+	EXCEPTION_COL_PERCENT_COUNT,
+	EXCEPTION_COL_CYCLES,
+	EXCEPTION_COL_PERCENT_CYCLES,
+	EXCEPTION_COL_DESCRIPTION,
+	EXCEPTION_NUM_COLUMNS,
+};
+
+screen_mode_t screen_mode = SCREEN_TABLE;
+static op_mode_t op_mode = OP_TASKS;
+static size_t sort_column = TASK_COL_PERCENT_USER;
+static int sort_reverse = -1;
+static bool excs_all = false;
 
 static const char *read_data(data_t *target)
@@ -67,5 +140,4 @@
 	target->tasks = NULL;
 	target->tasks_perc = NULL;
-	target->tasks_map = NULL;
 	target->threads = NULL;
 	target->exceptions = NULL;
@@ -76,9 +148,13 @@
 	target->ecycles_diff = NULL;
 	target->ecount_diff = NULL;
+	target->table.name = NULL;
+	target->table.num_columns = 0;
+	target->table.columns = NULL;
+	target->table.num_fields = 0;
+	target->table.fields = NULL;
 	
 	/* Get current time */
 	struct timeval time;
-	if (gettimeofday(&time, NULL) != EOK)
-		return "Cannot get time of day";
+	gettimeofday(&time, NULL);
 	
 	target->hours = (time.tv_sec % DAY) / HOUR;
@@ -87,9 +163,11 @@
 	
 	/* Get uptime */
-	sysarg_t uptime = stats_get_uptime();
-	target->udays = uptime / DAY;
-	target->uhours = (uptime % DAY) / HOUR;
-	target->uminutes = (uptime % HOUR) / MINUTE;
-	target->useconds = uptime % MINUTE;
+	struct timeval uptime;
+	getuptime(&uptime);
+	
+	target->udays = uptime.tv_sec / DAY;
+	target->uhours = (uptime.tv_sec % DAY) / HOUR;
+	target->uminutes = (uptime.tv_sec % HOUR) / MINUTE;
+	target->useconds = uptime.tv_sec % MINUTE;
 	
 	/* Get load */
@@ -117,9 +195,4 @@
 	if (target->tasks_perc == NULL)
 		return "Not enough memory for task utilization";
-	
-	target->tasks_map =
-	    (size_t *) calloc(target->tasks_count, sizeof(size_t));
-	if (target->tasks_map == NULL)
-		return "Not enough memory for task map";
 	
 	/* Get threads */
@@ -289,29 +362,172 @@
 static int cmp_data(void *a, void *b, void *arg)
 {
-	size_t ia = *((size_t *) a);
-	size_t ib = *((size_t *) b);
-	data_t *data = (data_t *) arg;
-	
-	uint64_t acycles = data->ucycles_diff[ia] + data->kcycles_diff[ia];
-	uint64_t bcycles = data->ucycles_diff[ib] + data->kcycles_diff[ib];
-	
-	if (acycles > bcycles)
-		return -1;
-	
-	if (acycles < bcycles)
-		return 1;
-	
+	field_t *fa = (field_t *)a + sort_column;
+	field_t *fb = (field_t *)b + sort_column;
+	
+	if (fa->type > fb->type)
+		return 1 * sort_reverse;
+
+	if (fa->type < fb->type)
+		return -1 * sort_reverse;
+
+	switch (fa->type) {
+	case FIELD_EMPTY:
+		return 0;
+	case FIELD_UINT_SUFFIX_BIN: /* fallthrough */
+	case FIELD_UINT_SUFFIX_DEC: /* fallthrough */
+	case FIELD_UINT:
+		if (fa->uint > fb->uint)
+			return 1 * sort_reverse;
+		if (fa->uint < fb->uint)
+			return -1 * sort_reverse;
+		return 0;
+	case FIELD_PERCENT:
+		if (fa->fixed.upper * fb->fixed.lower
+		    > fb->fixed.upper * fa->fixed.lower)
+			return 1 * sort_reverse;
+		if (fa->fixed.upper * fb->fixed.lower
+		    < fb->fixed.upper * fa->fixed.lower)
+			return -1 * sort_reverse;
+		return 0;
+	case FIELD_STRING:
+		return str_cmp(fa->string, fb->string) * sort_reverse;
+	}
+
 	return 0;
 }
 
-static void sort_data(data_t *data)
-{
-	size_t i;
-	
-	for (i = 0; i < data->tasks_count; i++)
-		data->tasks_map[i] = i;
-	
-	qsort((void *) data->tasks_map, data->tasks_count,
-	    sizeof(size_t), cmp_data, (void *) data);
+static void sort_table(table_t *table)
+{
+	if (sort_column >= table->num_columns)
+		sort_column = 0;
+	/* stable sort is probably best, so we use gsort */
+	gsort((void *) table->fields, table->num_fields / table->num_columns,
+	    sizeof(field_t) * table->num_columns, cmp_data, NULL);
+}
+
+static const char *fill_task_table(data_t *data)
+{
+	data->table.name = "Tasks";
+	data->table.num_columns = TASK_NUM_COLUMNS;
+	data->table.columns = task_columns;
+	data->table.num_fields = data->tasks_count * TASK_NUM_COLUMNS;
+	data->table.fields = calloc(data->table.num_fields,
+	    sizeof(field_t));
+	if (data->table.fields == NULL)
+		return "Not enough memory for table fields";
+
+	field_t *field = data->table.fields;
+	for (size_t i = 0; i < data->tasks_count; i++) {
+		stats_task_t *task = &data->tasks[i];
+		perc_task_t *perc = &data->tasks_perc[i];
+		field[TASK_COL_ID].type = FIELD_UINT;
+		field[TASK_COL_ID].uint = task->task_id;
+		field[TASK_COL_NUM_THREADS].type = FIELD_UINT;
+		field[TASK_COL_NUM_THREADS].uint = task->threads;
+		field[TASK_COL_RESIDENT].type = FIELD_UINT_SUFFIX_BIN;
+		field[TASK_COL_RESIDENT].uint = task->resmem;
+		field[TASK_COL_PERCENT_RESIDENT].type = FIELD_PERCENT;
+		field[TASK_COL_PERCENT_RESIDENT].fixed = perc->resmem;
+		field[TASK_COL_VIRTUAL].type = FIELD_UINT_SUFFIX_BIN;
+		field[TASK_COL_VIRTUAL].uint = task->virtmem;
+		field[TASK_COL_PERCENT_VIRTUAL].type = FIELD_PERCENT;
+		field[TASK_COL_PERCENT_VIRTUAL].fixed = perc->virtmem;
+		field[TASK_COL_PERCENT_USER].type = FIELD_PERCENT;
+		field[TASK_COL_PERCENT_USER].fixed = perc->ucycles;
+		field[TASK_COL_PERCENT_KERNEL].type = FIELD_PERCENT;
+		field[TASK_COL_PERCENT_KERNEL].fixed = perc->kcycles;
+		field[TASK_COL_NAME].type = FIELD_STRING;
+		field[TASK_COL_NAME].string = task->name;
+		field += TASK_NUM_COLUMNS;
+	}
+
+	return NULL;
+}
+
+static const char *fill_ipc_table(data_t *data)
+{
+	data->table.name = "IPC";
+	data->table.num_columns = IPC_NUM_COLUMNS;
+	data->table.columns = ipc_columns;
+	data->table.num_fields = data->tasks_count * IPC_NUM_COLUMNS;
+	data->table.fields = calloc(data->table.num_fields,
+	    sizeof(field_t));
+	if (data->table.fields == NULL)
+		return "Not enough memory for table fields";
+
+	field_t *field = data->table.fields;
+	for (size_t i = 0; i < data->tasks_count; i++) {
+		field[IPC_COL_TASKID].type = FIELD_UINT;
+		field[IPC_COL_TASKID].uint = data->tasks[i].task_id;
+		field[IPC_COL_CLS_SNT].type = FIELD_UINT_SUFFIX_DEC;
+		field[IPC_COL_CLS_SNT].uint = data->tasks[i].ipc_info.call_sent;
+		field[IPC_COL_CLS_RCV].type = FIELD_UINT_SUFFIX_DEC;
+		field[IPC_COL_CLS_RCV].uint = data->tasks[i].ipc_info.call_received;
+		field[IPC_COL_ANS_SNT].type = FIELD_UINT_SUFFIX_DEC;
+		field[IPC_COL_ANS_SNT].uint = data->tasks[i].ipc_info.answer_sent;
+		field[IPC_COL_ANS_RCV].type = FIELD_UINT_SUFFIX_DEC;
+		field[IPC_COL_ANS_RCV].uint = data->tasks[i].ipc_info.answer_received;
+		field[IPC_COL_FORWARD].type = FIELD_UINT_SUFFIX_DEC;
+		field[IPC_COL_FORWARD].uint = data->tasks[i].ipc_info.forwarded;
+		field[IPC_COL_NAME].type = FIELD_STRING;
+		field[IPC_COL_NAME].string = data->tasks[i].name;
+		field += IPC_NUM_COLUMNS;
+	}
+
+	return NULL;
+}
+
+static const char *fill_exception_table(data_t *data)
+{
+	data->table.name = "Exceptions";
+	data->table.num_columns = EXCEPTION_NUM_COLUMNS;
+	data->table.columns = exception_columns;
+	data->table.num_fields = data->exceptions_count *
+	    EXCEPTION_NUM_COLUMNS;
+	data->table.fields = calloc(data->table.num_fields, sizeof(field_t));
+	if (data->table.fields == NULL)
+		return "Not enough memory for table fields";
+
+	field_t *field = data->table.fields;
+	for (size_t i = 0; i < data->exceptions_count; i++) {
+		if (!excs_all && !data->exceptions[i].hot)
+			continue;
+		field[EXCEPTION_COL_ID].type = FIELD_UINT;
+		field[EXCEPTION_COL_ID].uint = data->exceptions[i].id;
+		field[EXCEPTION_COL_COUNT].type = FIELD_UINT_SUFFIX_DEC;
+		field[EXCEPTION_COL_COUNT].uint = data->exceptions[i].count;
+		field[EXCEPTION_COL_PERCENT_COUNT].type = FIELD_PERCENT;
+		field[EXCEPTION_COL_PERCENT_COUNT].fixed = data->exceptions_perc[i].count;
+		field[EXCEPTION_COL_CYCLES].type = FIELD_UINT_SUFFIX_DEC;
+		field[EXCEPTION_COL_CYCLES].uint = data->exceptions[i].cycles;
+		field[EXCEPTION_COL_PERCENT_CYCLES].type = FIELD_PERCENT;
+		field[EXCEPTION_COL_PERCENT_CYCLES].fixed = data->exceptions_perc[i].cycles;
+		field[EXCEPTION_COL_DESCRIPTION].type = FIELD_STRING;
+		field[EXCEPTION_COL_DESCRIPTION].string = data->exceptions[i].desc;
+		field += EXCEPTION_NUM_COLUMNS;
+	}
+
+	/* in case any cold exceptions were ignored */
+	data->table.num_fields = field - data->table.fields;
+
+	return NULL;
+}
+
+static const char *fill_table(data_t *data)
+{
+	if (data->table.fields != NULL) {
+		free(data->table.fields);
+		data->table.fields = NULL;
+	}
+
+	switch (op_mode) {
+	case OP_TASKS:
+		return fill_task_table(data);
+	case OP_IPC:
+		return fill_ipc_table(data);
+	case OP_EXCS:
+		return fill_exception_table(data);
+	}
+	return NULL;
 }
 
@@ -356,4 +572,7 @@
 	if (target->ecount_diff != NULL)
 		free(target->ecount_diff);
+
+	if (target->table.fields != NULL)
+		free(target->table.fields);
 }
 
@@ -367,65 +586,94 @@
 	printf("Reading initial data...\n");
 	
-	if ((ret = read_data(&data_prev)) != NULL)
+	if ((ret = read_data(&data)) != NULL)
 		goto out;
 	
 	/* Compute some rubbish to have initialised values */
-	compute_percentages(&data_prev, &data_prev);
+	compute_percentages(&data, &data);
 	
 	/* And paint screen until death */
 	while (true) {
 		int c = tgetchar(UPDATE_INTERVAL);
-		if (c < 0) {
+
+		if (c < 0) { /* timeout */
+			data_prev = data;
 			if ((ret = read_data(&data)) != NULL) {
-				free_data(&data);
+				free_data(&data_prev);
 				goto out;
 			}
 			
 			compute_percentages(&data_prev, &data);
-			sort_data(&data);
-			print_data(&data);
 			free_data(&data_prev);
-			data_prev = data;
-			
-			continue;
-		}
-		
+
+			c = -1;
+		}
+
+		if (screen_mode == SCREEN_HELP && c >= 0) {
+			if (c == 'h' || c == '?')
+				c = -1;
+			/* go back to table and handle the key */
+			screen_mode = SCREEN_TABLE;
+		}
+
+		if (screen_mode == SCREEN_SORT && c >= 0) {
+			for (size_t i = 0; i < data.table.num_columns; i++) {
+				if (data.table.columns[i].key == c) {
+					sort_column = i;
+					screen_mode = SCREEN_TABLE;
+				}
+			}
+
+			c = -1;
+		}
+
 		switch (c) {
-			case 't':
-				print_warning("Showing task statistics");
-				op_mode = OP_TASKS;
+		case -1: /* do nothing */
+			break;
+		case 't':
+			op_mode = OP_TASKS;
+			break;
+		case 'i':
+			op_mode = OP_IPC;
+			break;
+		case 'e':
+			op_mode = OP_EXCS;
+			break;
+		case 's':
+			screen_mode = SCREEN_SORT;
+			break;
+		case 'r':
+			sort_reverse = -sort_reverse;
+			break;
+		case 'h':
+		case '?':
+			screen_mode = SCREEN_HELP;
+			break;
+		case 'q':
+			goto out;
+		case 'a':
+			if (op_mode == OP_EXCS) {
+				excs_all = !excs_all;
+				if (excs_all)
+					show_warning("Showing all exceptions");
+				else
+					show_warning("Showing only hot exceptions");
 				break;
-			case 'i':
-				print_warning("Showing IPC statistics");
-				op_mode = OP_IPC;
-				break;
-			case 'e':
-				print_warning("Showing exception statistics");
-				op_mode = OP_EXCS;
-				break;
-			case 'h':
-				print_warning("Showing help");
-				op_mode = OP_HELP;
-				break;
-			case 'q':
-				goto out;
-			case 'a':
-				if (op_mode == OP_EXCS) {
-					excs_all = !excs_all;
-					if (excs_all)
-						print_warning("Showing all exceptions");
-					else
-						print_warning("Showing only hot exceptions");
-					break;
-				}
-			default:
-				print_warning("Unknown command \"%c\", use \"h\" for help", c);
-				break;
-		}
+			}
+			/* fallthrough */
+		default:
+			show_warning("Unknown command \"%c\", use \"h\" for help", c);
+			continue; /* don't redraw */
+		}
+
+		if ((ret = fill_table(&data)) != NULL) {
+			goto out;
+		}
+		sort_table(&data.table);
+		print_data(&data);
 	}
 	
 out:
 	screen_done();
-	free_data(&data_prev);
+	free_data(&data);
 	
 	if (ret != NULL) {
Index: uspace/dist/src/c/demos/top/top.h
===================================================================
--- uspace/dist/src/c/demos/top/top.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/dist/src/c/demos/top/top.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -51,17 +51,10 @@
 
 typedef enum {
-	OP_TASKS,
-	OP_IPC,
-	OP_EXCS,
-	OP_HELP
-} op_mode_t;
+	SCREEN_TABLE,
+	SCREEN_SORT,
+	SCREEN_HELP,
+} screen_mode_t;
 
-typedef enum {
-	SORT_TASK_CYCLES
-} sort_mode_t;
-
-extern op_mode_t op_mode;
-extern sort_mode_t sort_mode;
-extern bool excs_all;
+extern screen_mode_t screen_mode;
 
 typedef struct {
@@ -87,4 +80,32 @@
 } perc_exc_t;
 
+typedef enum {
+	FIELD_EMPTY, FIELD_UINT, FIELD_UINT_SUFFIX_BIN, FIELD_UINT_SUFFIX_DEC,
+	FIELD_PERCENT, FIELD_STRING
+} field_type_t;
+
+typedef struct {
+	field_type_t type;
+	union {
+		fixed_float fixed;
+		uint64_t uint;
+		const char *string;
+	};
+} field_t;
+
+typedef struct {
+	const char *name;
+	char key;
+	int width;
+} column_t;
+
+typedef struct {
+	const char *name;
+	size_t num_columns;
+	const column_t *columns;
+	size_t num_fields;
+	field_t *fields;
+} table_t;
+
 typedef struct {
 	time_t hours;
@@ -107,5 +128,4 @@
 	stats_task_t *tasks;
 	perc_task_t *tasks_perc;
-	size_t *tasks_map;
 	
 	size_t threads_count;
@@ -122,4 +142,6 @@
 	uint64_t *ecycles_diff;
 	uint64_t *ecount_diff;
+
+	table_t table;
 } data_t;
 
Index: uspace/lib/c/generic/stats.c
===================================================================
--- uspace/lib/c/generic/stats.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/c/generic/stats.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -291,18 +291,4 @@
 }
 
-/** Get system uptime
- *
- * @return System uptime (in seconds).
- *
- */
-sysarg_t stats_get_uptime(void)
-{
-	sysarg_t uptime;
-	if (sysinfo_get_value("system.uptime", &uptime) != EOK)
-		uptime = 0;
-	
-	return uptime;
-}
-
 /** Print load fixed-point value
  *
@@ -316,16 +302,13 @@
 void stats_print_load_fragment(load_t upper, unsigned int dec_length)
 {
-	/* Magic value from BSD */
-	load_t lower = 65536;
-	
 	/* Print the whole part */
-	printf("%u.", upper / lower);
-	
-	load_t rest = (upper % lower) * 10;
+	printf("%u.", upper / LOAD_UNIT);
+	
+	load_t rest = (upper % LOAD_UNIT) * 10;
 	
 	unsigned int i;
 	for (i = 0; i < dec_length; i++) {
-		printf("%u", rest / lower);
-		rest = (rest % lower) * 10;
+		printf("%u", rest / LOAD_UNIT);
+		rest = (rest % LOAD_UNIT) * 10;
 	}
 }
Index: uspace/lib/c/generic/time.c
===================================================================
--- uspace/lib/c/generic/time.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/c/generic/time.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -54,5 +54,12 @@
 #include <malloc.h>
 
-#define ASCTIME_BUF_LEN 26
+#define ASCTIME_BUF_LEN  26
+
+#define HOURS_PER_DAY  24
+#define MINS_PER_HOUR  60
+#define SECS_PER_MIN   60
+#define MINS_PER_DAY   (MINS_PER_HOUR * HOURS_PER_DAY)
+#define SECS_PER_HOUR  (SECS_PER_MIN * MINS_PER_HOUR)
+#define SECS_PER_DAY   (SECS_PER_HOUR * HOURS_PER_DAY)
 
 /** Pointer to kernel shared variables with time */
@@ -63,113 +70,126 @@
 } *ktime = NULL;
 
-/* Helper functions ***********************************************************/
-
-#define HOURS_PER_DAY (24)
-#define MINS_PER_HOUR (60)
-#define SECS_PER_MIN (60)
-#define MINS_PER_DAY (MINS_PER_HOUR * HOURS_PER_DAY)
-#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR)
-#define SECS_PER_DAY (SECS_PER_HOUR * HOURS_PER_DAY)
-
-/**
- * Checks whether the year is a leap year.
+static async_sess_t *clock_conn = NULL;
+
+/** Check whether the year is a leap year.
  *
  * @param year Year since 1900 (e.g. for 1970, the value is 70).
+ *
  * @return true if year is a leap year, false otherwise
- */
-static bool _is_leap_year(time_t year)
+ *
+ */
+static bool is_leap_year(time_t year)
 {
 	year += 1900;
-
+	
 	if (year % 400 == 0)
 		return true;
+	
 	if (year % 100 == 0)
 		return false;
+	
 	if (year % 4 == 0)
 		return true;
+	
 	return false;
 }
 
-/**
- * Returns how many days there are in the given month of the given year.
+/** How many days there are in the given month
+ *
+ * Return how many days there are in the given month of the given year.
  * Note that year is only taken into account if month is February.
  *
  * @param year Year since 1900 (can be negative).
- * @param mon Month of the year. 0 for January, 11 for December.
+ * @param mon  Month of the year. 0 for January, 11 for December.
+ *
  * @return Number of days in the specified month.
- */
-static int _days_in_month(time_t year, time_t mon)
-{
-	assert(mon >= 0 && mon <= 11);
-
-	static int month_days[] =
-		{ 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
-
+ *
+ */
+static int days_in_month(time_t year, time_t mon)
+{
+	assert(mon >= 0);
+	assert(mon <= 11);
+	
+	static int month_days[] = {
+		31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
+	};
+	
 	if (mon == 1) {
+		/* February */
 		year += 1900;
-		/* february */
-		return _is_leap_year(year) ? 29 : 28;
-	} else {
-		return month_days[mon];
-	}
-}
-
-/**
- * For specified year, month and day of month, returns which day of that year
+		return is_leap_year(year) ? 29 : 28;
+	}
+	
+	return month_days[mon];
+}
+
+/** Which day of that year it is.
+ *
+ * For specified year, month and day of month, return which day of that year
  * it is.
  *
  * For example, given date 2011-01-03, the corresponding expression is:
- *     _day_of_year(111, 0, 3) == 2
+ * day_of_year(111, 0, 3) == 2
  *
  * @param year Year (year 1900 = 0, can be negative).
- * @param mon Month (January = 0).
+ * @param mon  Month (January = 0).
  * @param mday Day of month (First day is 1).
+ *
  * @return Day of year (First day is 0).
- */
-static int _day_of_year(time_t year, time_t mon, time_t mday)
-{
-	static int mdays[] =
-	    { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
-	static int leap_mdays[] =
-	    { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
-
-	return (_is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
-}
-
-/**
- * Integer division that rounds to negative infinity.
- * Used by some functions in this file.
+ *
+ */
+static int day_of_year(time_t year, time_t mon, time_t mday)
+{
+	static int mdays[] = {
+		0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
+	};
+	
+	static int leap_mdays[] = {
+		0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
+	};
+	
+	return (is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
+}
+
+/** Integer division that rounds to negative infinity.
+ *
+ * Used by some functions in this module.
  *
  * @param op1 Dividend.
  * @param op2 Divisor.
+ *
  * @return Rounded quotient.
- */
-static time_t _floor_div(time_t op1, time_t op2)
-{
-	if (op1 >= 0 || op1 % op2 == 0) {
+ *
+ */
+static time_t floor_div(time_t op1, time_t op2)
+{
+	if ((op1 >= 0) || (op1 % op2 == 0))
 		return op1 / op2;
-	} else {
-		return op1 / op2 - 1;
-	}
-}
-
-/**
- * Modulo that rounds to negative infinity.
- * Used by some functions in this file.
+	
+	return op1 / op2 - 1;
+}
+
+/** Modulo that rounds to negative infinity.
+ *
+ * Used by some functions in this module.
  *
  * @param op1 Dividend.
  * @param op2 Divisor.
+ *
  * @return Remainder.
- */
-static time_t _floor_mod(time_t op1, time_t op2)
-{
-	int div = _floor_div(op1, op2);
-
-	/* (a / b) * b + a % b == a */
-	/* thus, a % b == a - (a / b) * b */
-
-	int result = op1 - div * op2;
-	
-	/* Some paranoid checking to ensure I didn't make a mistake here. */
+ *
+ */
+static time_t floor_mod(time_t op1, time_t op2)
+{
+	time_t div = floor_div(op1, op2);
+	
+	/*
+	 * (a / b) * b + a % b == a
+	 * Thus: a % b == a - (a / b) * b
+	 */
+	
+	time_t result = op1 - div * op2;
+	
+	/* Some paranoid checking to ensure there is mistake here. */
 	assert(result >= 0);
 	assert(result < op2);
@@ -179,59 +199,67 @@
 }
 
-/**
- * Number of days since the Epoch.
+/** Number of days since the Epoch.
+ *
  * Epoch is 1970-01-01, which is also equal to day 0.
  *
  * @param year Year (year 1900 = 0, may be negative).
- * @param mon Month (January = 0).
+ * @param mon  Month (January = 0).
  * @param mday Day of month (first day = 1).
+ *
  * @return Number of days since the Epoch.
- */
-static time_t _days_since_epoch(time_t year, time_t mon, time_t mday)
-{
-	return (year - 70) * 365 + _floor_div(year - 69, 4) -
-	    _floor_div(year - 1, 100) + _floor_div(year + 299, 400) +
-	    _day_of_year(year, mon, mday);
-}
-
-/**
- * Seconds since the Epoch. see also _days_since_epoch().
- * 
+ *
+ */
+static time_t days_since_epoch(time_t year, time_t mon, time_t mday)
+{
+	return (year - 70) * 365 + floor_div(year - 69, 4) -
+	    floor_div(year - 1, 100) + floor_div(year + 299, 400) +
+	    day_of_year(year, mon, mday);
+}
+
+/** Seconds since the Epoch.
+ *
+ * See also days_since_epoch().
+ *
  * @param tm Normalized broken-down time.
+ *
  * @return Number of seconds since the epoch, not counting leap seconds.
- */
-static time_t _secs_since_epoch(const struct tm *tm)
-{
-	return _days_since_epoch(tm->tm_year, tm->tm_mon, tm->tm_mday) *
+ *
+ */
+static time_t secs_since_epoch(const struct tm *tm)
+{
+	return days_since_epoch(tm->tm_year, tm->tm_mon, tm->tm_mday) *
 	    SECS_PER_DAY + tm->tm_hour * SECS_PER_HOUR +
 	    tm->tm_min * SECS_PER_MIN + tm->tm_sec;
 }
 
-/**
- * Which day of week the specified date is.
- * 
+/** Which day of week the specified date is.
+ *
  * @param year Year (year 1900 = 0).
- * @param mon Month (January = 0).
+ * @param mon  Month (January = 0).
  * @param mday Day of month (first = 1).
+ *
  * @return Day of week (Sunday = 0).
- */
-static int _day_of_week(time_t year, time_t mon, time_t mday)
+ *
+ */
+static time_t day_of_week(time_t year, time_t mon, time_t mday)
 {
 	/* 1970-01-01 is Thursday */
-	return _floor_mod((_days_since_epoch(year, mon, mday) + 4), 7);
-}
-
-/**
- * Normalizes the broken-down time and optionally adds specified amount of
- * seconds.
- * 
- * @param tm Broken-down time to normalize.
+	return floor_mod(days_since_epoch(year, mon, mday) + 4, 7);
+}
+
+/** Normalize the broken-down time.
+ *
+ * Optionally add specified amount of seconds.
+ *
+ * @param tm      Broken-down time to normalize.
  * @param sec_add Seconds to add.
+ *
  * @return 0 on success, -1 on overflow
- */
-static int _normalize_time(struct tm *tm, time_t sec_add)
+ *
+ */
+static int normalize_time(struct tm *tm, time_t sec_add)
 {
 	// TODO: DST correction
-
+	
 	/* Set initial values. */
 	time_t sec = tm->tm_sec + sec_add;
@@ -241,22 +269,22 @@
 	time_t mon = tm->tm_mon;
 	time_t year = tm->tm_year;
-
+	
 	/* Adjust time. */
-	min += _floor_div(sec, SECS_PER_MIN);
-	sec = _floor_mod(sec, SECS_PER_MIN);
-	hour += _floor_div(min, MINS_PER_HOUR);
-	min = _floor_mod(min, MINS_PER_HOUR);
-	day += _floor_div(hour, HOURS_PER_DAY);
-	hour = _floor_mod(hour, HOURS_PER_DAY);
-
+	min += floor_div(sec, SECS_PER_MIN);
+	sec = floor_mod(sec, SECS_PER_MIN);
+	hour += floor_div(min, MINS_PER_HOUR);
+	min = floor_mod(min, MINS_PER_HOUR);
+	day += floor_div(hour, HOURS_PER_DAY);
+	hour = floor_mod(hour, HOURS_PER_DAY);
+	
 	/* Adjust month. */
-	year += _floor_div(mon, 12);
-	mon = _floor_mod(mon, 12);
-
+	year += floor_div(mon, 12);
+	mon = floor_mod(mon, 12);
+	
 	/* Now the difficult part - days of month. */
 	
 	/* First, deal with whole cycles of 400 years = 146097 days. */
-	year += _floor_div(day, 146097) * 400;
-	day = _floor_mod(day, 146097);
+	year += floor_div(day, 146097) * 400;
+	day = floor_mod(day, 146097);
 	
 	/* Then, go in one year steps. */
@@ -264,5 +292,5 @@
 		/* January and February. */
 		while (day > 365) {
-			day -= _is_leap_year(year) ? 366 : 365;
+			day -= is_leap_year(year) ? 366 : 365;
 			year++;
 		}
@@ -270,5 +298,5 @@
 		/* Rest of the year. */
 		while (day > 365) {
-			day -= _is_leap_year(year + 1) ? 366 : 365;
+			day -= is_leap_year(year + 1) ? 366 : 365;
 			year++;
 		}
@@ -276,7 +304,8 @@
 	
 	/* Finally, finish it off month per month. */
-	while (day >= _days_in_month(year, mon)) {
-		day -= _days_in_month(year, mon);
+	while (day >= days_in_month(year, mon)) {
+		day -= days_in_month(year, mon);
 		mon++;
+		
 		if (mon >= 12) {
 			mon -= 12;
@@ -286,6 +315,6 @@
 	
 	/* Calculate the remaining two fields. */
-	tm->tm_yday = _day_of_year(year, mon, day + 1);
-	tm->tm_wday = _day_of_week(year, mon, day + 1);
+	tm->tm_yday = day_of_year(year, mon, day + 1);
+	tm->tm_wday = day_of_week(year, mon, day + 1);
 	
 	/* And put the values back to the struct. */
@@ -296,7 +325,7 @@
 	tm->tm_mon = (int) mon;
 	
-	/* Casts to work around libc brain-damage. */
-	if (year > ((int)INT_MAX) || year < ((int)INT_MIN)) {
-		tm->tm_year = (year < 0) ? ((int)INT_MIN) : ((int)INT_MAX);
+	/* Casts to work around POSIX brain-damage. */
+	if (year > ((int) INT_MAX) || year < ((int) INT_MIN)) {
+		tm->tm_year = (year < 0) ? ((int) INT_MIN) : ((int) INT_MAX);
 		return -1;
 	}
@@ -306,93 +335,110 @@
 }
 
-/**
- * Which day the week-based year starts on, relative to the first calendar day.
- * E.g. if the year starts on December 31st, the return value is -1.
+/** Which day the week-based year starts on.
+ *
+ * Relative to the first calendar day. E.g. if the year starts
+ * on December 31st, the return value is -1.
  *
  * @param Year since 1900.
+ *
  * @return Offset of week-based year relative to calendar year.
- */
-static int _wbyear_offset(int year)
-{
-	int start_wday = _day_of_week(year, 0, 1);
-	return _floor_mod(4 - start_wday, 7) - 3;
-}
-
-/**
- * Returns week-based year of the specified time.
+ *
+ */
+static int wbyear_offset(int year)
+{
+	int start_wday = day_of_week(year, 0, 1);
+	
+	return floor_mod(4 - start_wday, 7) - 3;
+}
+
+/** Week-based year of the specified time.
  *
  * @param tm Normalized broken-down time.
+ *
  * @return Week-based year.
- */
-static int _wbyear(const struct tm *tm)
-{
-	int day = tm->tm_yday - _wbyear_offset(tm->tm_year);
+ *
+ */
+static int wbyear(const struct tm *tm)
+{
+	int day = tm->tm_yday - wbyear_offset(tm->tm_year);
+	
 	if (day < 0) {
 		/* Last week of previous year. */
 		return tm->tm_year - 1;
 	}
-	if (day > 364 + _is_leap_year(tm->tm_year)) {
+	
+	if (day > 364 + is_leap_year(tm->tm_year)) {
 		/* First week of next year. */
 		return tm->tm_year + 1;
 	}
+	
 	/* All the other days are in the calendar year. */
 	return tm->tm_year;
 }
 
-/**
- * Week number of the year, assuming weeks start on sunday.
+/** Week number of the year (assuming weeks start on Sunday).
+ *
  * The first Sunday of January is the first day of week 1;
  * days in the new year before this are in week 0.
  *
  * @param tm Normalized broken-down time.
+ *
  * @return The week number (0 - 53).
- */
-static int _sun_week_number(const struct tm *tm)
-{
-	int first_day = (7 - _day_of_week(tm->tm_year, 0, 1)) % 7;
+ *
+ */
+static int sun_week_number(const struct tm *tm)
+{
+	int first_day = (7 - day_of_week(tm->tm_year, 0, 1)) % 7;
+	
 	return (tm->tm_yday - first_day + 7) / 7;
 }
 
-/**
- * Week number of the year, assuming weeks start on monday.
- * If the week containing January 1st has four or more days in the new year,
- * then it is considered week 1. Otherwise, it is the last week of the previous
- * year, and the next week is week 1. Both January 4th and the first Thursday
+/** Week number of the year (assuming weeks start on Monday).
+ *
+ * If the week containing January 1st has four or more days
+ * in the new year, then it is considered week 1. Otherwise,
+ * it is the last week of the previous year, and the next week
+ * is week 1. Both January 4th and the first Thursday
  * of January are always in week 1.
  *
  * @param tm Normalized broken-down time.
+ *
  * @return The week number (1 - 53).
- */
-static int _iso_week_number(const struct tm *tm)
-{
-	int day = tm->tm_yday - _wbyear_offset(tm->tm_year);
+ *
+ */
+static int iso_week_number(const struct tm *tm)
+{
+	int day = tm->tm_yday - wbyear_offset(tm->tm_year);
+	
 	if (day < 0) {
 		/* Last week of previous year. */
 		return 53;
 	}
-	if (day > 364 + _is_leap_year(tm->tm_year)) {
+	
+	if (day > 364 + is_leap_year(tm->tm_year)) {
 		/* First week of next year. */
 		return 1;
 	}
+	
 	/* All the other days give correct answer. */
 	return (day / 7 + 1);
 }
 
-/**
- * Week number of the year, assuming weeks start on monday.
+/** Week number of the year (assuming weeks start on Monday).
+ *
  * The first Monday of January is the first day of week 1;
- * days in the new year before this are in week 0. 
+ * days in the new year before this are in week 0.
  *
  * @param tm Normalized broken-down time.
+ *
  * @return The week number (0 - 53).
- */
-static int _mon_week_number(const struct tm *tm)
-{
-	int first_day = (1 - _day_of_week(tm->tm_year, 0, 1)) % 7;
+ *
+ */
+static int mon_week_number(const struct tm *tm)
+{
+	int first_day = (1 - day_of_week(tm->tm_year, 0, 1)) % 7;
+	
 	return (tm->tm_yday - first_day + 7) / 7;
 }
-
-/******************************************************************************/
-
 
 /** Add microseconds to given timeval.
@@ -468,5 +514,5 @@
 }
 
-/** Get time of day
+/** Get time of day.
  *
  * The time variables are memory mapped (read-only) from kernel which
@@ -482,68 +528,59 @@
  *
  */
-int gettimeofday(struct timeval *tv, struct timezone *tz)
-{
-	int rc;
-	struct tm t;
-	category_id_t cat_id;
-	size_t svc_cnt;
-	service_id_t *svc_ids = NULL;
-	service_id_t svc_id;
-	char *svc_name = NULL;
-
-	static async_sess_t *clock_conn = NULL;
-
+void gettimeofday(struct timeval *tv, struct timezone *tz)
+{
 	if (tz) {
 		tz->tz_minuteswest = 0;
 		tz->tz_dsttime = DST_NONE;
 	}
-
+	
 	if (clock_conn == NULL) {
-		rc = loc_category_get_id("clock", &cat_id, IPC_FLAG_BLOCKING);
+		category_id_t cat_id;
+		int rc = loc_category_get_id("clock", &cat_id, IPC_FLAG_BLOCKING);
 		if (rc != EOK)
-			goto ret_uptime;
-
+			goto fallback;
+		
+		service_id_t *svc_ids;
+		size_t svc_cnt;
 		rc = loc_category_get_svcs(cat_id, &svc_ids, &svc_cnt);
 		if (rc != EOK)
-			goto ret_uptime;
-
+			goto fallback;
+		
 		if (svc_cnt == 0)
-			goto ret_uptime;
-
+			goto fallback;
+		
+		char *svc_name;
 		rc = loc_service_get_name(svc_ids[0], &svc_name);
+		free(svc_ids);
 		if (rc != EOK)
-			goto ret_uptime;
-
+			goto fallback;
+		
+		service_id_t svc_id;
 		rc = loc_service_get_id(svc_name, &svc_id, 0);
+		free(svc_name);
 		if (rc != EOK)
-			goto ret_uptime;
-
+			goto fallback;
+		
 		clock_conn = loc_service_connect(EXCHANGE_SERIALIZE,
 		    svc_id, IPC_FLAG_BLOCKING);
 		if (!clock_conn)
-			goto ret_uptime;
-	}
-
-	rc = clock_dev_time_get(clock_conn, &t);
+			goto fallback;
+	}
+	
+	struct tm time;
+	int rc = clock_dev_time_get(clock_conn, &time);
 	if (rc != EOK)
-		goto ret_uptime;
-
+		goto fallback;
+	
 	tv->tv_usec = 0;
-	tv->tv_sec = mktime(&t);
-
-	free(svc_name);
-	free(svc_ids);
-
-	return EOK;
-
-ret_uptime:
-
-	free(svc_name);
-	free(svc_ids);
-
-	return getuptime(tv);
-}
-
-int getuptime(struct timeval *tv)
+	tv->tv_sec = mktime(&time);
+	
+	return;
+	
+fallback:
+	getuptime(tv);
+}
+
+void getuptime(struct timeval *tv)
 {
 	if (ktime == NULL) {
@@ -552,5 +589,5 @@
 		if (rc != EOK) {
 			errno = rc;
-			return -1;
+			goto fallback;
 		}
 		
@@ -561,5 +598,5 @@
 			as_area_destroy(addr);
 			errno = rc;
-			return -1;
+			goto fallback;
 		}
 		
@@ -580,6 +617,10 @@
 	} else
 		tv->tv_sec = s1;
-
-	return 0;
+	
+	return;
+	
+fallback:
+	tv->tv_sec = 0;
+	tv->tv_usec = 0;
 }
 
@@ -587,6 +628,5 @@
 {
 	struct timeval tv;
-	if (gettimeofday(&tv, NULL))
-		return (time_t) -1;
+	gettimeofday(&tv, NULL);
 	
 	if (tloc)
@@ -631,11 +671,16 @@
 }
 
-/**
- * This function first normalizes the provided broken-down time
- * (moves all values to their proper bounds) and then tries to
- * calculate the appropriate time_t representation.
+/** Get time from broken-down time.
+ *
+ * First normalize the provided broken-down time
+ * (moves all values to their proper bounds) and
+ * then try to calculate the appropriate time_t
+ * representation.
  *
  * @param tm Broken-down time.
- * @return time_t representation of the time, undefined value on overflow.
+ *
+ * @return time_t representation of the time.
+ * @return Undefined value on overflow.
+ *
  */
 time_t mktime(struct tm *tm)
@@ -643,18 +688,46 @@
 	// TODO: take DST flag into account
 	// TODO: detect overflow
-
-	_normalize_time(tm, 0);
-	return _secs_since_epoch(tm);
-}
-
-/**
- * Convert time and date to a string, based on a specified format and
- * current locale.
- * 
- * @param s Buffer to write string to.
+	
+	normalize_time(tm, 0);
+	return secs_since_epoch(tm);
+}
+
+/*
+ * FIXME: This requires POSIX-correct snprintf.
+ *        Otherwise it won't work with non-ASCII chars.
+ */
+#define APPEND(...) \
+	{ \
+		consumed = snprintf(ptr, remaining, __VA_ARGS__); \
+		if (consumed >= remaining) \
+			return 0; \
+		\
+		ptr += consumed; \
+		remaining -= consumed; \
+	}
+
+#define RECURSE(fmt) \
+	{ \
+		consumed = strftime(ptr, remaining, fmt, tm); \
+		if (consumed == 0) \
+			return 0; \
+		\
+		ptr += consumed; \
+		remaining -= consumed; \
+	}
+
+#define TO_12H(hour) \
+	(((hour) > 12) ? ((hour) - 12) : \
+	    (((hour) == 0) ? 12 : (hour)))
+
+/** Convert time and date to a string.
+ *
+ * @param s       Buffer to write string to.
  * @param maxsize Size of the buffer.
- * @param format Format of the output.
- * @param tm Broken-down time to format.
+ * @param format  Format of the output.
+ * @param tm      Broken-down time to format.
+ *
  * @return Number of bytes written.
+ *
  */
 size_t strftime(char *restrict s, size_t maxsize,
@@ -664,17 +737,21 @@
 	assert(format != NULL);
 	assert(tm != NULL);
-
+	
 	// TODO: use locale
+	
 	static const char *wday_abbr[] = {
 		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
 	};
+	
 	static const char *wday[] = {
 		"Sunday", "Monday", "Tuesday", "Wednesday",
 		"Thursday", "Friday", "Saturday"
 	};
+	
 	static const char *mon_abbr[] = {
 		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
 		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
 	};
+	
 	static const char *mon[] = {
 		"January", "February", "March", "April", "May", "June", "July",
@@ -682,7 +759,6 @@
 	};
 	
-	if (maxsize < 1) {
+	if (maxsize < 1)
 		return 0;
-	}
 	
 	char *ptr = s;
@@ -690,30 +766,7 @@
 	size_t remaining = maxsize;
 	
-	#define append(...) { \
-		/* FIXME: this requires POSIX-correct snprintf */ \
-		/*        otherwise it won't work with non-ascii chars */ \
-		consumed = snprintf(ptr, remaining, __VA_ARGS__); \
-		if (consumed >= remaining) { \
-			return 0; \
-		} \
-		ptr += consumed; \
-		remaining -= consumed; \
-	}
-	
-	#define recurse(fmt) { \
-		consumed = strftime(ptr, remaining, fmt, tm); \
-		if (consumed == 0) { \
-			return 0; \
-		} \
-		ptr += consumed; \
-		remaining -= consumed; \
-	}
-	
-	#define TO_12H(hour) (((hour) > 12) ? ((hour) - 12) : \
-	    (((hour) == 0) ? 12 : (hour)))
-	
 	while (*format != '\0') {
 		if (*format != '%') {
-			append("%c", *format);
+			APPEND("%c", *format);
 			format++;
 			continue;
@@ -721,13 +774,15 @@
 		
 		format++;
-		if (*format == '0' || *format == '+') {
+		if ((*format == '0') || (*format == '+')) {
 			// TODO: padding
 			format++;
 		}
+		
 		while (isdigit(*format)) {
 			// TODO: padding
 			format++;
 		}
-		if (*format == 'O' || *format == 'E') {
+		
+		if ((*format == 'O') || (*format == 'E')) {
 			// TODO: locale's alternative format
 			format++;
@@ -736,83 +791,120 @@
 		switch (*format) {
 		case 'a':
-			append("%s", wday_abbr[tm->tm_wday]); break;
+			APPEND("%s", wday_abbr[tm->tm_wday]);
+			break;
 		case 'A':
-			append("%s", wday[tm->tm_wday]); break;
+			APPEND("%s", wday[tm->tm_wday]);
+			break;
 		case 'b':
-			append("%s", mon_abbr[tm->tm_mon]); break;
+			APPEND("%s", mon_abbr[tm->tm_mon]);
+			break;
 		case 'B':
-			append("%s", mon[tm->tm_mon]); break;
+			APPEND("%s", mon[tm->tm_mon]);
+			break;
 		case 'c':
 			// TODO: locale-specific datetime format
-			recurse("%Y-%m-%d %H:%M:%S"); break;
+			RECURSE("%Y-%m-%d %H:%M:%S");
+			break;
 		case 'C':
-			append("%02d", (1900 + tm->tm_year) / 100); break;
+			APPEND("%02d", (1900 + tm->tm_year) / 100);
+			break;
 		case 'd':
-			append("%02d", tm->tm_mday); break;
+			APPEND("%02d", tm->tm_mday);
+			break;
 		case 'D':
-			recurse("%m/%d/%y"); break;
+			RECURSE("%m/%d/%y");
+			break;
 		case 'e':
-			append("%2d", tm->tm_mday); break;
+			APPEND("%2d", tm->tm_mday);
+			break;
 		case 'F':
-			recurse("%+4Y-%m-%d"); break;
+			RECURSE("%+4Y-%m-%d");
+			break;
 		case 'g':
-			append("%02d", _wbyear(tm) % 100); break;
+			APPEND("%02d", wbyear(tm) % 100);
+			break;
 		case 'G':
-			append("%d", _wbyear(tm)); break;
+			APPEND("%d", wbyear(tm));
+			break;
 		case 'h':
-			recurse("%b"); break;
+			RECURSE("%b");
+			break;
 		case 'H':
-			append("%02d", tm->tm_hour); break;
+			APPEND("%02d", tm->tm_hour);
+			break;
 		case 'I':
-			append("%02d", TO_12H(tm->tm_hour)); break;
+			APPEND("%02d", TO_12H(tm->tm_hour));
+			break;
 		case 'j':
-			append("%03d", tm->tm_yday); break;
+			APPEND("%03d", tm->tm_yday);
+			break;
 		case 'k':
-			append("%2d", tm->tm_hour); break;
+			APPEND("%2d", tm->tm_hour);
+			break;
 		case 'l':
-			append("%2d", TO_12H(tm->tm_hour)); break;
+			APPEND("%2d", TO_12H(tm->tm_hour));
+			break;
 		case 'm':
-			append("%02d", tm->tm_mon); break;
+			APPEND("%02d", tm->tm_mon);
+			break;
 		case 'M':
-			append("%02d", tm->tm_min); break;
+			APPEND("%02d", tm->tm_min);
+			break;
 		case 'n':
-			append("\n"); break;
+			APPEND("\n");
+			break;
 		case 'p':
-			append("%s", tm->tm_hour < 12 ? "AM" : "PM"); break;
+			APPEND("%s", tm->tm_hour < 12 ? "AM" : "PM");
+			break;
 		case 'P':
-			append("%s", tm->tm_hour < 12 ? "am" : "PM"); break;
+			APPEND("%s", tm->tm_hour < 12 ? "am" : "PM");
+			break;
 		case 'r':
-			recurse("%I:%M:%S %p"); break;
+			RECURSE("%I:%M:%S %p");
+			break;
 		case 'R':
-			recurse("%H:%M"); break;
+			RECURSE("%H:%M");
+			break;
 		case 's':
-			append("%ld", _secs_since_epoch(tm)); break;
+			APPEND("%ld", secs_since_epoch(tm));
+			break;
 		case 'S':
-			append("%02d", tm->tm_sec); break;
+			APPEND("%02d", tm->tm_sec);
+			break;
 		case 't':
-			append("\t"); break;
+			APPEND("\t");
+			break;
 		case 'T':
-			recurse("%H:%M:%S"); break;
+			RECURSE("%H:%M:%S");
+			break;
 		case 'u':
-			append("%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
+			APPEND("%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
 			break;
 		case 'U':
-			append("%02d", _sun_week_number(tm)); break;
+			APPEND("%02d", sun_week_number(tm));
+			break;
 		case 'V':
-			append("%02d", _iso_week_number(tm)); break;
+			APPEND("%02d", iso_week_number(tm));
+			break;
 		case 'w':
-			append("%d", tm->tm_wday); break;
+			APPEND("%d", tm->tm_wday);
+			break;
 		case 'W':
-			append("%02d", _mon_week_number(tm)); break;
+			APPEND("%02d", mon_week_number(tm));
+			break;
 		case 'x':
 			// TODO: locale-specific date format
-			recurse("%Y-%m-%d"); break;
+			RECURSE("%Y-%m-%d");
+			break;
 		case 'X':
 			// TODO: locale-specific time format
-			recurse("%H:%M:%S"); break;
+			RECURSE("%H:%M:%S");
+			break;
 		case 'y':
-			append("%02d", tm->tm_year % 100); break;
+			APPEND("%02d", tm->tm_year % 100);
+			break;
 		case 'Y':
-			append("%d", 1900 + tm->tm_year); break;
+			APPEND("%d", 1900 + tm->tm_year);
+			break;
 		case 'z':
 			// TODO: timezone
@@ -822,35 +914,33 @@
 			break;
 		case '%':
-			append("%%");
+			APPEND("%%");
 			break;
 		default:
 			/* Invalid specifier, print verbatim. */
-			while (*format != '%') {
+			while (*format != '%')
 				format--;
-			}
-			append("%%");
+			
+			APPEND("%%");
 			break;
 		}
+		
 		format++;
 	}
 	
-	#undef append
-	#undef recurse
-	
 	return maxsize - remaining;
 }
 
-
-/** Converts a time value to a broken-down UTC time
- *
- * @param time    Time to convert
- * @param result  Structure to store the result to
- *
- * @return        EOK or a negative error code
+/** Convert a time value to a broken-down UTC time/
+ *
+ * @param time   Time to convert
+ * @param result Structure to store the result to
+ *
+ * @return EOK or a negative error code
+ *
  */
 int time_utc2tm(const time_t time, struct tm *restrict result)
 {
 	assert(result != NULL);
-
+	
 	/* Set result to epoch. */
 	result->tm_sec = 0;
@@ -860,40 +950,41 @@
 	result->tm_mon = 0;
 	result->tm_year = 70; /* 1970 */
-
-	if (_normalize_time(result, time) == -1)
+	
+	if (normalize_time(result, time) == -1)
 		return EOVERFLOW;
-
+	
 	return EOK;
 }
 
-/** Converts a time value to a null terminated string of the form
- *  "Wed Jun 30 21:49:08 1993\n" expressed in UTC.
- *
- * @param time   Time to convert.
- * @param buf    Buffer to store the string to, must be at least
- *               ASCTIME_BUF_LEN bytes long.
- *
- * @return       EOK or a negative error code.
+/** Convert a time value to a NULL-terminated string.
+ *
+ * The format is "Wed Jun 30 21:49:08 1993\n" expressed in UTC.
+ *
+ * @param time Time to convert.
+ * @param buf  Buffer to store the string to, must be at least
+ *             ASCTIME_BUF_LEN bytes long.
+ *
+ * @return EOK or a negative error code.
+ *
  */
 int time_utc2str(const time_t time, char *restrict buf)
 {
-	struct tm t;
-	int r;
-
-	if ((r = time_utc2tm(time, &t)) != EOK)
-		return r;
-
-	time_tm2str(&t, buf);
+	struct tm tm;
+	int ret = time_utc2tm(time, &tm);
+	if (ret != EOK)
+		return ret;
+	
+	time_tm2str(&tm, buf);
 	return EOK;
 }
 
-
-/**
- * Converts broken-down time to a string in format
- * "Sun Jan 1 00:00:00 1970\n". (Obsolete)
+/** Convert broken-down time to a NULL-terminated string.
+ *
+ * The format is "Sun Jan 1 00:00:00 1970\n". (Obsolete)
  *
  * @param timeptr Broken-down time structure.
- * @param buf     Buffer to store string to, must be at least ASCTIME_BUF_LEN
- *                bytes long.
+ * @param buf     Buffer to store string to, must be at least
+ *                ASCTIME_BUF_LEN bytes long.
+ *
  */
 void time_tm2str(const struct tm *restrict timeptr, char *restrict buf)
@@ -901,13 +992,14 @@
 	assert(timeptr != NULL);
 	assert(buf != NULL);
-
+	
 	static const char *wday[] = {
 		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
 	};
+	
 	static const char *mon[] = {
 		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
 		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
 	};
-
+	
 	snprintf(buf, ASCTIME_BUF_LEN, "%s %s %2d %02d:%02d:%02d %d\n",
 	    wday[timeptr->tm_wday],
@@ -918,18 +1010,19 @@
 }
 
-/**
- * Converts a time value to a broken-down local time, expressed relative
- * to the user's specified timezone.
- *
- * @param timer     Time to convert.
- * @param result    Structure to store the result to.
- *
- * @return          EOK on success or a negative error code.
+/** Converts a time value to a broken-down local time.
+ *
+ * Time is expressed relative to the user's specified timezone.
+ *
+ * @param timer  Time to convert.
+ * @param result Structure to store the result to.
+ *
+ * @return EOK on success or a negative error code.
+ *
  */
 int time_local2tm(const time_t time, struct tm *restrict result)
 {
-	// TODO: deal with timezone
-	// currently assumes system and all times are in GMT
-
+	// TODO: Deal with timezones.
+	//       Currently assumes system and all times are in UTC
+	
 	/* Set result to epoch. */
 	result->tm_sec = 0;
@@ -939,41 +1032,41 @@
 	result->tm_mon = 0;
 	result->tm_year = 70; /* 1970 */
-
-	if (_normalize_time(result, time) == -1)
+	
+	if (normalize_time(result, time) == -1)
 		return EOVERFLOW;
-
+	
 	return EOK;
 }
 
-/**
- * Converts the calendar time to a null terminated string
- * of the form "Wed Jun 30 21:49:08 1993\n" expressed relative to the
+/** Convert the calendar time to a NULL-terminated string.
+ *
+ * The format is "Wed Jun 30 21:49:08 1993\n" expressed relative to the
  * user's specified timezone.
- * 
- * @param timer  Time to convert.
- * @param buf    Buffer to store the string to. Must be at least
- *               ASCTIME_BUF_LEN bytes long.
- *
- * @return       EOK on success or a negative error code.
+ *
+ * @param timer Time to convert.
+ * @param buf   Buffer to store the string to. Must be at least
+ *              ASCTIME_BUF_LEN bytes long.
+ *
+ * @return EOK on success or a negative error code.
+ *
  */
 int time_local2str(const time_t time, char *buf)
 {
 	struct tm loctime;
-	int r;
-
-	if ((r = time_local2tm(time, &loctime)) != EOK)
-		return r;
-
+	int ret = time_local2tm(time, &loctime);
+	if (ret != EOK)
+		return ret;
+	
 	time_tm2str(&loctime, buf);
-
 	return EOK;
 }
 
-/**
- * Calculate the difference between two times, in seconds.
- * 
+/** Calculate the difference between two times, in seconds.
+ *
  * @param time1 First time.
  * @param time0 Second time.
- * @return Time in seconds.
+ *
+ * @return Time difference in seconds.
+ *
  */
 double difftime(time_t time1, time_t time0)
Index: uspace/lib/c/include/fourcc.h
===================================================================
--- uspace/lib/c/include/fourcc.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/c/include/fourcc.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -38,4 +38,6 @@
 #include <libarch/common.h>
 
+typedef uint32_t fourcc_t;
+
 #define FOURCC(a, b, c, d) \
 	(((UINT32_T) (a)) | (((UINT32_T) (b)) << 8) | \
Index: uspace/lib/c/include/stats.h
===================================================================
--- uspace/lib/c/include/stats.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/c/include/stats.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -43,8 +43,9 @@
 #include <abi/sysinfo.h>
 
+#define LOAD_UNIT  65536
+
 extern stats_cpu_t *stats_get_cpus(size_t *);
 extern stats_physmem_t *stats_get_physmem(void);
 extern load_t *stats_get_load(size_t *);
-extern sysarg_t stats_get_uptime(void);
 
 extern stats_task_t *stats_get_tasks(size_t *);
Index: uspace/lib/c/include/stddef.h
===================================================================
--- uspace/lib/c/include/stddef.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/c/include/stddef.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -42,4 +42,5 @@
 #endif
 
+#define offsetof(type,member) ((size_t) &(((type *) 0)->member))
 
 #endif
Index: uspace/lib/c/include/sys/time.h
===================================================================
--- uspace/lib/c/include/sys/time.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/c/include/sys/time.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -40,6 +40,6 @@
 #include <sys/types.h>
 
-#define DST_NONE 0
-#define ASCTIME_BUF_LEN 26
+#define DST_NONE  0
+#define ASCTIME_BUF_LEN  26
 
 typedef long time_t;
@@ -50,13 +50,13 @@
 
 struct tm {
-	int tm_sec;         /* Seconds [0,60]. */
-	int tm_min;         /* Minutes [0,59]. */
-	int tm_hour;        /* Hour [0,23]. */
-	int tm_mday;        /* Day of month [1,31]. */
-	int tm_mon;         /* Month of year [0,11]. */
-	int tm_year;        /* Years since 1900. */
-	int tm_wday;        /* Day of week [0,6] (Sunday = 0). */
-	int tm_yday;        /* Day of year [0,365]. */
-	int tm_isdst;       /* Daylight Savings flag. */
+	int tm_sec;    /* Seconds [0,60]. */
+	int tm_min;    /* Minutes [0,59]. */
+	int tm_hour;   /* Hour [0,23]. */
+	int tm_mday;   /* Day of month [1,31]. */
+	int tm_mon;    /* Month of year [0,11]. */
+	int tm_year;   /* Years since 1900. */
+	int tm_wday;   /* Day of week [0,6] (Sunday = 0). */
+	int tm_yday;   /* Day of year [0,365]. */
+	int tm_isdst;  /* Daylight Savings flag. */
 };
 
@@ -71,22 +71,22 @@
 };
 
-extern void tv_add(struct timeval *tv, suseconds_t usecs);
-extern suseconds_t tv_sub(struct timeval *tv1, struct timeval *tv2);
-extern int tv_gt(struct timeval *tv1, struct timeval *tv2);
-extern int tv_gteq(struct timeval *tv1, struct timeval *tv2);
-extern int gettimeofday(struct timeval *tv, struct timezone *tz);
-extern int getuptime(struct timeval *tv);
+extern void tv_add(struct timeval *, suseconds_t);
+extern suseconds_t tv_sub(struct timeval *, struct timeval *);
+extern int tv_gt(struct timeval *, struct timeval *);
+extern int tv_gteq(struct timeval *, struct timeval *);
+extern void gettimeofday(struct timeval *, struct timezone *);
+extern void getuptime(struct timeval *);
 
 extern void udelay(useconds_t);
 
-extern time_t mktime(struct tm *tm);
-extern int time_utc2tm(const time_t time, struct tm *result);
-extern int time_utc2str(const time_t time, char *buf);
-extern void time_tm2str(const struct tm *timeptr, char *buf);
-extern int time_local2tm(const time_t time, struct tm *result);
-extern int time_local2str(const time_t time, char *buf);
-extern double difftime(time_t time1, time_t time0);
-extern size_t strftime(char *restrict s, size_t maxsize,
-    const char *restrict format, const struct tm *restrict tm);
+extern time_t mktime(struct tm *);
+extern int time_utc2tm(const time_t, struct tm *);
+extern int time_utc2str(const time_t, char *);
+extern void time_tm2str(const struct tm *, char *);
+extern int time_local2tm(const time_t, struct tm *);
+extern int time_local2str(const time_t, char *);
+extern double difftime(time_t, time_t);
+extern size_t strftime(char *restrict, size_t, const char *restrict,
+    const struct tm *restrict);
 
 #endif
Index: uspace/lib/compress/Makefile
===================================================================
--- uspace/lib/compress/Makefile	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/compress/Makefile	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,36 @@
+#
+# Copyright (c) 2014 Martin Decky
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+# - Redistributions in binary form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in the
+#   documentation and/or other materials provided with the distribution.
+# - The name of the author may not be used to endorse or promote products
+#   derived from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+USPACE_PREFIX = ../..
+LIBRARY = libcompress
+
+SOURCES = \
+	inflate.c \
+	gzip.c
+
+include $(USPACE_PREFIX)/Makefile.common
Index: uspace/lib/compress/gzip.c
===================================================================
--- uspace/lib/compress/gzip.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/compress/gzip.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) 2014 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <sys/types.h>
+#include <errno.h>
+#include <mem.h>
+#include <malloc.h>
+#include <unistd.h>
+#include "gzip.h"
+#include "inflate.h"
+
+#define GZIP_ID1  UINT8_C(0x1f)
+#define GZIP_ID2  UINT8_C(0x8b)
+
+#define GZIP_METHOD_DEFLATE  UINT8_C(0x08)
+
+#define GZIP_FLAGS_MASK     UINT8_C(0x1f)
+#define GZIP_FLAG_FHCRC     UINT8_C(1 << 1)
+#define GZIP_FLAG_FEXTRA    UINT8_C(1 << 2)
+#define GZIP_FLAG_FNAME     UINT8_C(1 << 3)
+#define GZIP_FLAG_FCOMMENT  UINT8_C(1 << 4)
+
+typedef struct {
+	uint8_t id1;
+	uint8_t id2;
+	uint8_t method;
+	uint8_t flags;
+	uint32_t mtime;
+	uint8_t extra_flags;
+	uint8_t os;
+} __attribute__((packed)) gzip_header_t;
+
+typedef struct {
+	uint32_t crc32;
+	uint32_t size;
+} __attribute__((packed)) gzip_footer_t;
+
+/** Expand GZIP compressed data
+ *
+ * The routine allocates the output buffer based
+ * on the size encoded in the input stream. This
+ * effectively limits the size of the uncompressed
+ * data to 4 GiB (expanding input streams that actually
+ * encode more data will always fail).
+ *
+ * So far, no CRC is perfomed.
+ *
+ * @param[in]  src     Source data buffer.
+ * @param[in]  srclen  Source buffer size (bytes).
+ * @param[out] dest    Destination data buffer.
+ * @param[out] destlen Destination buffer size (bytes).
+ *
+ * @return EOK on success.
+ * @return ENOENT on distance too large.
+ * @return EINVAL on invalid Huffman code, invalid deflate data,
+ *                   invalid compression method or invalid stream.
+ * @return ELIMIT on input buffer overrun.
+ * @return ENOMEM on output buffer overrun.
+ *
+ */
+int gzip_expand(void *src, size_t srclen, void **dest, size_t *destlen)
+{
+	gzip_header_t header;
+	gzip_footer_t footer;
+	
+	if ((srclen < sizeof(header)) || (srclen < sizeof(footer)))
+		return EINVAL;
+	
+	/* Decode header and footer */
+	
+	memcpy(&header, src, sizeof(header));
+	memcpy(&footer, src + srclen - sizeof(footer), sizeof(footer));
+	
+	if ((header.id1 != GZIP_ID1) ||
+	    (header.id2 != GZIP_ID2) ||
+	    (header.method != GZIP_METHOD_DEFLATE) ||
+	    ((header.flags & (~GZIP_FLAGS_MASK)) != 0))
+		return EINVAL;
+	
+	*destlen = footer.size;
+	
+	/* Ignore extra metadata */
+	
+	void *stream = src + sizeof(header);
+	size_t stream_length = srclen - sizeof(header) - sizeof(footer);
+	
+	if ((header.flags & GZIP_FLAG_FEXTRA) != 0) {
+		uint16_t extra_length;
+		
+		if (stream_length < sizeof(extra_length))
+			return EINVAL;
+		
+		memcpy(&extra_length, stream, sizeof(extra_length));
+		stream += sizeof(extra_length);
+		stream_length -= sizeof(extra_length);
+		
+		if (stream_length < extra_length)
+			return EINVAL;
+		
+		stream += extra_length;
+		stream_length -= extra_length;
+	}
+	
+	if ((header.flags & GZIP_FLAG_FNAME) != 0) {
+		while (*((uint8_t *) stream) != 0) {
+			if (stream_length == 0)
+				return EINVAL;
+			
+			stream++;
+			stream_length--;
+		}
+		
+		if (stream_length == 0)
+			return EINVAL;
+		
+		stream++;
+		stream_length--;
+	}
+	
+	if ((header.flags & GZIP_FLAG_FCOMMENT) != 0) {
+		while (*((uint8_t *) stream) != 0) {
+			if (stream_length == 0)
+				return EINVAL;
+			
+			stream++;
+			stream_length--;
+		}
+		
+		if (stream_length == 0)
+			return EINVAL;
+		
+		stream++;
+		stream_length--;
+	}
+	
+	if ((header.flags & GZIP_FLAG_FHCRC) != 0) {
+		if (stream_length < 2)
+			return EINVAL;
+		
+		stream += 2;
+		stream_length -= 2;
+	}
+	
+	/* Allocate output buffer and inflate the data */
+	
+	*dest = malloc(*destlen);
+	if (*dest == NULL)
+		return ENOMEM;
+	
+	int ret = inflate(stream, stream_length, *dest, *destlen);
+	if (ret != EOK) {
+		free(dest);
+		return ret;
+	}
+	
+	return EOK;
+}
Index: uspace/lib/compress/gzip.h
===================================================================
--- uspace/lib/compress/gzip.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/compress/gzip.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2014 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef LIBCOMPRESS_GZIP_H_
+#define LIBCOMPRESS_GZIP_H_
+
+#include <sys/types.h>
+
+extern int gzip_expand(void *, size_t, void **, size_t *);
+
+#endif
Index: uspace/lib/compress/inflate.c
===================================================================
--- uspace/lib/compress/inflate.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/compress/inflate.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,665 @@
+/*
+ * Copyright (c) 2010 Mark Adler
+ * Copyright (c) 2010 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @file
+ * @brief Implementation of inflate decompression
+ *
+ * A simple inflate implementation (decompression of `deflate' stream as
+ * described by RFC 1951) based on puff.c by Mark Adler. This code is
+ * currently not optimized for speed but for readability.
+ *
+ * All dynamically allocated memory memory is taken from the stack. The
+ * stack usage should be typically bounded by 2 KB.
+ *
+ * Original copyright notice:
+ *
+ *  Copyright (C) 2002-2010 Mark Adler, all rights reserved
+ *  version 2.1, 4 Apr 2010
+ *
+ *  This software is provided 'as-is', without any express or implied
+ *  warranty. In no event will the author be held liable for any damages
+ *  arising from the use of this software.
+ *
+ *  Permission is granted to anyone to use this software for any purpose,
+ *  including commercial applications, and to alter it and redistribute it
+ *  freely, subject to the following restrictions:
+ *
+ *  1. The origin of this software must not be misrepresented; you must not
+ *     claim that you wrote the original software. If you use this software
+ *     in a product, an acknowledgment in the product documentation would be
+ *     appreciated but is not required.
+ *  2. Altered source versions must be plainly marked as such, and must not
+ *     be misrepresented as being the original software.
+ *  3. This notice may not be removed or altered from any source
+ *     distribution.
+ *
+ *   Mark Adler <madler@alumni.caltech.edu>
+ *
+ */
+
+#include <sys/types.h>
+#include <stdbool.h>
+#include <errno.h>
+#include <mem.h>
+#include "inflate.h"
+
+/** Maximum bits in the Huffman code */
+#define MAX_HUFFMAN_BIT  15
+
+/** Number of length codes */
+#define MAX_LEN           29
+/** Number of distance codes */
+#define MAX_DIST          30
+/** Number of order codes */
+#define MAX_ORDER         19
+/** Number of literal/length codes */
+#define MAX_LITLEN        286
+/** Number of fixed literal/length codes */
+#define MAX_FIXED_LITLEN  288
+
+/** Number of all codes */
+#define MAX_CODE  (MAX_LITLEN + MAX_DIST)
+
+/** Check for input buffer overrun condition */
+#define CHECK_OVERRUN(state) \
+	do { \
+		if ((state).overrun) \
+			return ELIMIT; \
+	} while (false)
+
+
+/** Inflate algorithm state
+ *
+ */
+typedef struct {
+	uint8_t *dest;    /**< Output buffer */
+	size_t destlen;   /**< Output buffer size */
+	size_t destcnt;   /**< Position in the output buffer */
+	
+	uint8_t *src;     /**< Input buffer */
+	size_t srclen;    /**< Input buffer size */
+	size_t srccnt;    /**< Position in the input buffer */
+	
+	uint16_t bitbuf;  /**< Bit buffer */
+	size_t bitlen;    /**< Number of bits in the bit buffer */
+	
+	bool overrun;     /**< Overrun condition */
+} inflate_state_t;
+
+/** Huffman code description
+ *
+ */
+typedef struct {
+	uint16_t *count;   /**< Array of symbol counts */
+	uint16_t *symbol;  /**< Array of symbols */
+} huffman_t;
+
+/** Length codes
+ *
+ */
+static const uint16_t lens[MAX_LEN] = {
+	3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+	35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258
+};
+
+/** Extended length codes
+ *
+ */
+static const uint16_t lens_ext[MAX_LEN] = {
+	0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+	3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0
+};
+
+/** Distance codes
+ *
+ */
+static const uint16_t dists[MAX_DIST] = {
+	1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+	257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+	8193, 12289, 16385, 24577
+};
+
+/** Extended distance codes
+ *
+ */
+static const uint16_t dists_ext[MAX_DIST] = {
+	0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+	7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
+	12, 12, 13, 13
+};
+
+/** Order codes
+ *
+ */
+static const short order[MAX_ORDER] = {
+	16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
+};
+
+/** Static length symbol counts
+ *
+ */
+static uint16_t len_count[MAX_HUFFMAN_BIT + 1] = {
+	0, 0, 0, 0, 0, 0, 0, 24, 152, 112, 0, 0, 0, 0, 0, 0
+};
+
+/** Static length symbols
+ *
+ */
+static uint16_t len_symbol[MAX_FIXED_LITLEN] = {
+	256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268,
+	269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 0, 1, 2,
+	3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+	21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
+	37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
+	53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
+	69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
+	85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
+	101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
+	114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
+	127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
+	140, 141, 142, 143, 280, 281, 282, 283, 284, 285, 286, 287, 144,
+	145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
+	158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
+	171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
+	184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196,
+	197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
+	210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222,
+	223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235,
+	236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
+	249, 250, 251, 252, 253, 254, 255
+};
+
+/** Static distance symbol counts
+ *
+ */
+static uint16_t dist_count[MAX_HUFFMAN_BIT + 1] = {
+	0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/** Static distance symbols
+ *
+ */
+static uint16_t dist_symbol[MAX_DIST] = {
+	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+	16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
+};
+
+/** Huffman code for lengths
+ *
+ */
+static huffman_t len_code = {
+	.count = len_count,
+	.symbol = len_symbol
+};
+
+/** Huffman code for distances
+ *
+ */
+static huffman_t dist_code = {
+	.count = dist_count,
+	.symbol = dist_symbol
+};
+
+/** Get bits from the bit buffer
+ *
+ * @param state Inflate state.
+ * @param cnt   Number of bits to return (at most 16).
+ *
+ * @return Returned bits.
+ *
+ */
+static inline uint16_t get_bits(inflate_state_t *state, size_t cnt)
+{
+	/* Bit accumulator for at least 20 bits */
+	uint32_t val = state->bitbuf;
+	
+	while (state->bitlen < cnt) {
+		if (state->srccnt == state->srclen) {
+			state->overrun = true;
+			return 0;
+		}
+		
+		/* Load 8 more bits */
+		val |= ((uint32_t) state->src[state->srccnt]) << state->bitlen;
+		state->srccnt++;
+		state->bitlen += 8;
+	}
+	
+	/* Update bits in the buffer */
+	state->bitbuf = (uint16_t) (val >> cnt);
+	state->bitlen -= cnt;
+	
+	return ((uint16_t) (val & ((1 << cnt) - 1)));
+}
+
+/** Decode `stored' block
+ *
+ * @param state Inflate state.
+ *
+ * @return EOK on success.
+ * @return ELIMIT on input buffer overrun.
+ * @return ENOMEM on output buffer overrun.
+ * @return EINVAL on invalid data.
+ *
+ */
+static int inflate_stored(inflate_state_t *state)
+{
+	/* Discard bits in the bit buffer */
+	state->bitbuf = 0;
+	state->bitlen = 0;
+	
+	if (state->srccnt + 4 > state->srclen)
+		return ELIMIT;
+	
+	uint16_t len =
+	    state->src[state->srccnt] | (state->src[state->srccnt + 1] << 8);
+	uint16_t len_compl =
+	    state->src[state->srccnt + 2] | (state->src[state->srccnt + 3] << 8);
+	
+	/* Check block length and its complement */
+	if (((int16_t) len) != ~((int16_t) len_compl))
+		return EINVAL;
+	
+	state->srccnt += 4;
+	
+	/* Check input buffer size */
+	if (state->srccnt + len > state->srclen)
+		return ELIMIT;
+	
+	/* Check output buffer size */
+	if (state->destcnt + len > state->destlen)
+		return ENOMEM;
+	
+	/* Copy data */
+	memcpy(state->dest + state->destcnt, state->src + state->srccnt, len);
+	state->srccnt += len;
+	state->destcnt += len;
+	
+	return EOK;
+}
+
+/** Decode a symbol using the Huffman code
+ *
+ * @param state   Inflate state.
+ * @param huffman Huffman code.
+ * @param symbol  Decoded symbol.
+ *
+ * @param EOK on success.
+ * @param EINVAL on invalid Huffman code.
+ *
+ */
+static int huffman_decode(inflate_state_t *state, huffman_t *huffman,
+    uint16_t *symbol)
+{
+	uint16_t code = 0; /* Decoded bits */
+	size_t first = 0;  /* First code of the given length */
+	size_t index = 0;  /* Index of the first code of the given length
+	                      in the symbol table */
+	
+	size_t len;  /* Current number of bits in the code */
+	for (len = 1; len <= MAX_HUFFMAN_BIT; len++) {
+		/* Get next bit */
+		code |= get_bits(state, 1);
+		CHECK_OVERRUN(*state);
+		
+		uint16_t count = huffman->count[len];
+		if (code < first + count) {
+			/* Return decoded symbol */
+			*symbol = huffman->symbol[index + code - first];
+			return EOK;
+		}
+		
+		/* Update for next length */
+		index += count;
+		first += count;
+		first <<= 1;
+		code <<= 1;
+	}
+	
+	return EINVAL;
+}
+
+/** Construct Huffman tables from canonical Huffman code
+ *
+ * @param huffman Constructed Huffman tables.
+ * @param length  Lengths of the canonical Huffman code.
+ * @param n       Number of lengths.
+ *
+ * @return 0 if the Huffman code set is complete.
+ * @return Negative value for an over-subscribed code set.
+ * @return Positive value for an incomplete code set.
+ *
+ */
+static int16_t huffman_construct(huffman_t *huffman, uint16_t *length, size_t n)
+{
+	/* Count number of codes for each length */
+	size_t len;
+	for (len = 0; len <= MAX_HUFFMAN_BIT; len++)
+		huffman->count[len] = 0;
+	
+	/* We assume that the lengths are within bounds */
+	size_t symbol;
+	for (symbol = 0; symbol < n; symbol++)
+		huffman->count[length[symbol]]++;
+	
+	if (huffman->count[0] == n) {
+		/* The code is complete, but decoding will fail */
+		return 0;
+	}
+	
+	/* Check for an over-subscribed or incomplete set of lengths */
+	int16_t left = 1;
+	for (len = 1; len <= MAX_HUFFMAN_BIT; len++) {
+		left <<= 1;
+		left -= huffman->count[len];
+		if (left < 0) {
+			/* Over-subscribed */
+			return left;
+		}
+	}
+	
+	/* Generate offsets into symbol table */
+	uint16_t offs[MAX_HUFFMAN_BIT + 1];
+	
+	offs[1] = 0;
+	for (len = 1; len < MAX_HUFFMAN_BIT; len++)
+		offs[len + 1] = offs[len] + huffman->count[len];
+	
+	for (symbol = 0; symbol < n; symbol++) {
+		if (length[symbol] != 0) {
+			huffman->symbol[offs[length[symbol]]] = symbol;
+			offs[length[symbol]]++;
+		}
+	}
+	
+	return left;
+}
+
+/** Decode literal/length and distance codes
+ *
+ * Decode until end-of-block code.
+ *
+ * @param state     Inflate state.
+ * @param len_code  Huffman code for literal/length.
+ * @param dist_code Huffman code for distance.
+ *
+ * @return EOK on success.
+ * @return ENOENT on distance too large.
+ * @return EINVAL on invalid Huffman code.
+ * @return ELIMIT on input buffer overrun.
+ * @return ENOMEM on output buffer overrun.
+ *
+ */
+static int inflate_codes(inflate_state_t *state, huffman_t* len_code,
+    huffman_t* dist_code)
+{
+	uint16_t symbol;
+	
+	do {
+		int err = huffman_decode(state, len_code, &symbol);
+		if (err != EOK) {
+			/* Error decoding */
+			return err;
+		}
+		
+		if (symbol < 256) {
+			/* Write out literal */
+			if (state->destcnt == state->destlen)
+				return ENOMEM;
+			
+			state->dest[state->destcnt] = (uint8_t) symbol;
+			state->destcnt++;
+		} else if (symbol > 256) {
+			/* Compute length */
+			symbol -= 257;
+			if (symbol >= 29)
+				return EINVAL;
+			
+			size_t len = lens[symbol] + get_bits(state, lens_ext[symbol]);
+			CHECK_OVERRUN(*state);
+			
+			/* Get distance */
+			err = huffman_decode(state, dist_code, &symbol);
+			if (err != EOK)
+				return err;
+			
+			size_t dist = dists[symbol] + get_bits(state, dists_ext[symbol]);
+			if (dist > state->destcnt)
+				return ENOENT;
+			
+			if (state->destcnt + len > state->destlen)
+				return ENOMEM;
+			
+			while (len > 0) {
+				/* Copy len bytes from distance bytes back */
+				state->dest[state->destcnt]
+				    = state->dest[state->destcnt - dist];
+				state->destcnt++;
+				len--;
+			}
+		}
+	} while (symbol != 256);
+	
+	return EOK;
+}
+
+/** Decode `fixed codes' block
+ *
+ * @param state     Inflate state.
+ * @param len_code  Huffman code for literal/length.
+ * @param dist_code Huffman code for distance.
+ *
+ * @return EOK on success.
+ * @return ENOENT on distance too large.
+ * @return EINVAL on invalid Huffman code.
+ * @return ELIMIT on input buffer overrun.
+ * @return ENOMEM on output buffer overrun.
+ *
+ */
+static int inflate_fixed(inflate_state_t *state, huffman_t *len_code,
+    huffman_t *dist_code)
+{
+	return inflate_codes(state, len_code, dist_code);
+}
+
+/** Decode `dynamic codes' block
+ *
+ * @param state     Inflate state.
+ *
+ * @return EOK on success.
+ * @return ENOENT on distance too large.
+ * @return EINVAL on invalid Huffman code.
+ * @return ELIMIT on input buffer overrun.
+ * @return ENOMEM on output buffer overrun.
+ *
+ */
+static int inflate_dynamic(inflate_state_t *state)
+{
+	uint16_t length[MAX_CODE];
+	uint16_t dyn_len_count[MAX_HUFFMAN_BIT + 1];
+	uint16_t dyn_len_symbol[MAX_LITLEN];
+	uint16_t dyn_dist_count[MAX_HUFFMAN_BIT + 1];
+	uint16_t dyn_dist_symbol[MAX_DIST];
+	huffman_t dyn_len_code;
+	huffman_t dyn_dist_code;
+	
+	dyn_len_code.count = dyn_len_count;
+	dyn_len_code.symbol = dyn_len_symbol;
+	
+	dyn_dist_code.count = dyn_dist_count;
+	dyn_dist_code.symbol = dyn_dist_symbol;
+	
+	/* Get number of bits in each table */
+	uint16_t nlen = get_bits(state, 5) + 257;
+	CHECK_OVERRUN(*state);
+	
+	uint16_t ndist = get_bits(state, 5) + 1;
+	CHECK_OVERRUN(*state);
+	
+	uint16_t ncode = get_bits(state, 4) + 4;
+	CHECK_OVERRUN(*state);
+	
+	if ((nlen > MAX_LITLEN) || (ndist > MAX_DIST)
+	    || (ncode > MAX_ORDER))
+		return EINVAL;
+	
+	/* Read code length code lengths */
+	uint16_t index;
+	for (index = 0; index < ncode; index++) {
+		length[order[index]] = get_bits(state, 3);
+		CHECK_OVERRUN(*state);
+	}
+	
+	/* Set missing lengths to zero */
+	for (index = ncode; index < MAX_ORDER; index++)
+		length[order[index]] = 0;
+	
+	/* Build Huffman code */
+	int16_t rc = huffman_construct(&dyn_len_code, length, MAX_ORDER);
+	if (rc != 0)
+		return EINVAL;
+	
+	/* Read length/literal and distance code length tables */
+	index = 0;
+	while (index < nlen + ndist) {
+		uint16_t symbol;
+		int err = huffman_decode(state, &dyn_len_code, &symbol);
+		if (err != EOK)
+			return EOK;
+		
+		if (symbol < 16) {
+			length[index] = symbol;
+			index++;
+		} else {
+			uint16_t len = 0;
+			
+			if (symbol == 16) {
+				if (index == 0)
+					return EINVAL;
+				
+				len = length[index - 1];
+				symbol = get_bits(state, 2) + 3;
+				CHECK_OVERRUN(*state);
+			} else if (symbol == 17) {
+				symbol = get_bits(state, 3) + 3;
+				CHECK_OVERRUN(*state);
+			} else {
+				symbol = get_bits(state, 7) + 11;
+				CHECK_OVERRUN(*state);
+			}
+			
+			if (index + symbol > nlen + ndist)
+				return EINVAL;
+			
+			while (symbol > 0) {
+				length[index] = len;
+				index++;
+				symbol--;
+			}
+		}
+	}
+	
+	/* Check for end-of-block code */
+	if (length[256] == 0)
+		return EINVAL;
+	
+	/* Build Huffman tables for literal/length codes */
+	rc = huffman_construct(&dyn_len_code, length, nlen);
+	if ((rc < 0) || ((rc > 0) && (dyn_len_code.count[0] + 1 != nlen)))
+		return EINVAL;
+	
+	/* Build Huffman tables for distance codes */
+	rc = huffman_construct(&dyn_dist_code, length + nlen, ndist);
+	if ((rc < 0) || ((rc > 0) && (dyn_dist_code.count[0] + 1 != ndist)))
+		return EINVAL;
+	
+	return inflate_codes(state, &dyn_len_code, &dyn_dist_code);
+}
+
+/** Inflate data
+ *
+ * @param src     Source data buffer.
+ * @param srclen  Source buffer size (bytes).
+ * @param dest    Destination data buffer.
+ * @param destlen Destination buffer size (bytes).
+ *
+ * @return EOK on success.
+ * @return ENOENT on distance too large.
+ * @return EINVAL on invalid Huffman code or invalid deflate data.
+ * @return ELIMIT on input buffer overrun.
+ * @return ENOMEM on output buffer overrun.
+ *
+ */
+int inflate(void *src, size_t srclen, void *dest, size_t destlen)
+{
+	/* Initialize the state */
+	inflate_state_t state;
+	
+	state.dest = (uint8_t *) dest;
+	state.destlen = destlen;
+	state.destcnt = 0;
+	
+	state.src = (uint8_t *) src;
+	state.srclen = srclen;
+	state.srccnt = 0;
+	
+	state.bitbuf = 0;
+	state.bitlen = 0;
+	
+	state.overrun = false;
+	
+	uint16_t last;
+	int ret = 0;
+	
+	do {
+		/* Last block is indicated by a non-zero bit */
+		last = get_bits(&state, 1);
+		CHECK_OVERRUN(state);
+		
+		/* Block type */
+		uint16_t type = get_bits(&state, 2);
+		CHECK_OVERRUN(state);
+		
+		switch (type) {
+		case 0:
+			ret = inflate_stored(&state);
+			break;
+		case 1:
+			ret = inflate_fixed(&state, &len_code, &dist_code);
+			break;
+		case 2:
+			ret = inflate_dynamic(&state);
+			break;
+		default:
+			ret = EINVAL;
+		}
+	} while ((!last) && (ret == 0));
+	
+	return ret;
+}
Index: uspace/lib/compress/inflate.h
===================================================================
--- uspace/lib/compress/inflate.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/compress/inflate.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2010 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef LIBCOMPRESS_INFLATE_H_
+#define LIBCOMPRESS_INFLATE_H_
+
+#include <sys/types.h>
+
+extern int inflate(void *, size_t, void *, size_t);
+
+#endif
Index: uspace/lib/draw/Makefile
===================================================================
--- uspace/lib/draw/Makefile	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/draw/Makefile	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -31,8 +31,10 @@
 SLIBRARY = libdraw.so.0.0
 LSONAME = libdraw.so0
-EXTRA_CFLAGS += -I$(LIBSOFTREND_PREFIX)
+EXTRA_CFLAGS += -I$(LIBSOFTREND_PREFIX) -I$(LIBCOMPRESS_PREFIX)
 
 SOURCES = \
 	codec/tga.c \
+	codec/tga.gz.c \
+	codec/webp.c \
 	cursor/embedded.c \
 	font/embedded.c \
Index: uspace/lib/draw/codec/tga.c
===================================================================
--- uspace/lib/draw/codec/tga.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/draw/codec/tga.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -110,4 +110,5 @@
  * @return True on succesful decoding.
  * @return False on failure.
+ *
  */
 static bool decode_tga_header(void *data, size_t size, tga_t *tga)
@@ -174,4 +175,5 @@
  * @return Newly allocated surface with the decoded content.
  * @return NULL on error or unsupported format.
+ *
  */
 surface_t *decode_tga(void *data, size_t size, surface_flags_t flags)
@@ -264,4 +266,5 @@
  * @return True on succesful encoding.
  * @return False on failure.
+ *
  */
 bool encode_tga(surface_t *surface, void **pdata, size_t *psize)
Index: uspace/lib/draw/codec/tga.gz.c
===================================================================
--- uspace/lib/draw/codec/tga.gz.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/draw/codec/tga.gz.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2014 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup draw
+ * @{
+ */
+/**
+ * @file
+ */
+
+#include <errno.h>
+#include <gzip.h>
+#include <malloc.h>
+#include "tga.gz.h"
+#include "tga.h"
+
+/** Decode gzipped Truevision TGA format
+ *
+ * Decode gzipped Truevision TGA format and create a surface
+ * from it. The supported variants of TGA are limited those
+ * supported by decode_tga().
+ *
+ * @param[in] data  Memory representation of gzipped TGA.
+ * @param[in] size  Size of the representation (in bytes).
+ * @param[in] flags Surface creation flags.
+ *
+ * @return Newly allocated surface with the decoded content.
+ * @return NULL on error or unsupported format.
+ *
+ */
+surface_t *decode_tga_gz(void *data, size_t size, surface_flags_t flags)
+{
+	void *data_expanded;
+	size_t size_expanded;
+	
+	int ret = gzip_expand(data, size, &data_expanded, &size_expanded);
+	if (ret != EOK)
+		return NULL;
+	
+	surface_t *surface = decode_tga(data_expanded, size_expanded, flags);
+	
+	free(data_expanded);
+	return surface;
+}
+
+/** Encode gzipped Truevision TGA format
+ *
+ * Encode gzipped Truevision TGA format into an array.
+ *
+ * @param[in]  surface Surface to be encoded into gzipped TGA.
+ * @param[out] pdata   Pointer to the resulting array.
+ * @param[out] psize   Pointer to the size of the resulting array.
+ *
+ * @return True on succesful encoding.
+ * @return False on failure.
+ *
+ */
+bool encode_tga_gz(surface_t *surface, void **pdata, size_t *psize)
+{
+	// TODO
+	return false;
+}
+
+/** @}
+ */
Index: uspace/lib/draw/codec/tga.gz.h
===================================================================
--- uspace/lib/draw/codec/tga.gz.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/draw/codec/tga.gz.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup draw
+ * @{
+ */
+/**
+ * @file
+ */
+
+#ifndef DRAW_CODEC_TGA_GZ_H_
+#define DRAW_CODEC_TGA_GZ_H_
+
+#include <sys/types.h>
+#include "../surface.h"
+
+extern surface_t *decode_tga_gz(void *, size_t, surface_flags_t);
+extern bool encode_tga_gz(surface_t *, void **, size_t *);
+
+#endif
+
+/** @}
+ */
Index: uspace/lib/draw/codec/webp.c
===================================================================
--- uspace/lib/draw/codec/webp.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/draw/codec/webp.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,262 @@
+/*
+ * Copyright (c) 2014 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup draw
+ * @{
+ */
+/**
+ * @file
+ */
+
+#include <stdlib.h>
+#include <byteorder.h>
+#include <align.h>
+#include <stdbool.h>
+#include <fourcc.h>
+#include <pixconv.h>
+#include "webp.h"
+
+/** Check for input buffer overrun condition */
+#define CHECK_OVERRUN(state, retval) \
+	do { \
+		if ((state).overrun) \
+			return (retval); \
+	} while (false)
+
+#define SIGNATURE_WEBP_LOSSLESS  UINT8_C(0x2f)
+
+enum {
+	FOURCC_RIFF          = FOURCC('R', 'I', 'F', 'F'),
+	FOURCC_WEBP          = FOURCC('W', 'E', 'B', 'P'),
+	FOURCC_WEBP_LOSSLESS = FOURCC('V', 'P', '8', 'L')
+};
+
+typedef enum {
+	TRANSFORM_PREDICTOR      = 0,
+	TRANSFORM_COLOR          = 1,
+	TRANSFORM_SUBTRACT       = 2,
+	TRANSFORM_COLOR_INDEXING = 3
+} webp_transform_t;
+
+typedef struct {
+	fourcc_t fourcc;
+	uint32_t payload_size;
+} __attribute__((packed)) riff_header_t;
+
+typedef struct {
+	fourcc_t fourcc;
+	fourcc_t encoding;
+	uint32_t stream_size;
+	uint8_t signature;
+} __attribute__((packed)) webp_header_t;
+
+typedef struct {
+	uint32_t stream_size;
+	uint16_t width;
+	uint16_t height;
+	bool alpha_used;
+	uint8_t version;
+	
+	uint8_t *src;     /**< Input buffer */
+	size_t srclen;    /**< Input buffer size */
+	size_t srccnt;    /**< Position in the input buffer */
+	
+	uint32_t bitbuf;  /**< Bit buffer */
+	size_t bitlen;    /**< Number of bits in the bit buffer */
+	
+	bool overrun;     /**< Overrun condition */
+} webp_t;
+
+/** Get bits from the bit buffer
+ *
+ * @param state WebP state.
+ * @param cnt   Number of bits to return (at most 32).
+ *
+ * @return Returned bits.
+ *
+ */
+static inline uint32_t get_bits(webp_t *state, size_t cnt)
+{
+	/* Bit accumulator for at least 36 bits */
+	uint64_t val = state->bitbuf;
+	
+	while (state->bitlen < cnt) {
+		if (state->srccnt == state->srclen) {
+			state->overrun = true;
+			return 0;
+		}
+		
+		/* Load 8 more bits */
+		val |= ((uint64_t) state->src[state->srccnt]) << state->bitlen;
+		state->srccnt++;
+		state->bitlen += 8;
+	}
+	
+	/* Update bits in the buffer */
+	state->bitbuf = (uint32_t) (val >> cnt);
+	state->bitlen -= cnt;
+	
+	return ((uint32_t) (val & ((1 << cnt) - 1)));
+}
+
+/** Decode WebP header
+ *
+ * @param[in]  data Memory representation of WebP.
+ * @param[in]  size Size of the representation (in bytes).
+ * @param[out] webp Decoded WebP.
+ *
+ * @return True on succesful decoding.
+ * @return False on failure.
+ *
+ */
+static bool decode_webp_header(void *data, size_t size, webp_t *webp)
+{
+	/* Headers sanity check */
+	if ((size < sizeof(riff_header_t)) ||
+	    (size - sizeof(riff_header_t) < sizeof(webp_header_t)))
+		return false;
+	
+	riff_header_t *riff_header = (riff_header_t *) data;
+	if (riff_header->fourcc != FOURCC_RIFF)
+		return false;
+	
+	/* Check payload size */
+	size_t payload_size = uint32_t_le2host(riff_header->payload_size);
+	if (payload_size + sizeof(riff_header_t) > size)
+		return false;
+	
+	data += sizeof(riff_header_t);
+	webp_header_t *webp_header = (webp_header_t *) data;
+	if (webp_header->fourcc != FOURCC_WEBP)
+		return false;
+	
+	/* Only lossless encoding supported so far */
+	if (webp_header->encoding != FOURCC_WEBP_LOSSLESS)
+		return false;
+	
+	webp->stream_size = uint32_t_le2host(webp_header->stream_size);
+	if (webp->stream_size + sizeof(riff_header_t) +
+	    sizeof(webp_header_t) > size)
+		return false;
+	
+	if (webp_header->signature != SIGNATURE_WEBP_LOSSLESS)
+		return false;
+	
+	data += sizeof(webp_header_t);
+	
+	/* Setup decoding state */
+	webp->src = (uint8_t *) data;
+	webp->srclen = webp->stream_size - 1;
+	webp->srccnt = 0;
+	webp->bitbuf = 0;
+	webp->bitlen = 0;
+	webp->overrun = false;
+	
+	/* Decode the rest of the metadata */
+	webp->width = get_bits(webp, 14) + 1;
+	CHECK_OVERRUN(*webp, false);
+	
+	webp->height = get_bits(webp, 14) + 1;
+	CHECK_OVERRUN(*webp, false);
+	
+	webp->alpha_used = get_bits(webp, 1);
+	CHECK_OVERRUN(*webp, false);
+	
+	webp->version = get_bits(webp, 3);
+	CHECK_OVERRUN(*webp, false);
+	
+	if (webp->version != 0)
+		return false;
+	
+	return true;
+}
+
+/** Decode WebP format
+ *
+ * Decode WebP format and create a surface from it. The supported
+ * variants of WebP are currently limited to losslessly compressed
+ * ARGB images.
+ *
+ * @param[in] data  Memory representation of WebP.
+ * @param[in] size  Size of the representation (in bytes).
+ * @param[in] flags Surface creation flags.
+ *
+ * @return Newly allocated surface with the decoded content.
+ * @return NULL on error or unsupported format.
+ *
+ */
+surface_t *decode_webp(void *data, size_t size, surface_flags_t flags)
+{
+	webp_t webp;
+	if (!decode_webp_header(data, size, &webp))
+		return NULL;
+	
+	bool transform_present = false;
+	
+	do {
+		transform_present = get_bits(&webp, 1);
+		CHECK_OVERRUN(webp, NULL);
+		
+		if (transform_present) {
+			webp_transform_t transform = get_bits(&webp, 2);
+			CHECK_OVERRUN(webp, NULL);
+			
+			if (transform == TRANSFORM_PREDICTOR) {
+				// FIXME TODO
+			} else
+				return NULL;
+			
+			// FIXME: decode other transforms
+		}
+	} while (transform_present);
+	
+	// FIXME: decode image data
+	
+	return NULL;
+}
+
+/** Encode WebP format
+ *
+ * Encode WebP format into an array.
+ *
+ * @param[in]  surface Surface to be encoded into WebP.
+ * @param[out] pdata   Pointer to the resulting array.
+ * @param[out] psize   Pointer to the size of the resulting array.
+ *
+ * @return True on succesful encoding.
+ * @return False on failure.
+ *
+ */
+bool encode_webp(surface_t *surface, void **pdata, size_t *psize)
+{
+	// TODO
+	return false;
+}
+
+/** @}
+ */
Index: uspace/lib/draw/codec/webp.h
===================================================================
--- uspace/lib/draw/codec/webp.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/draw/codec/webp.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014 Martin Decky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup draw
+ * @{
+ */
+/**
+ * @file
+ */
+
+#ifndef DRAW_CODEC_WEBP_H_
+#define DRAW_CODEC_WEBP_H_
+
+#include <sys/types.h>
+#include "../surface.h"
+
+extern surface_t *decode_webp(void *, size_t, surface_flags_t);
+extern bool encode_webp(surface_t *, void **, size_t *);
+
+#endif
+
+/** @}
+ */
Index: uspace/lib/trackmod/Makefile
===================================================================
--- uspace/lib/trackmod/Makefile	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/trackmod/Makefile	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -32,5 +32,6 @@
 SOURCES = \
 	protracker.c \
-	trackmod.c
+	trackmod.c \
+	xm.c
 
 include $(USPACE_PREFIX)/Makefile.common
Index: uspace/lib/trackmod/protracker.c
===================================================================
--- uspace/lib/trackmod/protracker.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/trackmod/protracker.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -113,4 +113,140 @@
 }
 
+
+/** Decode pattern cell.
+ *
+ * @param pattern Pattern
+ * @param row     Row number
+ * @param channel Channel number
+ * @param cell    Place to store decoded cell
+ */
+static void protracker_decode_cell(uint32_t cdata, trackmod_cell_t *cell)
+{
+	uint32_t code;
+
+	code = uint32_t_be2host(cdata);
+	cell->period = (code >> (4 * 4)) & 0xfff;
+	cell->instr = (((code >> (7 * 4)) & 0xf) << 4) |
+	    ((code >> (3 * 4)) & 0xf);
+	cell->effect = code & 0xfff;
+}
+
+/** Load Protracker patterns.
+ *
+ * @param f      File to read from
+ * @param module Module being loaded to
+ * @return       EOK on success, ENOMEM if out of memory, EIO on I/O error.
+ */
+static int protracker_load_patterns(FILE *f, trackmod_module_t *module)
+{
+	size_t cells;
+	size_t i, j;
+	int rc;
+	size_t nread;
+	uint32_t *buf = NULL;
+
+	cells = module->channels * protracker_pattern_rows;
+	buf = calloc(sizeof(uint32_t), cells);
+
+	if (buf == NULL) {
+		rc = ENOMEM;
+		goto error;
+	}
+
+	for (i = 0; i < module->patterns; i++) {
+		module->pattern[i].rows = protracker_pattern_rows;
+		module->pattern[i].channels = module->channels;
+		module->pattern[i].data = calloc(sizeof(trackmod_cell_t), cells);
+		if (module->pattern[i].data == NULL) {
+			rc = ENOMEM;
+			goto error;
+		}
+
+		nread = fread(buf, sizeof(uint32_t), cells, f);
+		if (nread != cells) {
+			printf("Error reading pattern.\n");
+			rc = EIO;
+			goto error;
+		}
+
+		/* Decode cells */
+		for (j = 0; j < cells; j++) {
+			protracker_decode_cell(buf[j],
+			    &module->pattern[i].data[j]);
+		}
+	}
+
+	free(buf);
+	return EOK;
+error:
+	free(buf);
+	return rc;
+}
+
+/** Load protracker samples.
+ *
+ * @param f      File being read from
+ * @param sample Sample header
+ * @param module Module being loaded to
+ * @return       EOk on success, ENOMEM if out of memory, EIO on I/O error.
+ */
+static int protracker_load_samples(FILE *f, protracker_smp_t *smp,
+    trackmod_module_t *module)
+{
+	int rc;
+	size_t i;
+	uint8_t ftval;
+	size_t nread;
+	trackmod_sample_t *sample;
+
+	for (i = 0; i < module->instrs; i++) {
+		module->instr[i].samples = 1;
+		module->instr[i].sample = calloc(1, sizeof(trackmod_sample_t));
+		if (module->instr[i].sample == NULL) {
+			printf("Error allocating sample.\n");
+			rc = ENOMEM;
+			goto error;
+		}
+
+		sample = &module->instr[i].sample[0];
+		sample->length =
+		    uint16_t_be2host(smp[i].length) * 2;
+		sample->bytes_smp = 1;
+		sample->data = calloc(1, sample->length);
+		if (sample->data == NULL) {
+			printf("Error allocating sample.\n");
+			rc = ENOMEM;
+			goto error;
+		}
+
+		nread = fread(sample->data, 1, sample->length, f);
+		if (nread != sample->length) {
+			printf("Error reading sample.\n");
+			rc = EIO;
+			goto error;
+		}
+
+		sample->def_vol = smp[i].def_vol;
+
+		sample->loop_start =
+		    uint16_t_be2host(smp[i].loop_start) * 2;
+		sample->loop_len =
+		    uint16_t_be2host(smp[i].loop_len) * 2;
+		if (sample->loop_len <= 2)
+			sample->loop_type = tl_no_loop;
+		else
+			sample->loop_type = tl_forward_loop;
+
+		/* Finetune is a 4-bit signed value. */
+		ftval = smp[i].finetune & 0x0f;
+		sample->finetune =
+			(ftval & 0x8) ? (ftval & 0x7) - 8 : ftval;
+	}
+
+	return EOK;
+error:
+	return rc;
+}
+
 /** Load protracker module.
  *
@@ -128,10 +264,9 @@
 	protracker_order_list_t *order_list;
 	protracker_smp_t *sample;
-	size_t nread;
 	size_t samples;
 	size_t channels;
 	size_t patterns;
-	size_t cells;
-	size_t i, j;
+	size_t i;
+	size_t nread;
 	int rc;
 
@@ -192,7 +327,7 @@
 	module->channels = channels;
 
-	module->samples = samples;
-	module->sample = calloc(sizeof(trackmod_sample_t), samples);
-	if (module->sample == NULL) {
+	module->instrs = samples;
+	module->instr = calloc(sizeof(trackmod_instr_t), samples);
+	if (module->instr == NULL) {
 		printf("Out of memory.\n");
 		rc = ENOMEM;
@@ -221,57 +356,23 @@
 	}
 
+	/* The 'mark' byte may or may not contain a valid restart position */
+	if (order_list->mark < order_list->order_list_len) {
+		module->restart_pos = order_list->mark;
+	}
+
 	/* Load patterns */
-
-	cells = channels * protracker_pattern_rows;
-
-	for (i = 0; i < patterns; i++) {
-		module->pattern[i].rows = protracker_pattern_rows;
-		module->pattern[i].channels = channels;
-		module->pattern[i].data = calloc(sizeof(uint32_t), cells);
-
-		nread = fread(module->pattern[i].data,
-		    sizeof(uint32_t), cells, f);
-		if (nread != cells) {
-			printf("Error reading pattern.\n");
-			rc = EIO;
-			goto error;
-		}
-
-		/* Convert byte order */
-		for (j = 0; j < cells; j++) {
-			module->pattern[i].data[j] = uint32_t_be2host(
-			    module->pattern[i].data[j]);
-		}
-	}
+	rc = protracker_load_patterns(f, module);
+	if (rc != EOK)
+		goto error;
 
 	/* Load samples */
-	for (i = 0; i < samples; i++) {
-		module->sample[i].length =
-		    uint16_t_be2host(sample[i].length) * 2;
-		module->sample[i].data = calloc(1, module->sample[i].length);
-		if (module->sample[i].data == NULL) {
-			printf("Error allocating sample.\n");
-			rc = ENOMEM;
-			goto error;
-		}
-
-		nread = fread(module->sample[i].data, 1, module->sample[i].length,
-			f);
-		if (nread != module->sample[i].length) {
-			printf("Error reading sample.\n");
-			rc = EIO;
-			goto error;
-		}
-
-		module->sample[i].def_vol = sample[i].def_vol;
-		module->sample[i].loop_start =
-		    uint16_t_be2host(sample[i].loop_start) * 2;
-		module->sample[i].loop_len =
-		    uint16_t_be2host(sample[i].loop_len) * 2;
-		if (module->sample[i].loop_len <= 2)
-			module->sample[i].loop_len = 0;
-	}
+	rc = protracker_load_samples(f, sample, module);
+	if (rc != EOK)
+		goto error;
 
 	(void) fclose(f);
+
+	module->def_bpm = protracker_def_bpm;
+	module->def_tpr = protracker_def_tpr;
 
 	*rmodule = module;
Index: uspace/lib/trackmod/trackmod.c
===================================================================
--- uspace/lib/trackmod/trackmod.c	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/trackmod/trackmod.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -40,5 +40,7 @@
 
 #include "macros.h"
+#include "protracker.h"
 #include "trackmod.h"
+#include "xm.h"
 
 /** Tunables */
@@ -52,11 +54,35 @@
 	base_clock = 8363 * 428,
 	/** Maximum sample volume */
-	vol_max = 63,
-	/** Default TPR */
-	def_tpr = 6,
-	/** Default BPM */
-	def_bpm = 125
+	vol_max = 64,
+	/** Minimum period */
+	period_min = 113,
+	/** Maxium period */
+	period_max = 856
 };
 
+/** Table for finetune computation.
+  *
+  * Finetune is a number ft in [-8 .. 7]. The pitch should be adjusted by
+  * ft/8 semitones. To adjust pitch by 1/8 semitone down we can mutiply the
+  * period by 2^(1/12/8) =. 1.0072, one semitone up: 2^-(1/12/8) =. 0.9928,
+  * to adjust by ft/8 semitones, multiply by 2^(-ft/12/8).
+  *
+  * finetune_factor[ft] := 10000 * 2^(-ft/12/8)
+  * res_period = clip(period * fineture_factor[ft+8] / 10000)
+  */
+static unsigned finetune_factor[16] = {
+	10595, 10518, 10443, 10368, 10293, 10219, 10145, 10072,
+	10000,  9928,  9857,  9786,  9715,  9645,  9576,  9507
+};
+
+static unsigned period_table[12 * 8] = {
+     907,900,894,887,881,875,868,862,856,850,844,838,832,826,820,814,
+     808,802,796,791,785,779,774,768,762,757,752,746,741,736,730,725,
+     720,715,709,704,699,694,689,684,678,675,670,665,660,655,651,646,
+     640,636,632,628,623,619,614,610,604,601,597,592,588,584,580,575,
+     570,567,563,559,555,551,547,543,538,535,532,528,524,520,516,513,
+     508,505,502,498,494,491,487,484,480,477,474,470,467,463,460,457
+};
+
 static size_t trackmod_get_next_ord_idx(trackmod_modplay_t *);
 
@@ -70,4 +96,16 @@
 }
 
+/** Destroy instrument.
+ *
+ * @param instr Intrument
+ */
+static void trackmod_instr_destroy(trackmod_instr_t *instr)
+{
+	size_t i;
+
+	for (i = 0; i < instr->samples; i++)
+		trackmod_sample_destroy(&instr->sample[i]);
+}
+
 /** Destroy pattern.
  *
@@ -97,8 +135,8 @@
 
 	/* Destroy samples */
-	if (module->sample != NULL) {
-		for (i = 0; i < module->samples; i++)
-			trackmod_sample_destroy(&module->sample[i]);
-		free(module->sample);
+	if (module->instr != NULL) {
+		for (i = 0; i < module->instrs; i++)
+			trackmod_instr_destroy(&module->instr[i]);
+		free(module->instr);
 	}
 
@@ -114,4 +152,17 @@
 }
 
+int trackmod_module_load(char *fname, trackmod_module_t **rmodule)
+{
+	int rc;
+
+	rc = trackmod_xm_load(fname, rmodule);
+	if (rc == EOK)
+		return EOK;
+
+	rc = trackmod_protracker_load(fname, rmodule);
+	return rc;
+}
+
+
 /** Return current pattern.
  *
@@ -137,14 +188,34 @@
     size_t row, size_t channel, trackmod_cell_t *cell)
 {
-	uint32_t code;
-
-	code = pattern->data[row * pattern->channels + channel];
-	cell->period = (code >> (4 * 4)) & 0xfff;
-	cell->sample = (((code >> (7 * 4)) & 0xf) << 4) |
-	    ((code >> (3 * 4)) & 0xf);
-	cell->effect = code & 0xfff;
-}
-
-/** Process note (period, sample index)
+	*cell = pattern->data[row * pattern->channels + channel];
+}
+
+/** Compute floor(a / b), and the remainder.
+ *
+ * Unlike standard integer division this rounds towars negative infinity,
+ * not towards zero.
+ *
+ * @param a Dividend
+ * @param b Divisor
+ * @param quot Place to store 'quotient' (floor (a/b))
+ * @param rem Place to store 'remainder' (a - floor(a/b) * b)
+ */
+static void divmod_floor(int a, int b, int *quot, int *rem)
+{
+	if (b < 0) {
+		a = -a;
+		b = -b;
+	}
+
+	if (a >= 0) {
+		*quot = a / b;
+		*rem = a % b;
+	} else {
+		*quot = - (-a + (b - 1)) / b;
+		*rem = a - (*quot * b);
+	}
+}
+
+/** Process note (period)
  *
  * @param modplay Module playback
@@ -156,12 +227,75 @@
 {
 	trackmod_chan_t *chan = &modplay->chan[i];
-	size_t smpidx;
-
-	smpidx = (cell->sample - 1) % modplay->module->samples;
-	chan->sample = &modplay->module->sample[smpidx];
+	int period;
+	int pitch;
+	int octave;
+	int opitch;
+
+	if (chan->sample == NULL)
+		return;
+
+	if (cell->period == 0) {
+		pitch = 8 * (cell->note + chan->sample->rel_note) +
+		    chan->sample->finetune;
+		divmod_floor(pitch, 8 * 12, &octave, &opitch);
+
+		if (octave >= 0)
+			period = period_table[opitch] * 8 / (1 << octave);
+		else
+			period = period_table[opitch] * 8 * (1 << (-octave));
+	} else {
+		period = cell->period;
+		period = period *
+		    finetune_factor[chan->sample->finetune + 8] / 10000;
+		if (period > period_max)
+			period = period_max;
+		if (period < period_min)
+			period = period_min;
+	}
+
+	chan->period_new = period;
+}
+
+/** Process instrument number (this is what triggers the note playback)
+ *
+ * @param modplay Module playback
+ * @param i       Channel number
+ * @param cell    Cell
+ */
+static void trackmod_process_instr(trackmod_modplay_t *modplay, size_t i,
+    trackmod_cell_t *cell)
+{
+	trackmod_chan_t *chan = &modplay->chan[i];
+	trackmod_instr_t *instr;
+	size_t iidx;
+	size_t sidx;
+
+	if (cell->instr == 0)
+		return;
+
+	iidx = (cell->instr - 1) % modplay->module->instrs;
+	instr = &modplay->module->instr[iidx];
+	sidx = instr->key_smp[cell->note] % instr->samples;
+	chan->sample = &instr->sample[sidx];
 	chan->smp_pos = 0;
 	chan->lsmp = 0;
-	chan->period = cell->period;
+
 	chan->volume = modplay->chan[i].sample->def_vol;
+}
+
+/** Process keyoff note
+ *
+ * @param modplay Module playback
+ * @param i       Channel number
+ * @param cell    Cell
+ */
+static void trackmod_process_keyoff_note(trackmod_modplay_t *modplay, size_t i)
+{
+	trackmod_chan_t *chan = &modplay->chan[i];
+
+	chan->sample = NULL;
+	chan->period = 0;
+	chan->smp_pos = 0;
+	chan->lsmp = 0;
 }
 
@@ -175,5 +309,5 @@
     uint8_t param)
 {
-	modplay->chan[chan].volume = param & vol_max;
+	modplay->chan[chan].volume = param % (vol_max + 1);
 }
 
@@ -189,4 +323,8 @@
 	size_t next_idx;
 	trackmod_pattern_t *next_pat;
+	unsigned row;
+
+	/* Strangely the parameter is BCD */
+	row = (param >> 4) * 10 + (param & 0xf);
 
 	next_idx = trackmod_get_next_ord_idx(modplay);
@@ -194,5 +332,5 @@
 
 	modplay->pat_break = true;
-	modplay->pat_break_row = param % next_pat->rows;
+	modplay->pat_break_row = row % next_pat->rows;
 }
 
@@ -212,4 +350,190 @@
 }
 
+/** Process Fine volume slide down effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_fine_vol_slide_down(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param)
+{
+	int nv;
+
+	nv = modplay->chan[chan].volume - param;
+	if (nv < 0)
+		nv = 0;
+	modplay->chan[chan].volume = nv;
+}
+
+/** Process Fine volume slide up effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_fine_vol_slide_up(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param)
+{
+	int nv;
+
+	nv = modplay->chan[chan].volume + param;
+	if (nv > vol_max)
+		nv = vol_max;
+	modplay->chan[chan].volume = nv;
+}
+
+/** Process Volume slide effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_vol_slide(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param)
+{
+	if ((param & 0xf0) != 0)
+		modplay->chan[chan].vol_slide = param >> 4;
+	else
+		modplay->chan[chan].vol_slide = -(int)(param & 0xf);
+}
+
+/** Process Volume slide down effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_vol_slide_down(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param4)
+{
+	modplay->chan[chan].vol_slide = -(int)param4;
+}
+
+/** Process Volume slide up effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_vol_slide_up(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param4)
+{
+	modplay->chan[chan].vol_slide = param4;
+}
+
+/** Process Fine portamento down effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_fine_porta_down(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param)
+{
+	int np;
+
+	np = modplay->chan[chan].period + param;
+	if (np > period_max)
+		np = period_max;
+	modplay->chan[chan].period = np;
+}
+
+/** Process Fine portamento up effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_fine_porta_up(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param)
+{
+	int np;
+
+	np = modplay->chan[chan].period - param;
+	if (np < period_min)
+		np = period_min;
+	modplay->chan[chan].period = np;
+}
+
+/** Process Portamento down effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_porta_down(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param)
+{
+	modplay->chan[chan].portamento = -(int)param;
+}
+
+/** Process Portamento up effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_porta_up(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param)
+{
+	modplay->chan[chan].portamento = param;
+}
+
+/** Process Tone portamento effect.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param param   Effect parameter
+ */
+static void trackmod_effect_tone_porta(trackmod_modplay_t *modplay,
+    size_t chan, uint8_t param)
+{
+	/* Set up tone portamento effect */
+	modplay->chan[chan].portamento = param;
+	if (modplay->chan[chan].period_new != 0)
+		modplay->chan[chan].period_tgt = modplay->chan[chan].period_new;
+
+	/* Prevent going directly to new period */
+	modplay->chan[chan].period_new = 0;
+}
+
+/** Process volume column.
+ *
+ * @param modplay Module playback
+ * @param chan    Channel number
+ * @param cell    Cell
+ */
+static void trackmod_process_volume(trackmod_modplay_t *modplay, size_t chan,
+    trackmod_cell_t *cell)
+{
+	uint8_t param4;
+
+	if (cell->volume >= 0x10 && cell->volume <= 0x10 + vol_max)
+		trackmod_effect_set_volume(modplay, chan, cell->volume - 0x10);
+
+	param4 = cell->volume & 0xf;
+
+	switch (cell->volume & 0xf0) {
+	case 0x60:
+		trackmod_effect_vol_slide_down(modplay, chan, param4);
+		break;
+	case 0x70:
+		trackmod_effect_vol_slide_up(modplay, chan, param4);
+		break;
+	case 0x80:
+		trackmod_effect_fine_vol_slide_down(modplay, chan, param4);
+		break;
+	case 0x90:
+		trackmod_effect_fine_vol_slide_up(modplay, chan, param4);
+		break;
+	case 0xf0:
+		trackmod_effect_tone_porta(modplay, chan, param4 << 4);
+		break;
+	default:
+		break;
+	}
+}
+
 /** Process effect.
  *
@@ -222,8 +546,21 @@
 {
 	uint8_t param8;
+	uint8_t param4;
 
 	param8 = cell->effect & 0xff;
 
 	switch (cell->effect & 0xf00) {
+	case 0x100:
+		trackmod_effect_porta_up(modplay, chan, param8);
+		break;
+	case 0x200:
+		trackmod_effect_porta_down(modplay, chan, param8);
+		break;
+	case 0x300:
+		trackmod_effect_tone_porta(modplay, chan, param8);
+		break;
+	case 0xa00:
+		trackmod_effect_vol_slide(modplay, chan, param8);
+		break;
 	case 0xc00:
 		trackmod_effect_set_volume(modplay, chan, param8);
@@ -238,4 +575,21 @@
 		break;
 	}
+
+	param4 = cell->effect & 0xf;
+
+	switch (cell->effect & 0xff0) {
+	case 0xe10:
+		trackmod_effect_fine_porta_up(modplay, chan, param4);
+		break;
+	case 0xe20:
+		trackmod_effect_fine_porta_down(modplay, chan, param4);
+		break;
+	case 0xea0:
+		trackmod_effect_fine_vol_slide_up(modplay, chan, param4);
+		break;
+	case 0xeb0:
+		trackmod_effect_fine_vol_slide_down(modplay, chan, param4);
+		break;
+	}
 }
 
@@ -249,8 +603,19 @@
     trackmod_cell_t *cell)
 {
-	if (cell->period != 0 && cell->sample != 0)
+	modplay->chan[chan].period_new = 0;
+
+	trackmod_process_instr(modplay, chan, cell);
+
+	if (cell->period != 0 || (cell->note != 0 && cell->note != keyoff_note)) {
 		trackmod_process_note(modplay, chan, cell);
-
+	} else if (cell->note == keyoff_note && cell->instr == 0) {
+		trackmod_process_keyoff_note(modplay, chan);
+	}
+
+	trackmod_process_volume(modplay, chan, cell);
 	trackmod_process_effect(modplay, chan, cell);
+
+	if (modplay->chan[chan].period_new != 0)
+		modplay->chan[chan].period = modplay->chan[chan].period_new;
 }
 
@@ -267,8 +632,16 @@
 	pattern = trackmod_cur_pattern(modplay);
 
+	if (modplay->debug)
+		printf("%02zx: ", modplay->row);
+
 	for (i = 0; i < modplay->module->channels; i++) {
 		trackmod_pattern_get_cell(pattern, modplay->row, i, &cell);
-		if (modplay->debug)
-			printf("%4d %02x %03x |", cell.period, cell.sample, cell.effect);
+
+		if (modplay->debug) {
+			printf("%4d %02x %02x %03x |", cell.period ?
+			    cell.period : cell.note, cell.instr,
+			    cell.volume, cell.effect);
+		}
+
 		trackmod_process_cell(modplay, i, &cell);
 	}
@@ -289,5 +662,5 @@
 	ord_idx = modplay->ord_idx + 1;
 	if (ord_idx >= modplay->module->ord_list_len)
-		ord_idx = 0; /* XXX */
+		ord_idx = modplay->module->restart_pos;
 
 	return ord_idx;
@@ -313,4 +686,56 @@
 }
 
+/** Clear effects at end of row. */
+static void trackmod_clear_effects(trackmod_modplay_t *modplay)
+{
+	size_t i;
+
+	for (i = 0; i < modplay->module->channels; i++) {
+		modplay->chan[i].vol_slide = 0;
+		modplay->chan[i].portamento = 0;
+	}
+}
+
+/** Process effects at beginning of tick. */
+static void trackmod_process_tick(trackmod_modplay_t *modplay)
+{
+	trackmod_chan_t *chan;
+	size_t i;
+	int nv;
+	int np;
+
+	for (i = 0; i < modplay->module->channels; i++) {
+		chan = &modplay->chan[i];
+
+		/* Volume slides */
+		nv = (int)chan->volume + chan->vol_slide;
+		if (nv < 0)
+			nv = 0;
+		if (nv > vol_max)
+			nv = vol_max;
+
+		chan->volume = nv;
+
+		/* Portamentos */
+		if (chan->period_tgt == 0) {
+			/* Up or down portamento */
+			np = (int)chan->period - chan->portamento;
+		} else {
+			/* Tone portamento */
+			if (chan->period_tgt < chan->period)
+				np = max((int)chan->period_tgt, (int)chan->period - chan->portamento);
+			else
+				np = min((int)chan->period_tgt, (int)chan->period + chan->portamento);
+		}
+
+/*		if (np < period_min)
+			np = period_min;
+		if (np > period_max)
+			np = period_max;
+*/
+		modplay->chan[i].period = np;
+	}
+}
+
 /** Advance to next row.
  *
@@ -320,4 +745,7 @@
 {
 	trackmod_pattern_t *pattern;
+
+	/* Clear effect state at end of row */
+	trackmod_clear_effects(modplay);
 
 	pattern = trackmod_cur_pattern(modplay);
@@ -328,4 +756,5 @@
 		trackmod_next_pattern(modplay);
 
+	trackmod_process_tick(modplay);
 	trackmod_process_row(modplay);
 }
@@ -341,4 +770,6 @@
 	if (modplay->tick >= modplay->tpr)
 		trackmod_next_row(modplay);
+	else
+		trackmod_process_tick(modplay);
 }
 
@@ -366,6 +797,6 @@
 	modplay->smp = 0;
 
-	modplay->tpr = def_tpr;
-	modplay->bpm = def_bpm;
+	modplay->tpr = module->def_tpr;
+	modplay->bpm = module->def_bpm;
 
 	modplay->chan = calloc(module->channels,
@@ -374,4 +805,5 @@
 		goto error;
 
+	trackmod_process_tick(modplay);
 	trackmod_process_row(modplay);
 
@@ -416,4 +848,27 @@
 }
 
+/** Get sample frame.
+ *
+ * Get frame at the specified sample position.
+ *
+ * @param sample Sample
+ * @param pos	 Position (frame index)
+ * @return	 Frame value
+ */
+int trackmod_sample_get_frame(trackmod_sample_t *sample, size_t pos)
+{
+	int8_t *i8p;
+	int16_t *i16p;
+
+	if (sample->bytes_smp == 1) {
+		i8p = (int8_t *)sample->data;
+		return i8p[pos];
+	} else {
+		/* chan->sample->bytes_smp == 2 */
+		i16p = (int16_t *)sample->data;
+		return i16p[pos] / 256; /* XXX Retain full precision */
+	}
+}
+
 /** Advance sample position to next frame.
  *
@@ -422,15 +877,19 @@
 static void chan_smp_next_frame(trackmod_chan_t *chan)
 {
-	chan->lsmp = chan->sample->data[chan->smp_pos];
+	chan->lsmp = trackmod_sample_get_frame(chan->sample, chan->smp_pos);
 	++chan->smp_pos;
 
-	if (chan->sample->loop_len == 0) {
-		/* No looping */
+	switch (chan->sample->loop_type) {
+	case tl_pingpong_loop:
+		/** XXX Pingpong loop */
+	case tl_no_loop:
+		/* No loop */
 		if (chan->smp_pos >= chan->sample->length) {
 			chan->sample = NULL;
 			chan->smp_pos = 0;
 		}
-	} else {
-		/** Looping */
+		break;
+	case tl_forward_loop:
+		/** Forward loop */
 		if (chan->smp_pos >= chan->sample->loop_start +
 		    chan->sample->loop_len) {
@@ -455,5 +914,5 @@
 	trackmod_chan_t *chan = &modplay->chan[cidx];
 
-	if (chan->sample == NULL)
+	if (chan->sample == NULL || chan->period == 0)
 		return 0;
 
@@ -464,6 +923,6 @@
 	 */
 	sl = (int)chan->lsmp * amp_factor * chan->volume / vol_max;
-	sn = (int)chan->sample->data[chan->smp_pos] * amp_factor *
-	    chan->volume / vol_max;
+	sn = (int)trackmod_sample_get_frame(chan->sample, chan->smp_pos) *
+	    amp_factor * chan->volume / vol_max;
 
 	period = (int)chan->period;
Index: uspace/lib/trackmod/trackmod.h
===================================================================
--- uspace/lib/trackmod/trackmod.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/trackmod/trackmod.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -40,4 +40,5 @@
 
 extern trackmod_module_t *trackmod_module_new(void);
+extern int trackmod_module_load(char *, trackmod_module_t **);
 extern void trackmod_module_destroy(trackmod_module_t *);
 extern int trackmod_modplay_create(trackmod_module_t *, unsigned,
@@ -45,4 +46,5 @@
 extern void trackmod_modplay_destroy(trackmod_modplay_t *);
 extern void trackmod_modplay_get_samples(trackmod_modplay_t *, void *, size_t);
+extern int trackmod_sample_get_frame(trackmod_sample_t *, size_t);
 
 #endif
Index: uspace/lib/trackmod/types/protracker.h
===================================================================
--- uspace/lib/trackmod/types/protracker.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/trackmod/types/protracker.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -47,5 +47,9 @@
 	protracker_olist_len = 128,
 	/** Number of rows in a pattern */
-	protracker_pattern_rows = 64
+	protracker_pattern_rows = 64,
+	/** Default TPR */
+	protracker_def_tpr = 6,
+	/** Default BPM */
+	protracker_def_bpm = 125
 };
 
Index: uspace/lib/trackmod/types/trackmod.h
===================================================================
--- uspace/lib/trackmod/types/trackmod.h	(revision ef3da5ad625620e40458132c67c6c8d18ecf31fe)
+++ uspace/lib/trackmod/types/trackmod.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -41,17 +41,63 @@
 #include <stdint.h>
 
+enum {
+	max_key = 96,
+	keyoff_note = 97
+};
+
+typedef enum {
+	/** No loop */
+	tl_no_loop,
+	/** Forward loop */
+	tl_forward_loop,
+	/** Pingpong loop */
+	tl_pingpong_loop
+} trackmod_looptype_t;
+
 /** Sample */
 typedef struct {
 	/** Length in frames */
 	size_t length;
+	/** Bytes per sample */
+	size_t bytes_smp;
 	/** Sample data */
-	int8_t *data;
+	void *data;
+	/** Loop type */
+	trackmod_looptype_t loop_type;
 	/** Loop start position in frames */
 	size_t loop_start;
-	/** Loop length in frames or 0 - no looping */
+	/** Loop length in frames (> 0) */
 	size_t loop_len;
 	/** Default volume (0..63) */
 	uint8_t def_vol;
+	/** Relative note */
+	int rel_note;
+	/** Finetune value (-8..7) in 1/8 semitones */
+	int finetune;
 } trackmod_sample_t;
+
+/** Instrument */
+typedef struct {
+	/** Number of samples */
+	size_t samples;
+	/** Samples */
+	trackmod_sample_t *sample;
+	/** Sample index for each key */
+	int key_smp[max_key];
+} trackmod_instr_t;
+
+/** Pattern cell */
+typedef struct {
+	/** Note */
+	unsigned note;
+	/** Sample period */
+	unsigned period;
+	/** Instrument number */
+	unsigned instr;
+	/** Volume */
+	uint8_t volume;
+	/** Effect */
+	uint16_t effect;
+} trackmod_cell_t;
 
 /** Pattern */
@@ -62,5 +108,5 @@
 	size_t channels;
 	/** Pattern data */
-	uint32_t *data;
+	trackmod_cell_t *data;
 } trackmod_pattern_t;
 
@@ -70,7 +116,7 @@
 	size_t channels;
 	/** Number of samples */
-	size_t samples;
-	/** Samples */
-	trackmod_sample_t *sample;
+	size_t instrs;
+	/** Instruments */
+	trackmod_instr_t *instr;
 	/** Number of patterns */
 	size_t patterns;
@@ -81,4 +127,10 @@
 	/** Order list */
 	size_t *ord_list;
+	/** Restart pos */
+	size_t restart_pos;
+	/** Default BPM */
+	unsigned def_bpm;
+	/** Default TPR */
+	unsigned def_tpr;
 } trackmod_module_t;
 
@@ -92,8 +144,17 @@
 	/** Sample position (clock ticks within frame) */
 	size_t smp_clk;
-	/** Period */
+	/** Current period */
 	unsigned period;
+	/** Period after note was processed, zero if no note */
+	unsigned period_new;
 	/** Volume */
 	uint8_t volume;
+	/** Volume slide amount */
+	int vol_slide;
+	/** Portamento amount (positive for tone and up portamento,
+	  * negative for down portamento. */
+	int portamento;
+	/** Tone portamento target period. */
+	unsigned period_tgt;
 } trackmod_chan_t;
 
@@ -132,14 +193,4 @@
 } trackmod_modplay_t;
 
-/** Pattern cell (decoded) */
-typedef struct {
-	/** Sample period */
-	unsigned period;
-	/** Sample number */
-	unsigned sample;
-	/** Effect */
-	unsigned effect;
-} trackmod_cell_t;
-
 #endif
 
Index: uspace/lib/trackmod/types/xm.h
===================================================================
--- uspace/lib/trackmod/types/xm.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/trackmod/types/xm.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2014 Jiri Svoboda
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup trackmod
+ * @{
+ */
+/**
+ * @file Extended Module (.xm) types.
+ */
+
+#ifndef TYPES_XM_H
+#define TYPES_XM_H
+
+#include <stdint.h>
+
+enum {
+	/** ID text (signature) */
+	xm_id_text_size = 17,
+	/** Module name size */
+	xm_mod_name_size = 20,
+	/** Tracker name size */
+	xm_tracker_name_size = 20,
+	/** Pattern order table size */
+	xm_pat_ord_table_size = 256,
+	/** Instrument name size */
+	xm_instr_name_size = 22,
+	/** Sample number for all notes table size */
+	xm_smp_note_size = 96,
+	/** Max number of volume envelope points */
+	xm_vol_env_points = 48,
+	/** Max number of panning envelope points */
+	xm_pan_env_points = 48,
+	/** Sample name size */
+	xm_smp_name_size = 22,
+	/** Keyoff note number */
+	xm_keyoff_note = 97
+};
+
+/** XM file header */
+typedef struct {
+	uint8_t id_text[xm_id_text_size];
+	/** Module name */
+	uint8_t name[xm_mod_name_size];
+	/** Text EOF mark */
+	uint8_t text_break;
+	/** Tracker name */
+	uint8_t tracker_name[xm_tracker_name_size];
+	/** File format version */
+	uint16_t version;
+	/** Header size */
+	uint32_t hdr_size;
+	/** Song length (in pattern order table) */
+	uint16_t song_len;
+	/** Restart position */
+	uint16_t restart_pos;
+	/** Number of channels */
+	uint16_t channels;
+	/** Number of patterns */
+	uint16_t patterns;
+	/** Number of intstruments */
+	uint16_t instruments;
+	/** Flags */
+	uint16_t flags;
+	/** Default tempo */
+	uint16_t def_tempo;
+	/** Default BPM */
+	uint16_t def_bpm;
+	uint8_t pat_ord_table[xm_pat_ord_table_size];
+} __attribute__((packed)) xm_hdr_t;
+
+typedef enum {
+	/** 1 = Linear frequency table, 0 = Amiga freq. table */
+	xmf_lftable = 0
+} xm_flags_bits_t;
+
+/** XM pattern header */
+typedef struct {
+	/** Pattern header size */
+	uint32_t hdr_size;
+	/** Packing type */
+	uint8_t pack_type;
+	/** Number of rows */
+	uint16_t rows;
+	/** Packed pattern data size */
+	uint16_t data_size;
+} __attribute__((packed)) xm_pattern_t;
+
+/** XM instrument header. */
+typedef struct {
+	/** Instrument size */
+	uint32_t size;
+	/** Instrument name */
+	uint8_t name[xm_instr_name_size];
+	/** Instrument type */
+	uint8_t instr_type;
+	/** Number of samples in instrument */
+	uint16_t samples;
+} __attribute__((packed)) xm_instr_t;
+
+/** XM additional instrument header if number of samples > 0 */
+typedef struct {
+	/** Sample header size */
+	uint32_t smp_hdr_size;
+	/** Sample number for all notes */
+	uint8_t smp_note[xm_smp_note_size];
+	/** Points for volume envelope */
+	uint8_t vol_point[xm_vol_env_points];
+	/** Points for panning envelope */
+	uint8_t pan_point[xm_pan_env_points];
+	/** Number of volume points */
+	uint8_t vol_points;
+	/** Number of panning points */
+	uint8_t pan_points;
+	/** Volume sustating point */
+	uint8_t vol_sustain;
+	/** Volume loop start point */
+	uint8_t vol_loop_start;
+	/** Volume loop end point */
+	uint8_t vol_loop_end;
+	/** Panning sustating point */
+	uint8_t pan_sustain;
+	/** Panning loop start point */
+	uint8_t pan_loop_start;
+	/** Panning loop end point */
+	uint8_t pan_loop_end;
+	/** Volume type */
+	uint8_t vol_type;
+	/** Panning type */
+	uint8_t pan_type;
+	/** Vibrato type */
+	uint8_t vibrato_type;
+	/** Vibrato sweep */
+	uint8_t vibrato_sweep;
+	/** Vibrato depth */
+	uint8_t vibrato_depth;
+	/** Vibrato rate */
+	uint8_t vibrato_rate;
+	/** Volume fadeout */
+	uint16_t vol_fadeout;
+	/** Reserved */
+	uint16_t res241;
+} __attribute__((packed)) xm_instr_ext_t;
+
+/** XM sample header */
+typedef struct {
+	/** Sample length */
+	uint32_t length;
+	/** Loop start */
+	uint32_t loop_start;
+	/** Loop length */
+	uint32_t loop_len;
+	/** Volume */
+	uint8_t volume;
+	/** Finetune */
+	int8_t finetune;
+	/** Sample type */
+	uint8_t smp_type;
+	/** Panning */
+	uint8_t panning;
+	/** Relative note number */
+	int8_t rel_note;
+	/** Reserved */
+	uint8_t res17;
+	/** Sample name */
+	uint8_t name[xm_smp_name_size];
+} __attribute__((packed)) xm_smp_t;
+
+/** XM sample type bits */
+typedef enum {
+	/** 16-bit sample data */
+	xmst_16_bit = 4,
+	/** Loop type (H) */
+	xmst_loop_type_h = 1,
+	/** Loop type (L) */
+	xmst_loop_type_l = 0
+} xm_smp_type_bits_t;
+
+/** Sample loop type */
+typedef enum {
+	/** No loop */
+	xmsl_no_loop = 0,
+	/** Forward loop */
+	xmsl_forward_loop = 1,
+	/** Ping-pong loop */
+	xmsl_pingpong_loop = 2
+} xm_smp_loop_type;
+
+#endif
+
+/** @}
+ */
Index: uspace/lib/trackmod/xm.c
===================================================================
--- uspace/lib/trackmod/xm.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/trackmod/xm.c	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,497 @@
+/*
+ * Copyright (c) 2014 Jiri Svoboda
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup trackmod
+ * @{
+ */
+/**
+ * @file Extended Module (.xm).
+ */
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <mem.h>
+
+#include "byteorder.h"
+#include "xm.h"
+#include "trackmod.h"
+#include "types/xm.h"
+
+static char xm_id_text[] = "Extended Module: ";
+
+/** Load XM order list
+ *
+ * @param xm_hdr XM header
+ * @param module Module
+ * @return EOK on success, EIO on format error, ENOMEM if out of memory.
+ */
+static int trackmod_xm_load_order_list(xm_hdr_t *xm_hdr, trackmod_module_t *module)
+{
+	int rc;
+	size_t i;
+
+	/* Order list */
+	module->ord_list_len = uint16_t_le2host(xm_hdr->song_len);
+	if (module->ord_list_len > xm_pat_ord_table_size) {
+		/* Invalid song length */
+		rc = EIO;
+		goto error;
+	}
+
+	module->ord_list = calloc(sizeof(size_t), module->ord_list_len);
+	if (module->ord_list == NULL) {
+		printf("Out of memory.\n");
+		rc = ENOMEM;
+		goto error;
+	}
+
+	for (i = 0; i < module->ord_list_len; i++) {
+		module->ord_list[i] = xm_hdr->pat_ord_table[i];
+	}
+
+	module->restart_pos = uint16_t_le2host(xm_hdr->restart_pos);
+	if (module->restart_pos >= module->ord_list_len) {
+		rc = EIO;
+		goto error;
+	}
+
+	return EOK;
+error:
+	return rc;
+}
+
+/** Decode XM pattern.
+ *
+ * @param data    Packed pattern data
+ * @param pattern Pattern to load to
+ * @return	  EOK on success, EINVAL if there is error in the coded data.
+ */
+static int trackmod_xm_decode_pattern(uint8_t *data, size_t dsize,
+    trackmod_pattern_t *pattern)
+{
+	size_t cells;
+	size_t i;
+	size_t si;
+	uint8_t mask;
+
+	cells = pattern->rows * pattern->channels;
+	si = 0;
+
+	for (i = 0; i < cells; i++) {
+		if (si >= dsize)
+			return EINVAL;
+
+		if ((data[si] & 0x80) != 0) {
+			mask = data[si++] & 0x1f;
+		} else {
+			mask = 0x1f;
+		}
+
+		/* Note */
+		if ((mask & 0x1) != 0) {
+			if (si >= dsize)
+				return EINVAL;
+			pattern->data[i].note = data[si++] & 0x7f;
+		}
+
+		/* Instrument */
+		if ((mask & 0x2) != 0) {
+			if (si >= dsize)
+				return EINVAL;
+			pattern->data[i].instr = data[si++];
+		}
+
+		/* Volume */
+		if ((mask & 0x4) != 0) {
+			if (si >= dsize)
+				return EINVAL;
+			pattern->data[i].volume = data[si++];
+		}
+
+		/* Effect type */
+		if ((mask & 0x8) != 0) {
+			if (si >= dsize)
+				return EINVAL;
+			pattern->data[i].effect = (unsigned)data[si++] << 8;
+		}
+
+		/* Effect parameter */
+		if ((mask & 0x10) != 0) {
+			if (si >= dsize)
+				return EINVAL;
+			pattern->data[i].effect |= data[si++];
+		}
+	}
+
+	/* Note: Ignoring any extra data */
+
+	return EOK;
+}
+
+/** Load XM patterns
+ *
+ * @param file File
+ * @param module Module
+ * @return EOK on success, EIO on format error, ENOMEM if out of memory.
+ */
+static int trackmod_xm_load_patterns(FILE *f, trackmod_module_t *module)
+{
+	size_t i;
+	size_t hdr_size;
+	uint8_t pack_type;
+	size_t rows;
+	size_t data_size;
+	ssize_t nread;
+	xm_pattern_t pattern;
+	uint8_t *buf = NULL;
+	long seek_amount;
+	int rc;
+
+	module->pattern = calloc(sizeof(trackmod_pattern_t), module->patterns);
+	if (module->pattern == NULL) {
+		rc = ENOMEM;
+		goto error;
+	}
+
+	for (i = 0; i < module->patterns; i++) {
+		rc = fread(&pattern, 1, sizeof(xm_pattern_t), f);
+		if (rc != sizeof(xm_pattern_t)) {
+			rc = EIO;
+			goto error;
+		}
+
+		hdr_size = (size_t)uint32_t_le2host(pattern.hdr_size);
+		pack_type = pattern.pack_type;
+		rows = uint16_t_le2host(pattern.rows);
+		data_size = uint16_t_le2host(pattern.data_size);
+
+		if (pack_type != 0) {
+			rc = EIO;
+			goto error;
+		}
+
+		/* Jump to end of pattern header */
+		seek_amount = (long)hdr_size - (long)sizeof(xm_pattern_t);
+		if (fseek(f, seek_amount, SEEK_CUR) < 0) {
+			rc = EIO;
+			goto error;
+		}
+
+		module->pattern[i].rows = rows;
+		module->pattern[i].channels = module->channels;
+		module->pattern[i].data = calloc(sizeof(trackmod_cell_t),
+		    rows * module->channels);
+
+		if (module->pattern[i].data == NULL) {
+			rc = ENOMEM;
+			goto error;
+		}
+
+		buf = calloc(1, data_size);
+		if (buf == NULL) {
+			rc = ENOMEM;
+			goto error;
+		}
+
+		nread = fread(buf, 1, data_size, f);
+		if (nread != (ssize_t)data_size) {
+			rc = EIO;
+			goto error;
+		}
+
+		rc = trackmod_xm_decode_pattern(buf, data_size,
+		    &module->pattern[i]);
+		if (rc != EOK)
+			goto error;
+
+		free(buf);
+		buf = NULL;
+	}
+
+	return EOK;
+error:
+	free(buf);
+	return rc;
+}
+
+/** Decode XM sample data.
+ *
+ * XM sample data is delta-encoded. Undo the delta encoding and convert
+ * byte order.
+ */
+static void trackmod_xm_decode_sample_data(trackmod_sample_t *sample)
+{
+	size_t i;
+	int8_t *i8p;
+	int16_t *i16p;
+	int8_t cur8;
+	int16_t cur16;
+
+	if (sample->bytes_smp == 1) {
+		cur8 = 0;
+		i8p = (int8_t *)sample->data;
+
+		for (i = 0; i < sample->length; i++) {
+			cur8 = cur8 + i8p[i];
+			i8p[i] = cur8;
+		}
+	} else {
+		cur16 = 0;
+		i16p = (int16_t *)sample->data;
+
+		for (i = 0; i < sample->length; i++) {
+			cur16 = cur16 + (int16_t)uint16_t_le2host(i16p[i]);
+			i16p[i] = cur16;
+		}
+	}
+}
+
+/** Load XM instruments
+ *
+ * @param file File
+ * @param module Module
+ * @return EOK on success, EIO on format error, ENOMEM if out of memory.
+ */
+static int trackmod_xm_load_instruments(xm_hdr_t *xm_hdr, FILE *f,
+    trackmod_module_t *module)
+{
+	size_t i, j;
+	xm_instr_t instr;
+	xm_instr_ext_t instrx;
+	xm_smp_t smp;
+	size_t samples;
+	size_t instr_size;
+	size_t smp_size;
+	size_t smp_hdr_size;
+	ssize_t nread;
+	uint8_t ltype;
+	trackmod_sample_t *sample;
+	void *smp_data;
+	long pos;
+	int rc;
+
+	module->instrs = uint16_t_le2host(xm_hdr->instruments);
+	module->instr = calloc(module->instrs, sizeof(trackmod_instr_t));
+	if (module->instr == NULL)
+		return ENOMEM;
+
+	for (i = 0; i < module->instrs; i++) {
+		pos = ftell(f);
+		rc = fread(&instr, 1, sizeof(xm_instr_t), f);
+		if (rc != sizeof(xm_instr_t)) {
+			rc = EIO;
+			goto error;
+		}
+
+		samples = uint16_t_le2host(instr.samples);
+		instr_size = (size_t)uint32_t_le2host(instr.size);
+
+		if (samples > 0) {
+			rc = fread(&instrx, 1, sizeof(xm_instr_ext_t), f);
+			if (rc != sizeof(xm_instr_ext_t)) {
+				rc = EIO;
+				goto error;
+			}
+
+			smp_hdr_size = uint32_t_le2host(instrx.smp_hdr_size);
+
+			for (j = 0; j < xm_smp_note_size; j++) {
+				module->instr[i].key_smp[j] =
+				    instrx.smp_note[j];
+			}
+
+			module->instr[i].samples = samples;
+			module->instr[i].sample = calloc(samples,
+			    sizeof(trackmod_sample_t));
+			if (module->instr[i].sample == NULL) {
+				rc = ENOMEM;
+				goto error;
+			}
+		}
+
+		if (fseek(f, pos + instr_size, SEEK_SET) < 0) {
+			rc = EIO;
+			goto error;
+		}
+
+		for (j = 0; j < samples; j++) {
+			sample = &module->instr[i].sample[j];
+			pos = ftell(f);
+
+			rc = fread(&smp, 1, sizeof(xm_smp_t), f);
+			if (rc != sizeof(xm_smp_t)) {
+				rc = EIO;
+				goto error;
+			}
+
+			smp_size = (size_t)uint32_t_le2host(smp.length);
+
+			smp_data = calloc(smp_size, 1);
+			if (smp_data == NULL) {
+				rc = ENOMEM;
+				goto error;
+			}
+
+			if (fseek(f, pos + smp_hdr_size, SEEK_SET) < 0) {
+				rc = EIO;
+				goto error;
+			}
+
+			nread = fread(smp_data, 1, smp_size, f);
+			if (nread != (ssize_t)smp_size) {
+				rc = EIO;
+				goto error;
+			}
+
+			if (smp.smp_type & (1 << xmst_16_bit)) {
+				sample->bytes_smp = 2;
+			} else {
+				sample->bytes_smp = 1;
+			}
+
+			sample->data = smp_data;
+			sample->length = smp_size / sample->bytes_smp;
+
+			ltype = smp.smp_type & 0x3;
+			switch (ltype) {
+			case xmsl_no_loop:
+				sample->loop_type = tl_no_loop;
+				break;
+			case xmsl_forward_loop:
+				sample->loop_type = tl_forward_loop;
+				break;
+			case xmsl_pingpong_loop:
+				sample->loop_type = tl_pingpong_loop;
+				break;
+			default:
+				rc = EIO;
+				goto error;
+			}
+
+			sample->loop_start =
+			    uint32_t_le2host(smp.loop_start) / sample->bytes_smp;
+			sample->loop_len =
+			    uint32_t_le2host(smp.loop_len) / sample->bytes_smp;
+			sample->def_vol = 0x40;
+			sample->rel_note = smp.rel_note;
+			sample->finetune = smp.finetune / 2;
+
+			trackmod_xm_decode_sample_data(sample);
+		}
+	}
+
+	return EOK;
+error:
+	return rc;
+}
+
+/** Load extended module.
+ *
+ * @param fname   File name
+ * @param rmodule Place to store pointer to newly loaded module.
+ * @return        EOK on success, ENONEM if out of memory, EIO on I/O error
+ *                or if any error is found in the format of the file.
+ */
+int trackmod_xm_load(char *fname, trackmod_module_t **rmodule)
+{
+	FILE *f = NULL;
+	trackmod_module_t *module = NULL;
+	xm_hdr_t xm_hdr;
+	size_t nread;
+	size_t hdr_size;
+	int rc;
+
+	f = fopen(fname, "rb");
+	if (f == NULL) {
+		printf("Error opening file.\n");
+		rc = EIO;
+		goto error;
+	}
+
+	nread = fread(&xm_hdr, 1, sizeof(xm_hdr_t), f);
+	if (nread < sizeof(xm_hdr_t)) {
+		printf("File too small.\n");
+		rc = EIO;
+		goto error;
+	}
+
+	if (memcmp(xm_hdr.id_text, xm_id_text, xm_id_text_size) != 0) {
+		rc = EIO;
+		goto error;
+	}
+
+	module = trackmod_module_new();
+	if (module == NULL) {
+		printf("Out of memory.\n");
+		rc = ENOMEM;
+		goto error;
+	}
+
+	module->channels = uint16_t_le2host(xm_hdr.channels);
+	module->patterns = uint16_t_le2host(xm_hdr.patterns);
+	module->ord_list_len = uint16_t_le2host(xm_hdr.song_len);
+
+	hdr_size = (size_t)uint32_t_le2host(xm_hdr.hdr_size)
+	    + offsetof(xm_hdr_t, hdr_size);
+
+	module->def_bpm = uint16_t_le2host(xm_hdr.def_bpm);
+	module->def_tpr = uint16_t_le2host(xm_hdr.def_tempo);
+
+	/* Jump to end of file header */
+	if (fseek(f, hdr_size, SEEK_SET) < 0) {
+		rc = EIO;
+		goto error;
+	}
+
+	rc = trackmod_xm_load_order_list(&xm_hdr, module);
+	if (rc != EOK)
+		goto error;
+
+	rc = trackmod_xm_load_patterns(f, module);
+	if (rc != EOK)
+		goto error;
+
+	rc = trackmod_xm_load_instruments(&xm_hdr, f, module);
+	if (rc != EOK)
+		goto error;
+
+	(void) fclose(f);
+
+	*rmodule = module;
+	return EOK;
+error:
+	if (module != NULL)
+		trackmod_module_destroy(module);
+	if (f != NULL)
+		(void) fclose(f);
+	return rc;
+}
+
+/** @}
+ */
Index: uspace/lib/trackmod/xm.h
===================================================================
--- uspace/lib/trackmod/xm.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
+++ uspace/lib/trackmod/xm.h	(revision b4121689a97413ef8da0250ed768bb2a55f82865)
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2014 Jiri Svoboda
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup trackmod
+ * @{
+ */
+/**
+ * @file Extended Module (.xm).
+ */
+
+#ifndef XM_H
+#define XM_H
+
+#include "types/trackmod.h"
+
+extern int trackmod_xm_load(char *, trackmod_module_t **);
+
+#endif
+
+/** @}
+ */
