#!/usr/bin/perl
# This is a simple perl script to generate a brainfuck program to print out a
# given message. For example, the text "f0rked" is output by the following
# program:
#
# ++++++++++[>++++++++++>+++++>++++++++
# +++>+++++++++++>++++++++++>++++++++++
# >+<<<<<<<-]>++.>--.>++++.>---.>+.>.>.
#
# There are many interpreters available for brainfuck programs. One written
# in C is available here: http://brainfoo.sourceforge.net/
# 
# Matt Sparks, 20061002
#
# usage: ./bfmsg.pl [-w<# of columns>] <msg>
#    ex: ./bfmsg.pl -w80 put your message here. No space between -w and 80.
#        ./bfmsg.pl the number of columns will be chosen automatically otherwise
#
# Note: the following code is intentionally semi-obfuscated.
use strict;

my $col;
if ($ARGV[0] =~ /^\-w(\d+)/) { $col=$1; shift @ARGV; }
# die if we are not given a message
die "usage: $0 <msg>\n" if (!$ARGV[0]);
my $msg=join(" ",@ARGV)."\n";

# die if the message is too long. BF has a 30k-char array, two positions of
# which we use for the counter variable and newline.
die "Message is too long (must be <29,999 characters)\n"
    if length $msg >= 29999;

# start our brainfuck output
my $l; # in loop
my $al; # after loop
my $o = "+"x(10)."[";
for(split //,$msg) {
    my $c = ord;
    $l  .= ">"."+"x(sprintf("%d",$c/10));
    $l  .= "+" if $c%10 > 5;
    $al .= ($c%10 > 5) ? ">"."-"x(10-($c%10))."." : ">"."+"x($c%10).".";
}
$l .= "<"x(length $msg)."-";
$o .= $l."]".$al;
my $w; 
if (!$col) { 
    for($w=78;$w>40;$w--) { last if length($o)%$w == 0; }
}
else {
    $w = $col;
}
while(my $p=substr($o,0,$w)) { print "$p\n"; $o = substr($o,$w); }
