Fixed null checks and file writing