// H3Replace.java
//
// You may use and distribute this example. This program is 
// provided WITHOUT WARRANTY either expressed or implied.
//
// Copyright Henrik Björkman 1997
//
// This program is about the same as H2Replace. The difference 
// is that this program will also need an output filename as 
// argument when started.
//
// This program uses Piped Input and Output Streams to send a 
// stream of data through a number of filter programs. Each of 
// these filter programs is a thread reading from an input and 
// writing to an output stream. For the first filter the input 
// is a file and for the last the output is system out.
//
// History:
// 0.0 Created by Henrik Björkman 1997-12-03 
//     (using code from H2Replace.java)
// 0.1 Added package. Henrik 1998-01-25
// 0.2 Using se.beod.henrik.filter.*. Henrik 1998-06-06


import java.io.*;
import se.beod.henrik.filter.*;



public class H3Replace
{
  static FilterDB db=null;

  PipedInputStream in=null;
  PipedOutputStream out=null;
  PipedInputStream next_in=null;

  static void error(String str)
  {
    System.err.println("H3Replace: " + str);
  }

  static void debug(String str)
  {
    //error(str);
  }

  // This function is called before each filter thread is created
  // To create an input output pair of piped stream and set up the
  // in and out to be used by the filter thread to be started.
  void setupInOut() throws IOException
  {
    in=next_in;
    out=new PipedOutputStream();
    next_in=new PipedInputStream(out);
  }

  public H3Replace(FilterDB db, String in_file_name, String out_file_name)
  {
    Thread last_thread=null;
    try 
    {
      setupInOut();
      new WordParse(new FileInputStream(in_file_name),out);

      setupInOut();
      new MultiReplacer(in,out,db);

      setupInOut();
      last_thread=new LineMerge(in,new FileOutputStream(out_file_name));  

      try 
      {
        /* Now just wait for the last thread to finish (or die) */
        last_thread.join();
      }
      catch (InterruptedException e) {error(""+e);}
    }
    catch (IOException e) {error(""+e);}

  }

  public static void main(String args[]) 
  {
    if (args.length < 3 )
    {
      System.out.println("Usage: java H3Replace <name data file> <in file> <out file>");
      System.exit(0);
    }
        
    db=new FilterDB(args[0]);

    new H3Replace(db,args[1],args[2]);

    debug("end.");
  }
}


