#!/Perl

# from : http://www.foo.be/docs/tpj/issues/vol3_2/tpj0302-0008.html
# http://www.cbot.com/mplex/quotes/tsfut/tsf$Contract.htm
###print "Hello, World...\n";
my $Contract = "12345678";

#use LWP::Simple;
#my $URL = 'http://www.cbot.com/mplex/quotes/tsfut';
#my $text = get("$URL/tsf$Contract.htm");

#
#use Win32::Internet;
#my $URL = 'http://www.cbot.com/mplex/quotes/tsfut';
#my $text = $Win32::Internet->new->FetchURL("$URL/tsf$Contract.htm");


my @Bars = ();

my $text = "03/12/1998 US 98Mar 12116 15:28:34 Open\n";
$text .= "03/12/1998 US 98Mar 12117 15:43:34 Open\n";
$text .= "03/12/1998 US 98Mar 12118 15:58:34 Open\n";
$text .= "03/12/1998 US 98Mar 12120 16:03:34 Open\n";
$text .= "03/12/1998 US 98Mar 12118 16:18:34 Open\n";
$text .= "03/12/1998 US 98Mar 12110 16:23:34 Open\n";
$text .= "03/12/1998 US 98Mar 12105 16:38:34 Open\n";

my $cyc = 0;
foreach (split "\n", $text) {
    # 03/12/1998 US 98Mar 12116 15:28:34 Open
    my ($Date,$Price,$Hour,$Min,$Sec,$Ind) =
         m|^\s*(\d+/\d+/\d+) # " 03/12/1998"
            \s+US\s+\S+\s+(\d+) # " US 98Mar 12116"
            \s+(\d+):(\d+):(\d+) # " 12:42:40"
            \s*(.*)$|x; # " Ask"

	$cyc++;
    next unless defined $Date;
    $Day = $Date;
	if (defined $Time) {
		print "$cyc Time1 is defined as $Time ...\n";
	} else {
		print "$cyc Time1 is NOT defined ...\n";
	}
	
    # Convert from fractional to decimal format
    $Price = int($Price/100) + ($Price%100)/32;
	
    # Round up time to next multiple of 15 minutes
    my $NewTime = int(($Sec+$Min*60+$Hour*3600)/900+1)*900;
    unless (defined $Time && $NewTime == $Time) {
		if (defined $Time) {
			print "$cyc Pushing $hhmm, $Open, $High, $Low, $Close ...\n";
		} else {
			print "$cyc Time2 is NOT defined ...\n";
		}
        push @Bars, [$hhmm, $Open, $High, $Low, $Close]
                                          if defined $Time;
        $Open = $High = $Low = $Close = undef;
		if (defined $Time) {
			print "$cyc Time changed from $Time to $NewTime ...\n";
		} else {
			print "$cyc Time NOT defined, being set to $NewTime ...\n";
		}

        $Time = $NewTime;
        my $Hour = int($Time/3600);
        $hhmm = sprintf "%02d:%02d", $Hour, $Time/60-$Hour*60;
    }
	
    # Update 15 minute bar values
    $Close = $Price;
    $Open = $Price unless defined $Open;
    $High = $Price unless defined $High && $High > $Price;
    $Low = $Price unless defined $Low && $Low > $Price;
	print "$cyc Next $hhmm, $Open, $High, $Low, $Close ...\n";
	if (defined $Time) {
		print "$cyc Time3 is defined as $Time ...\n";
	} else {
		print "$cyc Time2 is NOT defined ...\n";
	}

}

die "No data found" unless defined $Time;
print "Pushing $hhmm, $Open, $High, $Low, $Close ...\n";
push @Bars, [$hhmm, $Open, $High, $Low, $Close];

