#!perl

use strict;
use warnings;
use utf8;
use Lang::HL;
use File::Find;
use Perl::Tidy;

sub readFile {
    my ($fileName) = @_;
    my $fileContent;
    open(my $fh, '<:encoding(UTF-8)', $fileName) or die "Cannot open the program file";
    {
        local $/;
        $fileContent = <$fh>;
    }
    close($fh);
    return $fileContent;
}

my $dirName = $ARGV[0];

if(! defined $dirName ) {
    die("give a directory path");
}

my $code = "";
find({ wanted => \&process_file, no_chdir => 1 }, @ARGV);

sub process_file {
    if (-f $_) {
        $code .= readFile($_);
    }
}

$code =~ s/[\r\n\f]+//g;

my @code = split(" ", $code);
$code = join(" ", @code);

my $hlObject = Lang::HL->new();
my $generatedCode = $hlObject->parse($code);
my $formattedCode;

my $argv = "-npro";   # Ignore any .perltidyrc at this site
$argv .= " -pbp";     # Format according to perl best practices
$argv .= " -nst";     # Must turn off -st in case -pbp is specified
$argv .= " -se";      # -se appends the errorfile to stderr

my $error = Perl::Tidy::perltidy(
    argv => $argv,
    source => \$generatedCode,
    destination => \$formattedCode,
);

if($formattedCode) {
    print $formattedCode;
}
else {
    print $generatedCode;
}
