#!/usr/bin/perl -w


$main::VERSION = "1.1";
# 05.09.2008  1.1
# 08.06.2008  1.0

# Changelog:
#
# v1.1 (05.09.2008)
# Zmeneno nacitani prikazu
# Pouziti modulu Term::ReadLine::Gnu
# opravena chyba pri dekodovani LZW
# odstranen parametr u LZSS, zda se ma jednoznakova shoda kodovat jako novy znak
# pridano pocitani bitu na zakodovanou zpravu
#
# v1.0 (08.06.2008)
# Initial version

# implementovane metody:
# LZ77
# LZSS
# LZ78
# BSTW
# intervalove kodovani
# LZW

use strict;
use locale;

# modul pro cteni radky
use Term::ReadLine;

# The POSIX module permits you to access all (or nearly all) the standard POSIX 1003.1 identifiers. 
use POSIX;

# modul obsahujici spolecne funkce
use Common;

# moduly s implementovanymi metodami
use LZ77;
use LZSS;
use BSTW;
use Interval;
use LZ78;
use LZW;

# inicializace paremetru
my $default_mode_enc = $Common::NO_WAITING_MODE | $Common::NO_SILENT_MODE | $Common::NO_TREE_VIEW | $Common::NO_LIST_VIEW;
my $default_mode_dec = $Common::NO_WAITING_MODE | $Common::NO_SILENT_MODE | $Common::NO_TREE_VIEW | $Common::NO_LIST_VIEW;
my $mode_enc = $default_mode_enc;
my $mode_dec = $default_mode_dec;
my @default_window_size = (7, 3);
my @window_size = @default_window_size;
# pomocny parametr
my @alphabet;

my $input = undef;
my @encoded;
my $decoded;

# seznam implementovanych metod
my %methods = (
	'LZ77' => { 
		id => 1, 
		f_encode => \&lz77_encode,
		f_decode => \&lz77_decode,
		params => [\@window_size],
		f_info => \&print_help_lz77,
		f_count_bits => \&lz77_count_bits
	},
	'LZSS' => { 
		id => 2, 
		f_encode => \&lzss_encode,
		f_decode => \&lzss_decode,
		params => [\@window_size],
		f_info => \&print_help_lzss,
		f_count_bits => \&lzss_count_bits
	},
	'LZ78' => { 
		id => 3, 
		f_encode => \&lz78_encode, 
		f_decode => \&lz78_decode, 
		params => [],
		f_info => \&print_help_lz78,
		f_count_bits => \&lz78_count_bits
	},
	'LZW' => { 
		id => 4, 
		f_encode => \&lzw_encode, 
		f_decode => \&lzw_decode, 
		params => [\@alphabet],
		f_info => \&print_help_lzw,
		f_count_bits => \&lzw_count_bits
	},
	'BSTW' => { 
		id => 5, 
		f_encode => \&bstw_encode,
		f_decode => \&bstw_decode,
		params => [],
		f_info => \&print_help_bstw, 
		f_count_bits => \&bstw_count_bits
	},
	'Interval' => { 
		id => 6, 
		f_encode => \&int_encode, 
		f_decode => \&int_decode, 
		params => [],
		f_info => \&print_help_int,
		f_count_bits => \&int_count_bits
	},
);

# array of methods - sorted by ids
my @methods = sort { $methods{$a}->{id} <=> $methods{$b}->{id} } keys %methods;

my %commands = (
	'describe'		=> { func => \&com_describe,	doc => "Vypíše popis metody (id nebo název metody), bez parametru se chová jako 'methods'" },
	'exec'			=> { func => \&com_exec,		doc => "Spustí metodu (parametr nutný - id nebo název metody)" },
	'exit'			=> { func => \&com_quit,		doc => "Synonymum pro 'quit'" },
	'help'			=> { func => \&com_help,		doc => "Zobrazí nápovědu (parametr - nápověda pouze zadaného příkazu)" },
	'?'				=> { func => \&com_help,		doc => "Synonymum pro 'help'" },
	'input'			=> { func => \&com_input,		doc => "Zadání textu (parametr volitelný)" },
	'methods'		=> { func => \&com_methods,	doc => "Vypíše dostupné metody" },
	'print_input'	=> { func => \&com_print_input,	doc => "Vytiskne vstup" },
	'print_mask_info'	=> { func => \&com_print_mask_info,		doc => "Vytiskne informace o masce" },
	'print_params'	=> { func => \&com_print_params,		doc => "Vytiskne parametry" },
	'quit'			=> { func => \&com_quit,		doc => "Ukončí program" },
	'set_mode_dec'	=> { func => \&com_set_mode_dec,	doc => "Nastaví parametry dekódování (parametr nutný - maska)" },
	'set_mode_enc'	=> { func => \&com_set_mode_enc,	doc => "Nastaví parametry kódování (parametr nutný - maska)" },
	'set_params'	=> { func => \&com_set_params,	doc => "Nastaví parametry" },
	'set_window'	=> { func => \&com_set_window,	doc => "Nastaví velikost okénka (parametr nutný - <P> <B>)" },
	'version'		=> { func => \&com_version,		doc => "Vypíše verzi programu" },
);

