#!/usr/bin/perl

use FindBin;

$BINPATH = $FindBin::Bin;

use File::Find;
use Data::Dumper;

# Taken from find2perl
sub fileglob_to_re ($) {
    my $x = shift;
    $x =~ s#([./^\$()+])#\\$1#g;
    $x =~ s#([?*])#.$1#g;
    "^$x\\z";
}

sub prefix_to_re ($) {
    my $x = shift;
    $x =~ s#([./^\$()+?*])#\\$1#g;
    "^$x";
}

sub buildMatcher {
	my ($globs, $excludes) = @_;
	my @globs = split(/\s+/, $globs);
	my $globREs = join(" || ",
			map { "/".fileglob_to_re($_)."/s" } @globs);
	
	my @excludes = split(/\s+/, $excludes);
	my $excludeREs = join(" || ",
			map { "/".prefix_to_re($_)."/s" } @excludes) || 0; 
			
	eval("sub { -f && ($globREs) && !($excludeREs) && push \@params, \$File::Find::name; }");
}

sub readfile {
	open(FILE, $_[0]);
	my @lines = <FILE>;
	close(FILE);
	join("", @lines);
}

sub getConfig {
	my ($cfg, $var) = @_;
	$cfg =~ /^$var[ \t]*=[ \t]*([^\n]*)/m;
	return $1;
}

$cfgFile = readfile($ARGV[0] || "Doxyfile");
$cfgFile =~ s/#[^\n]*//g;
$cfgFile =~ s/\\[ \r\t]*\n//g;

$input = getConfig($cfgFile, "INPUT") || ".";
@input = split(/\s+/, $input);

$patterns = getConfig($cfgFile, "FILE_PATTERNS") || "*.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm";
$exclude = getConfig($cfgFile, "EXCLUDE");

$headers = getConfig($cfgFile, "INCLUDE_PATH");
@headers = split(/\s+/, $headers);
@params = map { "-I$_" } @headers;

$defines = getConfig($cfgFile, "DEFINES");
@defines = split(/\s+/, $defines);
push(@params, map { "-D$_" } @defines);

push(@params, grep { -f } @input);

@dirs = grep { -d } @input;
if (@dirs) {
	$matcher = buildMatcher($patterns, $exclude);
	finddepth($matcher, @dirs);
}

print "Running parser with the following arguments: ".join(" ", @params)."\n";
exec "$BINPATH/correctAllComments", @params;
