redesigned to be more robust

Signed-off-by: Jan Dvořák <mordae@anilinux.org>