import browser.Applet;
import awt.Graphics;
import awt.Image;

class HandBell extends Applet implements Runnable {
       static int limitNumber=4;
       static int border=4;

       Thread animeThread=null;
       Image  images[];
       int    maxNumber=0, maxWidth=0, maxHeight=0;
       int    counter=0;
       int    intervalTime;
       String state = null;
       String pitch = null;

       public void init() {
             int  i;
             Integer I;
             String dir = getAttribute("dir");
             String file = getAttribute("file");
             String interval = getAttribute("interval");

             if ( dir == null ) dir = "/~tatsuo/anime";
             if ( file == null ) file = "handbell";
             images = new Image[limitNumber];

             for( i=0; i<limitNumber; i++ ) {
                  images[i] = getImage( dir + "/" + file + (i+1) + ".gif" );
                  if( images[i] == null )  break;

                  maxWidth  = Math.max( maxWidth,  images[i].width  );
                  maxHeight = Math.max( maxHeight, images[i].height );
             }
             maxNumber = i;
             resize( maxWidth + border*2, maxHeight + border*2 );

             if ( interval == null ) interval = "50";
             I = new Integer( interval );
             intervalTime = I.intValue();
             if( intervalTime > 3000 )  intervalTime=3000;
             if( intervalTime < 50   )  intervalTime=50;

             state = getAttribute("state");
             pitch = getAttribute("pitch");
       }

       public void paint( Graphics g ) {

             if( 0 <= counter && counter < maxNumber ) {
                  g.drawImage( images[counter], border, border );
             }
       }

       public void start() {
             if( state.equals("play")
                 || state.equals("Play") || state.equals("PLAY") ) {
                   if( animeThread == null ) {
                         animeThread = new Thread(this);
                         animeThread.start();
                   }
             }
       }

       public void stop() {
             if( animeThread != null ) {
                   animeThread = null;
             }
       }

       public void run() {
             int i;
             if( animeThread.isAlive() ) {
                  for( i=0; i<8; i++ ) {
                       repaint();
                       counter++; counter%=maxNumber;

                       Thread.sleep( intervalTime );
                  }
             }
       }

       public void mouseDown( int x, int y ) {
             play( "/~tatsuo/audio/" + pitch + ".au" );
             if( animeThread == null ) {
                   animeThread = new Thread(this);
                   animeThread.start();
             }
             else if( animeThread.isAlive() ) {
                   animeThread.stop();
             }
             else {
                   animeThread.start();
             }
       }
}

