#!/usr/bin/perl
use strict;
use warnings;
use File::Find;

find(sub {
    #we only want files
    return unless -f $_;
    #of a given extension
    return unless /\.(?:c|h|texi)/i;
    #and not from hidden folders (to avoid touching .svn folders for example)
    return if $File::Find::name =~ /[\/\\]\./;
    my $filename = $_;
    
    print "Fixing $File::Find::name\n";
    
    my $f;
    unless (open $f, '<', $filename) {
        warn qq{Failed to open "$File::Find::name" for reading: $!\n};
        return;
    }
    my @lines = map { 
        my $line_ending = ($_ =~ /[\x0d\x0a]+\z/); 
        s/[\x0d\x0a]+\z// if ($line_ending);
        s/\s+$//;
        $_ .= "\n" if ($line_ending);
        $_
    } <$f>;
    close $f;
    
    unless (open $f, '>', $filename) {
        warn qq{Failed to open "$File::Find::name" for writing: $!\n};
        return;
    }
    print $f @lines;
    close $f;
}, '.');
