some raii and merging in changes from master manually