#!/usr/bin/perl

use strict;

my $version = 1.0; # version number of the script

if ((@ARGV < 2) or (@ARGV > 3)) 
	{ die "Correct syntax is:\n\tweka2bmr.pl weka_file_name bmr_file_name [BXR]\n"; }

# slurp the weka file into memory
open (WEKA, $ARGV[0]) or die "Could not open weka data file.\n";
my @weka = <WEKA>;
chomp (@weka);
close (WEKA);

@weka = grep(!/^$/, @weka); # weed out blank lines
my @weka_attrib = grep(/^\@attribute/i, @weka); # extract all of the attribute names
my @weka_data = grep(!/^[@%]/, @weka); # extract the data lines

# we end up with a single blank line on the end of the lists, so get rid of that
#pop(@weka_attrib);
#pop(@weka_data);

# decide how to deal with feature names
if (uc($ARGV[2]) eq 'BXR') {
	# we're using BXR, so text feature names are OK
	for (my $i = 0; $i < @weka_attrib; $i++) {
		$weka_attrib[$i] =~ m/^\@attribute\s+(\w+?)\s+/i; # get the attribute name
		$weka_attrib[$i] = $1; # replace the attribute line with the attribute name
	}
} else {
	# we're using BMR, so we need to use numeric feature ids
	for (my $i = 0; $i < @weka_attrib; $i++) 
		{ $weka_attrib[$i] = $i; } # replace the attribute line the attribute number 
}

# open output file
open (BMR, ">" . $ARGV[1]) or die "Could not open bmr data file.\n";

print BMR "# File: $ARGV[1]\n# Source File: $ARGV[0]\n# Generated by: weka2bmr.pl ver. $version\n#\n";

foreach my $data (@weka_data) {
	# work on the each of the data lines
	my @data_set = split(/,/, $data);
	print BMR "$data_set[0] "; # we assume the author always identified by the first entry
	for (my $i = 1; $i < @data_set; $i++) {
		#work through the feature data
		if ($data_set[$i] != 0) {
			# we only print feature values which are non-zero
			print BMR "$weka_attrib[$i]:$data_set[$i] ";
		}
	}
	print BMR "\n";
}

close (BMR); # close the output file, we're done with it