/*
 * Java Network Programming, Second Edition
 * Merlin Hughes, Michael Shoffner, Derek Hamner
 * Manning Publications Company; ISBN 188477749X
 *
 * http://nitric.com/jnp/
 *
 * Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner;
 * all rights reserved; see license.txt for details.
 */

import java.io.*;

public class PushbackProcessor {
  public static InputStream process (InputStream in) throws IOException {
    PushbackInputStream pushbackIn = new PushbackInputStream (in, 2);
    if (processorA (pushbackIn)) {
      return null;
    } else if (processorXY (pushbackIn)) {
      return null;
    } else {
      return pushbackIn;
    }
  }

  protected static boolean processorA (PushbackInputStream pushbackIn) throws IOException {
    int chr = pushbackIn.read ();
    if (chr == 'A') {
      // read from pushbackIn
      return true;
    } else {
      if (chr != -1)
        pushbackIn.unread (chr);
      return false;
    }
  }
  
  protected static boolean processorXY (PushbackInputStream pushbackIn) throws IOException {
    byte[] buffer = new byte[2];
    int numberRead = pushbackIn.read (buffer);
    if ((numberRead == 1) && (pushbackIn.read (buffer, 1, 1) == 1))
      ++ numberRead;
    if ((numberRead == 2) && (buffer[0] == 'X') && (buffer[1] == 'Y')) {
      // read from pushbackIn
      return true;
    } else {
      if (numberRead > 0)
        pushbackIn.unread (buffer, 0, numberRead);
      return false;
    }
  }
}