###############################################################################

print "\
_____                        _____\
|  __ \\                      / ____|\
| |  | | ___ _ __ ___   ___ | |     ___  _ __ ___  _ __  _ __ ___  ___ ___\
| |  | |/ _ \\ '_ ` _ \\ / _ \\| |    / _ \\| '_ ` _ \\| '_ \\| '__/ _ \\/ __/ __|\
| |__| |  __/ | | | | | (_) | |___| (_) | | | | | | |_) | | |  __/\\__ \\__ \\\
|_____/ \\___|_| |_| |_|\\___/ \\_____\\___/|_| |_| |_| .__/|_|  \\___||___/___/\
                                                 | |\
                                                 |_|\
\n";
print_methods();
print "\nNapište '?' nebo 'help' pro vypsání nápovědy\n";

my $line;

my $term = new Term::ReadLine 'DemoCompress';
$term->Attribs->{attempted_completion_function} = \&commands_completion;


while ( defined ($line = $term->readline('> ')) )
{	
	next unless $line;
	stripwhite(\$line);
	my ($word, $arg) = split(/\s/, $line, 2);
	my $command = $commands{$word};

	unless ($command) {
		printf STDERR "$word: Neznámý příkaz, zadejte 'help' pro nápovědu\n";
		next;
	}

	last if (&{$command->{func}}($arg));

}

print "\nThanks for using this program\n";


###############################################################################
# SUBROUTINES                                                                ##
###############################################################################

sub com_describe {
	my $arg = shift;
	my $method_name;
	if (not $arg) {
		print_methods();
	}
	elsif (not ($method_name = get_method_name($arg))) {
		print "Neznámá metoda\n";
		print_methods();
	}
	else {
		$methods{$method_name}->{f_info}();
	}
	return 0;
}

sub com_exec {
	my $arg = shift;
	if (not defined $arg) {
		print "Zadejte 'exec <id_metody>' nebo 'exec <název_metody>'\nZadejte 'help' pro nápovědu\n";
		return 0;
	}
	my $method_name = get_method_name($arg);
	if (not $method_name) {
		print "Neznámá metoda\n";
		print_methods();	
	}
	else {
		if (not defined $input) {
			com_input();
		}
		my $ref = $methods{$method_name};
		@encoded = $ref->{f_encode}(\$input, $mode_enc, @{$ref->{params}});
		print_encoded(\@encoded);
		# kolik se usetri bitu
		my $puvodni = length($input) * 8;
		my $kodovana = $ref->{f_count_bits}(\@encoded, @{$ref->{params}});
		printf "pocet bitu: puvodni zprava - %d bits (%d bytes), kodovana zprava - %d bits (%d bytes) \n",
			$puvodni, ceil($puvodni/8), $kodovana, ceil($kodovana/8);
		printf "kompresni pomer: %.2f%%\n", 100*$kodovana/$puvodni;

		if (ask_decode()) {
				$decoded = $ref->{f_decode}(\@encoded, $mode_dec, @{$ref->{params}});
			print "\ndecoded: $decoded\n";
			print "input:   $input\n";
			print "ERROR - please contact an author\n" if $decoded ne $input
		}
	}
	return 0;
}

sub com_quit {
	return 1;
}

sub com_help {
	my $arg = shift;
	if ((not defined $arg) || (not defined $commands{$arg})) {
		foreach my $command (sort keys %commands) {
			printf "%-20s %s\n", $command, $commands{$command}->{doc};
		}
	}
	else {
		printf "%-20s %s\n", $arg, $commands{$arg}->{doc};
	}
	return 0;
}


sub com_input {
	my $arg = shift;
	
	my $l_term = new Term::ReadLine 'Input';
# 	$l_term->MinLine(0);
	
	unless ($arg) { 
		do {
			print "Zadejte vstup, ktery chcete zakodovat (mozno i s diakritikou). Vstup ukoncete klavesou <Enter>:\n";
		} while not $input = $l_term->readline('') or $input eq "\n";
		chomp $input;
	}
	else {
		$input = $arg;
	}
	return 0;
}

