Bug fixes

@jirikuncar As discussed Friday here's the bug fixes. Note 3 last commits should not be be integrated yet.