if ($2 == !d4) {

should have been

if ($1 == !d4) {

same for the others