# $Id: CRF.pm 368 2008-02-22 10:19:38Z michal $

package Victor::Output::CRF;

use strict;
use warnings;
use open ':locale';

use Exporter;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(&output_crf);

use Victor::Cfg;
use Victor::SplitHTML;
use Victor::Features;

sub output_crf {
	my $opt = shift;
	my @close;
	my $out;
	if (!$opt->{output}) {
		$out = \*STDOUT;
	} elsif (ref($opt->{output}) eq "GLOB") {
		$out = $opt->{output};
	} else {
		open($out, ">", $opt->{output}) || die "can't open $opt->{output}: $!\n";
		push(@close, $out);
	}
	$opt->{train} ||= 0;

	# sanity check
	if (!feature_supported("_verbose", cfg_get_array('crf-features'))) {
		die "error in configuration\n";
	}

	foreach my $file (@_) {
		my $blocks = [];
		if (ref($file) eq "ARRAY") {
			# argument is an array of already split blocks
			$blocks = $file;
			$file = $opt->{filename} || "<input>";
		} else {
			split_html($file, $blocks);
		}

		calculate_fv(@$blocks);

		foreach my $block (@$blocks) {
			print $out "$block->{id}";
			foreach (cfg_get_array('crf-features')) {
				print $out "\t" . ($block->{fv}{$_} ? $block->{fv}{$_} : "0");
			}
			if ($opt->{train}) {
				if (!$block->{class}) {
					die "$file: block #$block->{id} is not annotated\n";
				}
				print $out "\t$block->{class}";
			}
			print $out "\n";
		}
		# document delimiter
		print $out "\n";
	}

	foreach my $fh (@close) {
		close($fh);
	}
}
