A bit of a refactor of the code, it should simplify the while thing including fixing the permissions