#!/usr/bin/perl

#
#
# Script to invoke astyle pretty printer on all cpp, c, and header files
# 
# NOTES: 
#        - Script expects RELATIVE path for easier call from a Makefile
#  
# Revision History
# 2007/09/13 - bkieft - Initial creation     
# 2008/07/07 - godin - Removed recursion into directories
#
#
$usage = "usage: make_pretty.pl rootPath [recurseDepth]\n";
die $usage unless @ARGV >= 1; #show usage if no parameters were passed 
use File::Find;
my $baseDepth;
my $recurseDepth = @ARGV >= 2 ? $ARGV[1] : 1000;

my @files;

sub process_file 
{
    my $name = $File::Find::name;
    my $depth = ($name =~ tr!/!!); # count slashes to get depth
    if($depth- $baseDepth <= $recurseDepth && $File::Find::name =~/(.*\.cpp$)|(.*\.c$)|(.*\.hpp$)|(.*\.h$)/) 
    {
        my $fileName = $File::Find::name;
        #$status = system("astyle --style=ansi -pUDZn $fileName");
        #die "Pretty printing failed with: $?" unless $status == 0;
        push( @files, $fileName );
    }
}

# get current directory to prepend to ARGV
chomp($pathPrefix = `pwd`);

foreach $dir ($ARGV[0]) {
    my $path = "$pathPrefix/$dir";
    $path=~ s/\/+$//g;
    $baseDepth = ($path =~ tr!/!!);
    #print("path=$path, baseDepth=$baseDepth, recurseDepth=$recurseDepth\n");
    find(\&process_file, $path);
    $status = system("astyle --style=ansi --formatted -pUDZn @files");
    if( $status != 0 )
    {
        printf("Trying astyle with | grep \"formatted*\"\n");
        $status = system("astyle --style=ansi -pUDZn @files | grep \"formatted*\"");
        print "No files formatted\n" unless $status == 0;
    }
}

exit 0;