#!/usr/bin/perl -w
#
# $Revision: 1.2 $ $Date: 2012-07-26 17:11:47-04 $
# $Source: /home/vogelke/bin/RCS/commflags,v $
# $Host: sys7.com $
# $UUID: ece9ece5-4c4c-324b-9cbc-6b50920fde8d $
#
#<commflags: find common compiler flags in make output.

use strict;

my $flist;
my $match;
my $p;
my %a;
my @disp;
my @fl;
my @orig;
my @pat;
my @rep;
my @used;

my $k = 0;
while (<>) {
    chomp;
    s/\s+/ /g;
    s/-pipe -c/-c -pipe/g;    # keep -c out of middle of line.
    $orig[$k] = "$_";
    $k++;
}

my $max  = $k;
my $n    = 0;
my $prev = '';

# Get just the options.
while ($n < $max) {
    $_         = $orig[$n];
    @fl        = grep (/^-/, split());
    $flist     = join(' ', @fl);
    $a{$flist} = 1;
    $n++;
}

# Keep only option patterns long enough to be worth it.
$k = 1;
foreach $p (sort keys %a) {
    next unless length($p) > 60;
    $p =~ s/-c //g;
    $p =~ s/-o //g;
    $p =~ s/ -c//g;
    $p =~ s/ -o//g;
    $pat[$k] = "$p";
    $k++;
}

# Set up the flag variables that might be used.
$k = 1;
while ($pat[$k]) {
    $disp[$k] = '$flag' . $k . " = $pat[$k]";
    $rep[$k]  = '$flag' . $k;
    $used[$k] = 0;

    # Kill backslashes, or they screw up the replacement.
    $pat[$k] =~ s/\\/./g;
    $k++;
}

# Go through the original file, look for matches.
$n = 0;
while ($n < $max) {
    $_     = $orig[$n];
    $k     = 1;
    $match = 0;

    while ($pat[$k]) {
        if (/$pat[$k]/) {
            $match = 1;
            $used[$k]++;
            last;
        }
        $k++;
    }

    $n++;
}

# Print only the flag strings that were used.
$k = 1;
while ($pat[$k]) {
    print "$disp[$k]\n" if $used[$k];
    $k++;
}
print "\n";

# Now, go through original file for the last time, doing subs.
$n = 0;
while ($n < $max) {
    $_     = $orig[$n];
    $k     = 1;
    $match = 0;

    while ($pat[$k]) {
        if (/$pat[$k]/) {
            s/$pat[$k]/$rep[$k]/g;
            print "$_\n";
            $match = 1;
            $used[$k]++;
            last;
        }
        $k++;
    }

    print "$_\n" unless $match;
    $n++;
}

exit(0);
