#!/usr/bin/perl
use strict;
use warnings;

local $/ = undef;

for my $file (@ARGV) {
    open(my $fh, '+<', $file) or die "$file: $!\n";
    my $text = <$fh>;

    my $match = $text =~ s/
        (\#if    .* \n
         \#error .* \n
         \#endif .* \n
         \n*)
        (\#ifndef \s* (\S*) \s* \n
         \#define \s* \3    \s* \n
         \n)
        /$2$1/x;

    if ($match) {
        truncate $fh, 0;
        seek $fh, 0, 0;   
        print $fh $text;
    } else {
        print "$file: no match, not patched\n";
    }
    close($fh);
}
