import java.io.*;

public class ImagePageGenerator
{
  private String title;
  private String sourceDirectory;
  private String eoln;
  
  public ImagePageGenerator( String title, String directory )
  {
    this.title = title;
    sourceDirectory = directory;
    eoln = System.getProperty( "line.separator" );

  }
  
  public void writePage()
  {
    String fullname  = sourceDirectory + "index.html";
    try {
      BufferedWriter output = new BufferedWriter(
                                  new FileWriter(fullname) );
      this.writePreamble( output );
      this.writeHeader( output );
      this.writeBody( output );
      this.writePostamble( output );
      output.close();
    } catch (IOException ex) {
      System.out.println( "An error occurred writing the file " + fullname );
    }
  }
  
  // ----- standard helpers
  
  private void writePreamble( BufferedWriter output ) throws IOException
  {
    output.write( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD " +
                  "HTML 4.01 Transition //EN\">" );
    output.newLine();
    output.write( "<HTML>" );
    output.newLine();
  }
  
  private void writeHeader( BufferedWriter output ) throws IOException
  {
    output.write( "<HEAD>" );
    output.newLine();
    output.write( "<TITLE>" );
    output.newLine();
    output.write( title );
    output.newLine();
    output.write( "</TITLE>" );
    output.newLine();
    output.write( "</HEAD>" );
    output.newLine();
  }
  
  private void writePostamble( BufferedWriter output ) throws IOException
  {
    output.write( "</HTML>" );
    output.newLine();
  }
  
  // ----- customized helpers
  
  private void writeBody( BufferedWriter output ) throws IOException
  {
    File     directory = new File( sourceDirectory );
    String[] filenames = directory.list();
    String   name;

    String body = "<BODY>" + eoln +
                  "<H4> Thumbnails from " + sourceDirectory +
                  "</H4>" + eoln;
    
    for (int i = 0; i < filenames.length; i++)
    {
      name = filenames[i];
      if ( name.endsWith(".jpg") )
      {
        body = body + "<P> Filename: " + name +
               "<IMG SRC=\"" + name + "\" HEIGHT=\"150\"" + eoln +
               "     ALT=\"" + name + "\"/> </P>" + eoln;
      }
    }
    
    output.write( body );
  }
}
