#! /usr/bin/perl -w
    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
        if 0; #$running_under_some_shell

use strict;
use File::Find ();

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;

sub wanted;

chomp(my $pwd = `pwd`);

my @path = split('/', $pwd);
my @relpath = ();

while ($path[$#path] ne 'm5') {
    push @relpath, '..';
    pop @path;
    if (scalar(@path) == 0) {
	die "Can't find 'm5' in path $pwd\n";
    }
}

my $relpath = join('/', @relpath);
$relpath = '.' if ($relpath eq '');

# where to put the files we find
my @files = ();

# Find *.h and *.hh files to build rename commands.
File::Find::find({wanted => \&wanted}, $relpath);

# put headers before source files... I like it that way for grep since
# the declarations show up before the uses.
sub is_hdr { return ($_[0] =~ /\.hh?$/); }

sub headers_first {
    my $a_is_hdr = is_hdr($a);
    my $b_is_hdr = is_hdr($b);

    if ($a_is_hdr && !$b_is_hdr) {
	return -1;
    }
    elsif ($b_is_hdr && !$a_is_hdr) {
	return 1;
    }
    else {
	return ($a cmp $b);
    }
}

print join("\n", sort headers_first @files), "\n";

sub wanted {
    # files/directories to skip
    ($prune = 1, return) if
      (m{
	 ^(SCCS|Attic|BitKeeper|PENDING|build|docs)\z	# full names to match
	 | ^(\..+)					# prefixes
	 | (~)\z					# suffixes
	 | ^\#.*\#\z					# emacs autosave files
        }sx);

    # -type f
    my ($dev,$ino,$mode,$nlink,$uid,$gid);
    ($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_) or return;
    return unless -f _;

    # strip leading "./"
    my $pname = $name;
    $pname =~ s|^\./||;

    # -print
    push @files, $pname;
}
