refactoring, both to avoid unnecessary repetition, as well as fixing bugs

Signed-off-by: Leo Bärring <leo.barring@gmail.com>