sub com_methods {
	print_methods();
	return 0;
}

sub com_print_input {
	if (defined $input) {
		print "Input: $input \n";
	}
	else {
		print "Nebyl zadán\n";
	}
	return 0;
}

sub com_print_mask_info {
	print_mask_info();
	return 0;
}

sub com_print_params {
	print_params();
	return 0;
}

sub com_set_mode_dec {
	my $arg = shift;
	if (defined $arg and $arg eq "default") {
		$mode_dec = $default_mode_dec;
		print "new decoding mode: ($mode_dec) " . translate_mask($mode_dec) . "\n";
	}
	elsif (defined $arg and $arg =~ m/([0-9]+)/) {
		$mode_dec = $+;
		print "new decoding mode: ($mode_dec) " . translate_mask($mode_dec) . "\n";
	}
	else {
		print "Nesprávně zadaný příkaz.\nPro změnu decoding mode zadejte 'set_mode_dec default' nebo 'set_mode_dec <mask>'\nPro nápovědu, jak správně vytvořit masku, zadejte 'print_mask_info'\n";
	}
	
	return 0;
}

sub com_set_mode_enc {
	my $arg = shift;
	if (defined $arg and $arg eq "default") {
		$mode_enc = $default_mode_enc;
		print "new encoding mode: ($mode_enc) " . translate_mask($mode_enc) . "\n";
	}
	elsif (defined $arg and $arg =~ m/([0-9]+)/) {
		$mode_enc = $+;
		print "new encoding mode: ($mode_enc) " . translate_mask($mode_enc) . "\n";
	}
	else {
		print "Nesprávně zadaný příkaz.\nPro změnu encoding mode zadejte 'set_mode_enc default' nebo 'set_mode_enc <mask>'\nPro nápovědu, jak správně vytvořit masku, zadejte 'print_mask_info'\n";
	}
	
	return 0;
}

sub com_set_params {
	if (my $ret = set_params()) {
		print "Nové hodnoty parametrů:\n";
		print_params();
	}
	return 0;
}

sub com_set_window {
	my $arg = shift;
	if (defined $arg and $arg eq "default") {
		@window_size = @default_window_size;
		print "new window_size: @window_size\n";
	}
	elsif (defined $arg and $arg =~ m/([0-9]+\s+[0-9]+)/) {
		@window_size = split /\s/, $+;
		print "new window_size: @window_size\n";
	}
	else {
		print "Nesprávně zadaný příkaz.\nPro změnu velikosti okénka zadejte 'set_window default' nebo 'set_window <P> <B>'\n";
	}
	return 0;
}

sub com_version {
	print "\nVersion $main::VERSION\n";
	return 0;
}

###############################################################################

sub get_method_name
{
# in:
# cislo metody nebo jeji nazev (case-insensitive)
# out:
# nazev metody nebo undef (pokud neexistuje)

	my $method = shift;
	return undef if not defined $method;
	if ($method =~ /^[0-9]+$/) { # cislo
		if ($method < 1 || $method > $#methods + 1) {
			return undef;
		}
		else {
			return $methods[$method - 1];
		}
	}
	else {
		foreach my $key (keys %methods) {
			if ($method =~ m/$key/i) {
				return $key;
			}
		}
		return undef;
	}
}

###############################################################################

sub print_methods
{
# vytiskne seznam dostupnych metod

	print "Momentálně jsou k dispozici tyto metody:\n";
	my $i = 1;
	foreach my $a (@methods) {
		print "$i : $a\n";
		$i++;
	}
}

###############################################################################

sub print_encoded
{
# in:
# encoded (ref array)
# vytiskne zakodovany vstup

	my $ref_encoded = shift;
	&endl;
	print "encoded: ";
	print_code_words($ref_encoded);
	&endl;
}

###############################################################################

sub ask_decode
{
# polozi otazku a ceka na odpoved ano/ne

	print "dekódovat? yes/no\n"; 
	my $key; 
	while (($key = read_key()) !~ m/[yYnN]/) {}
	return ($key =~ m/[yY]/);
}

###############################################################################

sub print_params
{
# vytiskne seznam parametru

	print "encoding mode: ($mode_enc) " . translate_mask($mode_enc) . "\n";
	print "decoding mode: ($mode_dec) " . translate_mask($mode_dec) . "\n";
	print "window size: @window_size\n";
	print "default window size (constant): @default_window_size\n";
}

###############################################################################

