import java.io.*;
import java.net.URL;

public class FoxTrotDownloader
{
  private String pageAddress;
  
  public FoxTrotDownloader()
  {
    pageAddress = "http://www.foxtrot.com/";
  }
  
  public Picture getTodaysCartoon()
  {
    String searchSequence = "&copy;";
    String line;
    
    try {
      
      URL url = new URL( pageAddress );
      
      InputStream source = url.openStream();
      BufferedReader reader = new BufferedReader( new InputStreamReader(source) );
      
      while ( true )
      {
        line = reader.readLine();
        if ( line == null )
          break;
        if (line.indexOf( searchSequence ) >= 0 )
          break;
      }
      
      if ( line == null )
        return new Picture( 10, 10 );
      
      int imageUrlStart = line.indexOf( "src=\"" ) + 5;
      int imageUrlEnd   = line.indexOf( ".gif\"" ) + 4;
      String imageUrl   = line.substring( imageUrlStart, imageUrlEnd );
      // System.out.println( imageUrl );
      
      url = new URL( imageUrl );
      String filename = this.downloadCartoonFrom( url );
      
      Picture result = new Picture( filename );
      result.show();
      return result;
      // return new Picture( filename );
      
    } catch ( FileNotFoundException e ) {
      System.out.println( "Could not open file " + pageAddress );
    } catch ( Exception e ) {
      System.out.println( "Error occurred during download from " + pageAddress );
    }
    
    return null;
  }
  
  private String downloadCartoonFrom( URL url )
  {
    String fullname = url.getFile();
    String [] parts = fullname.split( "/" );
    String filename = parts[parts.length-1];
    
    try {
      InputStream  in  = url.openStream();
      OutputStream out = new FileOutputStream( filename );
      
      byte[] buffer = new byte[4096];
      int bytesRead;
      while ( (bytesRead = in.read(buffer)) != -1 )
        out.write( buffer, 0, bytesRead );
      
      in.close();
      out.close();
    } catch ( Exception e ) {
      System.out.println( "Error occurred in downloadCartoonFrom()" );
    }
    
    return filename;
  }
}
