added conditional checks to get around some errors when doing cleanup