Moved permissions setting at the start of the function.