Moved write action to end of function instead of defer