We don't really have to keep track of device opens/closes manually, since we can already check that by calling IsOpened() on the device. This also replaces some loops with for range loops.