Move file assignment out from if statement. Somehow this fixes a wrong $file assignment.