/*
 * refactoring example, improved version
 * http://www.informit.com/articles/article.aspx?p=167891&seqNum=1
 * "What Is Refactoring?" by William C. Wake.
 *
 */

import java.io.*;
import java.util.*;
/** Replace %CODE% with requested id, and 
%ALTCODE% w/"dashed" version of id.*/

public class CodeReplacer {
  String sourceTemplate;

  public CodeReplacer(Reader reader) throws IOException {
    sourceTemplate = readTemplate(reader);
  }

  String readTemplate(Reader reader) throws IOException {
    BufferedReader br = new BufferedReader(reader);
    StringBuffer sb = new StringBuffer();
    try {
      String line = br.readLine();
      while (line!=null) {
	sb.append(line);
	sb.append("\n");
	line = br.readLine();
      }
    } finally {
      try {if (br != null) br.close();} 
      catch (IOException ioe_ignored) {}
    }
    return sb.toString();
  }

  void substituteCode (String template, String pattern,
		       String replacement, Writer out)
      throws IOException {
    int templateSplitBegin = template.indexOf(pattern);
    int templateSplitEnd = 
	templateSplitBegin + pattern.length();
    out.write(template.substring(0, templateSplitBegin));
    out.write(replacement);
    out.write(template.substring(
				 templateSplitEnd, template.length()));
    out.flush();
  }

  public void substitute(String reqId, PrintWriter out)
      throws IOException {
    StringWriter templateOut = new StringWriter();
    substituteCode(sourceTemplate, "%CODE%", 
		   reqId, templateOut);

    String altId = reqId.substring(0,5) + "-" + 
	reqId.substring(5,8);
    substituteCode(templateOut.toString(), "%ALTCODE%",
		   altId, out);
  }
}
