moved basename to after open, in case path gets clobbered