move open and close into the loop