#!/usr/bin/perl
use strict;
use warnings;
(my $ME = $0) =~ s|.*/||;

# collect name/lineno pairs from output of gcc -W...
my $w = 'warning: format not a string literal and no format arguments';
my $lineno = {};
while (<>)
  {
    /^(\S+?\.c):(\d+): $w/
      or next;
    $lineno->{$1} ||= {};
    $lineno->{$1}->{$2} = undef
  }

foreach my $file (sort keys %$lineno)
  {
    # Read in all lines of $file.
    open FH, '<', $file
      or die "$ME: can't open `$file' for reading: $!\n";
    my @line = <FH>;
    close FH;

    my $h = $lineno->{$file};
    my @line_nums = sort { $a <=> $b } keys %$h;

    # Perform required substitutions.
    foreach my $k (@line_nums)
      {
        # Handle 3 cases:
        # 1: ... f(arg, arg2, ..., _("...")
        # 2: ... _("...")
        # 3: ... f(arg, arg2,\n
        #          _("...")
        # print "$file: $k: $line[$k-1]";
        $line[$k-1] =~ /(.*, )(_\(.*)/
          and ($line[$k-1] = qq!$1"%s", $2\n!), next;

        $line[$k-1] =~ /^( *)(_\(.*)/
          and ($line[$k-1] = qq!$1"%s", $2\n!), next;

        defined $line[$k] && $line[$k] =~ /^( *)(_\(.*)/
          and ($line[$k] = qq!$1"%s", $2\n!), next;

        warn "$file:$k: no match\n";
      }

    # Write them to temp file.
    my $tmp = "$file-t";
    open FH, '>', $tmp
      or die "$ME: can't open `$tmp' for writing: $!\n";
    print FH @line;
    close FH
      or die "$ME: failed to write `$tmp': $!\n";

    # Move temp file back onto original.
    rename $tmp, $file
      or die "$ME: failed to rename: `$tmp' -> `$file': $!\n";
  }

# Local variables:
#  indent-tabs-mode: nil
# End:
