Moved defer f.Close() up so there is no chance of returning without closing and handled an error on f.Chmod