#!/usr/bin/perl -w
# entropie.pl - Berechnet die Entropie von Dateien
# Copyright (C) Son Aug  5 11:42:36 MEST 2001 by Ingo Blechschmidt
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Ingo Blechschmidt
# Arberstraße 5
# 86179 Augsburg
# E-Mail: iblech@web.de, http://www.way.to/uselinux/
# Tel.: +49 / 821 882955
#
# 

$file = '';
%char = ();
$len  = 0;
$a    = 0;
$b    = 0;
$c    = 0;
$d    = 0;
$e    = '';
$f    = '';
# Erw:
$kurz = '';

if (not $ARGV[0]) {
  print 'Bitte Dateinamen angeben: ';
  chomp($file = <STDIN>);
} else {
  $file = $ARGV[0];
}

open(DATEI, $file) || die("Konnte '$file' nicht laden!");
while () {
  $e = getc(DATEI);
  last if (not $e);
  $char{ord($e)}++;
  $len++;
}
close(DATEI);


# Erweiterungen Son Aug  5 11:34:44 MEST 2001:
if (defined $ARGV[1]) { $kurz = 'ja' } else { $kurz = 'nein' }

if ($kurz eq 'nein') {
  open(OUT, '|less') || die "Konnte nicht 'less' starten!";
  select(OUT);
}

print("Entropie der Datei '$file':\n\n") unless ($kurz eq 'ja');
for($b = 0; $b <= 255; $b++) {
  if (not $char{$b}) {
    $c = 0;
  } else {
    $a = $char{$b} / $len;
    $c = -($a * (log($a) / log(2)));
  }
  $d += $c;
  $f = chr($b); $f = '' if ($b < 32);
  print "$b ($f):  \t$c\n" unless ($c eq 0 or $kurz eq 'ja');
}
if ($kurz eq 'ja') {
  print "$d\n";
} else {
  print "\nMittlere Entropie der Datei: $d\n";
}

close(OUT) unless ($kurz eq 'ja');
select(STDOUT);
