fixed logic of #467 and added tests