#!/usr/bin/perl

use strict;
use LWP::UserAgent;
use HTTP::Request;

my $ua = new LWP::UserAgent;

my $freq;
my $pol;
my $fec;
my $symrate;
my $col;
my $channel;
my $vpid;
my $apid;
my $sid;

my $sat = "S1.0W";
my $url = "http://www.lyngsat.com/packages/canaldigital.html";
my $request = new HTTP::Request ('GET', $url);
my $res = $ua->request($request)->content;
$res = substr($res,index($res,"colspan"));
my @tags = split("<", $res);

foreach (@tags) {
    if (substr($_,0,2) eq "td" && !($col > 1 && $channel eq "")) {
	$col ++;
    }
    elsif (substr($_,0,2) eq "tr") {
	$col=0;
	if (length($channel)*$freq*length($pol)*$symrate*$vpid*$apid*$sid > 0) {
	    printf "$channel:$freq:$pol$fec:$sat:$symrate:$vpid:$apid:0:0:$sid:0:0:0\n";
	}
	$channel="";
	$vpid=0;
	$apid=0;
	$sid=0;
    }
    my @tag = split(">", $_);
    if ($#tag>0 && length($tag[1]) > 2) {
	my @row = split(" ",$tag[1]);
	if ($col == 1) {
	    if (("$row[1]" eq "V") || ("$row[1]" eq "H")) {
		$freq = $row[0];
		$symrate=0;
		$fec="";
	        if ("$row[1]" eq "V") {
		    $pol = "v";
		} elsif ("$row[1]" eq "H") {
		    $pol = "h";
		}
	    } elsif ("$row[0]" eq "SR") {
		$symrate = $row[1];
	    } elsif ("$row[0]" eq "FEC") {
		$fec = "C78" if (index($row[1],"8") >= 0);
		$fec = "C23" if (index($row[1],"2") >= 0);
	    }
	} elsif ($col == 2) {
	    $channel .= $tag[1];
	} elsif ($col == 5) {
	    my $tmp = rindex($row[0],";");
	    if ($tmp < 0) {
		$sid = $row[0];
	    } else {
		$sid = substr($row[0],$tmp+1);
	    }
	} elsif ($col == 6) {
	    my $tmp = rindex($row[0],";");
	    if ($tmp < 0) {
		$vpid = $row[0];
	    } else {
		$vpid = substr($row[0],$tmp+1);
	    }
	} elsif ($col == 7) {
	    my $tmp = rindex($row[0],";");
	    if ($tmp < 0) {
		$apid = $row[0];
	    } else {
		$apid = substr($row[0],$tmp+1);
	    }
	}
    }
}
