#!/usr/bin/perl
#Downloads stock quotes from Yahoo for Bilberg
#By James Stanley
#No license - Use as you wish

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use URI::Escape;

my $ua = LWP::UserAgent->new();
$ua->agent("bilberg/0.2 (jamesstanley@bluebottle.com)");

open(SYMBOLS, "symbols.txt");

$string = "";

while(<SYMBOLS>) {
  chomp;
  $string .= "$_+";
}

close(SYMBOLS);

$string = substr($string, 0, length($string)-1);

$page = $ua->get("http://download.finance.yahoo.com/d/quotes.csv?s=$string&f=l1ns")->content;

open(QUOTES, ">quotes.csv");
print QUOTES $page;
close(QUOTES);

open(QUOTES, "quotes.csv");

while(<QUOTES>) {
  chomp;
  $comma = index($_, ",");
  $speechmark = index($_, "\"", $comma+2);
  $quote = substr($_, 0, $comma);
  $name = substr($_, $comma+2, $speechmark-$comma-2);
  $comma = index($_, ",", $speechmark);
  $symbol = substr($_, $comma+2, length($_)-($comma+2)-2);
  open(QUOTE, ">quotes/$symbol");
  print QUOTE "$quote\n";
  $name = trim($name);
  print QUOTE "$name\n";
  close(QUOTE);
}

close(QUOTES);

# Perl trim function to remove whitespace from the start and end of the string - http://www.somacon.com/p114.php
sub trim($)
{
        my $string = shift;
        $string =~ s/^\s+//;
        $string =~ s/\s+$//;
        return $string;
}
