#!/usr/bin/perl -ws
#
# $dotat: scripts/randsig,v 1.63 2011/02/14 16:25:31 fanf2 Exp $

use strict;
use integer;

our ($a,$r);

sub nowrap {
    my $line = shift;
    $line =~ s/\s+/ /g;
    $line =~ s/^\s+//;
    $line =~ s/\s*$/\n/;
    return $line;
}

sub wrap ($) {
    my @words = split m|\s+|, shift;
    my $result = "";

    do {
	my $length = 0;
	my @line;
	while ($length < 80 && @words) {
#	    print "$result*\n@line\n*\n@words\n****\n";
	    my $word = shift @words;
	    $length += 1 + length $word;
	    push @line, $word;
	}
	unshift @words, pop @line if @words || $length > 79;
	my $line = join ' ', @line;
	$result .= $line . "\n";
#	print "$result*\n@words\n********\n";
    } while (@words);
    return $result;
}

sub offshore () {
    my $url = 'http://www.metoffice.gov.uk/weather/marine/shipping_printable.html';
    my $content = qx{wget -q -O- $url} or die;
    $content =~ s{<h2>The area forecasts for the next 24 hours</h2>}{}i;
    my @area;
    push @area, "$1: $2."
	while $content =~ m{<h3>(.*?)(?:[&].*?)?</h3>\s*<p>(.*?)</p>}g;
    return @area;
}

if ($a or $r) {
    my $w = $r ? \&nowrap : \&wrap;
    my @area = map &$w($_), offshore;
    print join "----\n", "", @area, "";
} else {
    my @area = offshore;
    my $message = wrap $area[rand @area];
    print "\nTony.\n-- \nf.anthony.n.finch  <dot\@dotat.at>  http://dotat.at/\n$message";
}
exit;
