re-arrange code to make sure closing cursor after use