sub print_mask_info
{
# vytiskne slozeni masky

	printf "Maska se zadává jako součet voleb:\
    %-15s : %2s (při (de)kódování se bude čekat na stisk klávesy v každém kroku) \
    %-15s : %2s\
    %-15s : %2s (v jednotlivých krocích se nebude nic vypisovat)\
    %-15s : %2s\
    %-15s : %2s (pouze u lz78 a lzw - vypsat slovník jako strom po každém kroku)\ 
    %-15s : %2s\
    %-15s : %2s (pouze u lz78 a lzw - vypsat slovník jako seznam po každém kroku)\
    %-15s : %2s\n",
		"waiting_mode", $Common::WAITING_MODE, "no_waiting_mode", $Common::NO_WAITING_MODE,
		"silent_mode", $Common::SILENT_MODE, "no_silent_mode", $Common::NO_SILENT_MODE,
		"tree_view", $Common::TREE_VIEW, "no_tree_view", $Common::NO_TREE_VIEW,
		"list_view", $Common::LIST_VIEW, "no_list_view", $Common::NO_LIST_VIEW;
}

###############################################################################

sub set_params
{
# procedura pro nastaveni parametru
# out:
# true/false - jestli se zmenil nejaky parametr

	my $key;
	my $line;
	my $zmena = 0;
	
	print "Chcete změnit parametr window_size? yes/no/quit\n";
	while (($key = read_key()) !~ m/[qQyYnN]/) {}
	return $zmena if $key =~ m/[qQ]/;
	if ($key =~ m/[yY]/) {
		print "Velikost první části (processed): ";
		$line = <>;
		if (defined $line && $line =~ m/([0-9]+)/) {
			$window_size[0] = $+;
		}
		print "Velikost druhé části (buffer): ";
		$line = <>;
		if (defined $line && $line =~ m/([0-9]+)/) {
			$window_size[1] = $+;
		}
		$zmena = 1;
	}
	
	print "Chcete změnit parametr encode_mode? yes/no/quit\n";
	while (($key = read_key()) !~ m/[qQyYnN]/) {}
	return $zmena if $key =~ m/[qQ]/;
	if ($key =~ m/[yY]/) {
		print_mask_info();
		print "mask: ";
		while (1) {
			$line = <>;
			next if not defined $line;
			chomp $line;
			if ($line =~ m/([0-9]+)/) {
				$mode_enc = $+;
				last;
			}
		}
		$zmena = 1;
	}
	
	print "Chcete změnit parametr decode_mode? yes/no/quit\n";
	while (($key = read_key()) !~ m/[qQyYnN]/) {}
	return $zmena if $key =~ m/[qQ]/;
	if ($key =~ m/[yY]/) {
		print_mask_info();
		print "mask: ";
		while (1) {
			$line = <>;
			next if not defined $line;
			chomp $line;
			if ($line =~ m/([0-9]+)/) {
				$mode_enc = $+;
				last;
			}
		}
	}
	return $zmena;
}

###############################################################################



# Strip whitespace from the start and end of STRING.  Return a pointer
# into STRING.
sub stripwhite {
    my $string = shift;
    $$string =~ s/^\s*//;
    $$string =~ s/\s*$//;
    return $string;
}


# Attempt to complete on the contents of TEXT.  START and END bound
# the region of rl_line_buffer that contains the word to complete.
# TEXT is the word to complete.  We can use the entire contents of
# rl_line_buffer in case we want to do some simple parsing.  Return
# the array of matches, or NULL if there aren't any.
sub commands_completion {
	my ($text, $line, $start, $end) = @_;

	my @matches = ();

	# If this word is at the start of the line, then it is a command
	# to complete.  Otherwise it is the name of a file in the current
	# directory.
	@matches = $term->completion_matches ($text, \&command_generator) if ($start == 0);

	return @matches;
}

# Generator function for command completion.  STATE lets us know
# whether to start from scratch; without any state (i.e. STATE == 0),
# then we start at the top of the list.

## Term::ReadLine::Gnu has list_completion_function similar with this
## function.  I defined new one to be compared with original C version.
{
	my $list_index;
	my @name;

	sub command_generator {
		my ($text, $state) = @_;
	
		# If this is a new word to complete, initialize now.  This
		# includes saving the length of TEXT for efficiency, and
		# initializing the index variable to 0.
		unless ($state) {
			$list_index = 0;
			@name = keys(%commands);
		}
	
		# Return the next name which partially matches from the
		# command list.
		while ($list_index <= $#name) {
			$list_index++;
			return $name[$list_index - 1]
			if ($name[$list_index - 1] =~ /^$text/);
		}
		# If no names matched, then return NULL.
		return undef;
	}
}

