import java.io.InputStream;
import com.sun.java.swing.JTextArea;

// URL url= new URL("http://...");
// Parser parser= new Parser(url.openStream());
// while (parser.findTag()!=null) ...

public class Parser
{
  InputStream is;
  JTextArea log;

  public Parser(InputStream is, JTextArea log)
    {
      this.is= is;
      this.log= log;
    }

  public StringBuffer findTag() // Trouve le mot cle, null si fin
    {
      StringBuffer sb;
      int i;

      try
	{
	  while ((i= is.read())!=-1)
	    switch (Character.toUpperCase((char)i))
	      {
	      case 'B': //BACKGROUND
		if ((i= is.read())!=-1 && Character.toUpperCase((char)i)=='A' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='C' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='K' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='G' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='R' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='O' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='U' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='N' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='D')
		  if ((sb= findVal())!=null)
		    return sb;
		break;
	      case 'H': //HREF
		if ((i= is.read())!=-1 && Character.toUpperCase((char)i)=='R' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='E' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='F')
		  if ((sb= findVal())!=null)
		    return sb;
		break;
	      case 'S': //SRC
		if ((i= is.read())!=-1 && Character.toUpperCase((char)i)=='R' &&
		    (i= is.read())!=-1 && Character.toUpperCase((char)i)=='C')
		  if ((sb= findVal())!=null)
		    return sb;
		break;
	      }
	}
      catch (java.io.IOException x) { log.append("Oooops !\n"); }
      return null;
    }

  StringBuffer findVal() // Extrait la valeur associee au mot cle, null si invalide
    {
      StringBuffer sb= new StringBuffer();
      int i;

      try
	{
	  while ((i= is.read())!=-1 && (char)i==' ');
	  if (i==-1 || (char)i!='=')
	    return null;
	  while ((i= is.read())!=-1 && (char)i==' ');
	  if (i==-1 || (char)i!='"')
	    return null;
	  while ((i= is.read())!=-1 && (char)i!='"' && (char)i!='\n' && (char)i!='>')
	    sb.append((char)i);
	  return sb;
	}
      catch (java.io.IOException x) { log.append("Oooops !\n"); }
      return null;
    }
}
