updated code according to my latest comment (will have better commit message if everyone agrees this is the right way to do it)