Solution for the icfp-2014 contest.