Fixes #306 and adds a few small optimisations. Co-authored-by: Alexander Kriegisch <Alexander@Kriegisch.name> Signed-off-by: Alexander Kriegisch <Alexander@Kriegisch.name>