import java.util.*;


/** Houses static method to get a stock quote 
 * for a given ticker symbol at the time of creation.
  * Requires In.java to compile; download and place it in the same directory.
  * Download site: http://www.cs.princeton.edu/introcs/stdlib/In.java
  * Demo idea due to Sedgewick and Wayne */
public class StockQuote {
   
    
    
    /** = current price of stock with ticker symbol s.
      * Precondition: s is a valid ticker symbol (case doesn't matter):
      * examples:  "goog", "GOOG" "MsFT" */
    public static double getQuote(String s) throws YahooFinanceFailedException, 
    												YahooDataUnparseableException {
        
        double price= 0.0;
        
        // find URL for data
        String url="http://finance.yahoo.com/q?s=" +s; 

        // treat the webpage as a String so we can process it
        String targetText="";
       
        try {
        	targetText= new In(url).readAll();
        }  catch(NullPointerException ne) {
        	// couldn't access the Yahoo finance page
        	throw new YahooFinanceFailedException();
        }

        // pull out the substring corresponding to the price
        try {
        targetText= targetText.substring(targetText.indexOf("Last Trade:"));
        targetText= targetText.substring(0,targetText.indexOf("</span>"));
        targetText= targetText.substring(targetText.lastIndexOf(">")+1);
        } catch(StringIndexOutOfBoundsException e) {
        	// invalid ticker symbol or other problem processing data on the page
        	throw new YahooDataUnparseableException(s);
        }
        
        // convert String in targetText to a double price
        price= Double.parseDouble(targetText);
        return price;
    }
   
 
    
    /** just for private debugging purposes */
    public static void main(String[] args)  {
        //tests of getQuote
        System.out.println("getting a google quote: ");   getQuote("goog");
        System.out.println("getting a MSFT quote: "); getQuote("msft");
        System.out.println("getting an apple quote: ");   getQuote("aapl");
        System.out.println("getting a bogus quote: ");   getQuote("24df234a");
       
    }
    
    
}
