Close old file and open new one if a new filename is passed in

Not sure if this is the best way to solve the problem in #3218, but it works.  Please comment if there's a preferred way.