Added extra checks to ensure directory exists