moved opening of $curout file outside of the loop and now close it