#enc.pl

use strict;
use utf8;

binmode(STDOUT, ":utf8");

my $space0 = ' ';
my $space1 = chr 0x3000;

my @binaryData = split '', readBinaryFile("smiley.svg.gz");
my @textData = split '', readUTF8File("input.txt");

my $spaceCount = countSpaces(join '', @textData);
my $bitCount = scalar @binaryData;

if ($spaceCount < (scalar @binaryData)) {
	die "File too large to encode: $spaceCount spaces < $bitCount bits";
}

foreach (@textData) {
	my $char = $_;
	if ($char eq $space0 or $char eq $space1) {
		if (@binaryData > 0) {
			my $bit = shift @binaryData;
			if ($bit eq '0') { print $space0; }
			else { print $space1; }
		} else {
			print $space0;
		}
	} else {
		print $char;
	}
}

sub readBinaryFile {
	my $filename = shift;
	
	open my $fh, $filename or die "Failed to open file: $filename";
	my $bytes = join '', <$fh>;
	close $fh;
	
	my $binary = "";
	
	foreach (split '', $bytes) {
		$binary .= sprintf "%08b", ord $_;
	}
	
	return '1' . $binary . '1';
}

sub readUTF8File {
	my $filename = shift;

	open my $fh, '<:encoding(UTF-8)', $filename or die "Failed to open text file: $filename";
	my $chars = join '', <$fh>;
	close $fh;
	
	return $chars;
}

sub countSpaces {
	my $text = shift;
	
	my @s0 = $text =~ /$space0/g;
	my @s1 = $text =~ /$space1/g;
	return (scalar @s0) + (scalar @s1);
}