#! /usr/bin/perl
use strict;

use HTML::Entities;

binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");

# get data
my $data;
if (defined($ARGV[0])) {
    if (-e $ARGV[0]) { 
	$/ = undef;
	open FH, "<:utf8", "$ARGV[0]" || die "cannot open $ARGV[0]: $!\n";
	$data = <FH>;
	close FH || die "cannot close $ARGV[0] after reading: $!\n";
    } else {
	# file not found, let's get out of here
	exit 0;
    }
} else {
    # go for stdin
    $/ = undef;
    $data = <>;
} 

# convert it
if ($0 =~ m|/utf2html$|) {
    encode_entities($data, "\200-\377");
} elsif ($0 =~ m|/html2utf$| ) {
    decode_entities($data);
} else {
    die "unknown command: $0";
}

# give data back
if (defined($ARGV[0])) {
    open FH, ">:utf8", "$ARGV[0]" || die "cannot open $ARGV[0]: $!\n";
    print FH $data;
#    print "Dest: $ARGV[0]; Data: $data\n";
    close FH || die "cannot close $ARGV[0]: $!\n";
} else {
    print "$data";
}


