import java.applet.*;
import java.awt.*;
import java.awt.image.*;

class AnimatedSprite extends Sprite {

  int frames;         // frames in sprite
  int current_track; 


  class TrackState {
    public int[] frame;
    public int[] ticks;
    public int[] dx;
    public int[] dy;

    public int counter;  // to be added 
    public int index; // to be drawn

    public TrackState() {

      //      System.err.println(String.valueOf(frames));

      this.frame = new int[frames];
      this.ticks = new int[frames];
      this.dx = new int[frames];
      this.dy = new int[frames];
      counter = 0; // to be added
      index = 0; // to be drawn
    
    }

    public int currentTicks() {
      return ticks[index];
    }

    public int currentFrame() {
      return frame[index];
    }
	
	
    public void addFrame(int frame_p, int ticks, int dx, int dy) {
      /*      System.err.println(String.valueOf(frames));
      System.err.println(String.valueOf(counter));
      System.err.println(String.valueOf(frame.length)); */
      
      frame[counter] = frame_p;
      this.ticks[counter] = ticks;
      this.dx[counter] = dx;
      this.dy[counter] = dy;

      counter++;
      
    }
    
  }

  // there are other private variables

  private Sprite[] sprites;
  private TrackState[] tracks;

              
  public AnimatedSprite(Image images, int frames) {
    super(images);

    this.frames = frames;

    tracks = new TrackState[20]; // limit of 20
    for (int i = 0; i < 20; i ++) {
      tracks[i] = new TrackState();
    }
    this.sprites = new Sprite[frames];

    try {
      PixelGrabber grabber = new PixelGrabber(images,0,0,-1,-1,true);
      if (grabber.grabPixels()) {
	int width = grabber.getWidth();
	int height = grabber.getHeight();
	int frame_width = width / frames;

	for (int i = 0; i< frames; i++) {
	  try {
            PixelGrabber grabber2 = new PixelGrabber(images, i * frame_width, 0,
						     frame_width, -1, true);
            if (grabber2.grabPixels()) {
	      Sprite spr = new Sprite();
	      spr.pixel = (int []) grabber2.getPixels();
	      this.sprites[i] = spr;
            }
	  } catch (InterruptedException e) { }
        
	}
      }
    } catch (InterruptedException e) { }
  }


  public int currentTicks() {
    return tracks[current_track].currentTicks();
  }

  public void addState(int track, int frame, int ticks, int dx, int dy) {
    TrackState ts = tracks[track];
    ts.addFrame(frame,ticks,dx,dy);
  }

  public void Draw(Raster bgnd) {
    sprites[tracks[current_track].currentFrame()].Draw(bgnd);
  }
    
  
  
  public void nextState() {
    tracks[current_track].counter++;
  }


  public void setTrack(int track) {
    current_track = track;
    tracks[track].index = 0;
  }
  
};


    
