import java.awt.*;
import java.applet.*;

public class RText3 extends Applet implements Runnable 
{
   String text;
   String fontname;
   int fontstyle;
   int fontsize;
   int sleeptime;
   int strlen;
   Thread th;
   char theChars[];
   int charOffsets[];
   Color colors[];
   int y;
   int phase = 0;
   Image img;
   Graphics gr;
   Font font;
   FontMetrics fm;
   int bgcolor;  

  public void init() {
    float h;
    int xPos=20;
   
    text = getParameter("text");
    fontname = getParameter("fontname");
    fontsize = Integer.valueOf(getParameter("size")).intValue();
    fontstyle = Integer.valueOf(getParameter("style")).intValue();
    sleeptime = Integer.valueOf(getParameter("sleep")).intValue();
    bgcolor = Integer.valueOf(getParameter("bgcolor")).intValue();

    font=new Font(fontname,fontstyle,fontsize);
    fm=getFontMetrics(font);
       
    strlen = text.length();
    theChars =  new char [strlen];
    charOffsets = new int [strlen];
    text.getChars(0,strlen,theChars,0);
    colors = new Color[strlen];

    for (int i = 0; i < strlen; i++) {
      h = ((float)i)/((float)strlen);
      colors[i] = new Color(Color.HSBtoRGB(h,1.0f,1.0f));
      charOffsets[i] = xPos;
      xPos+=fm.charWidth(theChars[i]);
    }

    img = createImage(this.size().width,this.size().height);
    gr = img.getGraphics();
    gr.setColor(new Color(bgcolor));
    gr.fillRect(0, 0, size().width, size().height);
    gr.setFont(font);
  }

  public void start() {
    if(th == null) {
      th = new Thread(this);
      th.start();
    }
  }

  public void stop() {
    if (th != null)
      th.stop();
    th = null;
  }

  public void run() {

    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    
    while (th != null) {
      super.repaint();
	  try {
	    Thread.sleep(sleeptime);
	  }
	  catch (InterruptedException e) { }
    }
  }

  public void update(Graphics g) {
    int x;
    phase--;
    if (phase < 0)
      phase=strlen-1;
    for(int i=0;i<strlen;i++)
     {
       x = charOffsets[i];
       y = fm.getAscent()+5;
       gr.setColor(colors[(phase+i)%strlen]); // värvit liikelle
       
       gr.drawChars(theChars,i,1,x,y);
     }
    paint(g);
  }

  public void paint(Graphics g) {
     g.drawImage(img, 0, 0, size().width, size().height, this);
  }

  
}

