/*
===================
idSWFSpriteInstance::Run
===================
*/
bool idSWFSpriteInstance::Run() {
	if ( !isVisible ) {
		return false;
	}

	if ( childrenRunning ) {
		childrenRunning = false;
		for ( int i = 0; i < displayList.Num(); i++ ) {
			if ( displayList[i].spriteInstance != NULL ) {
				Prefetch( displayList[i].spriteInstance, 0 );
			}
		}
		for ( int i = 0; i < displayList.Num(); i++ ) {
			if ( displayList[i].spriteInstance != NULL ) {
				childrenRunning |= displayList[i].spriteInstance->Run();
			}
		}
	}
	if ( isPlaying ) {
		if ( currentFrame == frameCount ) {
			if ( frameCount > 1 ) {
				FreeDisplayList();
				RunTo( 1 );
			}
		} else {
			RunTo( currentFrame + 1 );
		}
	}
	return childrenRunning || isPlaying;
}
/*
========================
idSWFSpriteInstance::~idSWFSpriteInstance
========================
*/
idSWFSpriteInstance::~idSWFSpriteInstance() {
	if ( parent != NULL ) {
		parent->scriptObject->Set( name, idSWFScriptVar() );
	}
	FreeDisplayList();
	displayList.Clear();
	scriptObject->SetSprite( NULL );
	scriptObject->Clear();
	scriptObject->Release();
	actionScript->Release();
}
/*
===================
idSWFSpriteInstance::RunTo
===================
*/
void idSWFSpriteInstance::RunTo( int targetFrame )
{
	if( targetFrame == currentFrame )
	{
		return; // otherwise we'll re-run the current frame
	}
	if( targetFrame < currentFrame )
	{
		FreeDisplayList();
	}
	if( targetFrame < 1 )
	{
		return;
	}
	
	if( targetFrame > sprite->frameOffsets.Num() - 1 )
	{
		targetFrame = sprite->frameOffsets.Num() - 1;
	}
	
	//actions.Clear();
	
	uint32 firstActionCommand = sprite->frameOffsets[ targetFrame - 1 ];
	
	for( uint32 c = sprite->frameOffsets[ currentFrame ]; c < sprite->frameOffsets[ targetFrame ]; c++ )
	{
		idSWFSprite::swfSpriteCommand_t& command = sprite->commands[ c ];
		if( command.tag == Tag_DoAction && c < firstActionCommand )
		{
			// Skip DoAction up to the firstActionCommand
			// This is to properly support skipping to a specific frame
			// for example if we're on frame 3 and skipping to frame 10, we want
			// to run all the commands PlaceObject commands for frames 4-10 but
			// only the DoAction commands for frame 10
			continue;
		}
		command.stream.Rewind();
		switch( command.tag )
		{
#define HANDLE_SWF_TAG( x ) case Tag_##x: x( command.stream ); break;
				HANDLE_SWF_TAG( PlaceObject2 );
				HANDLE_SWF_TAG( PlaceObject3 );
				HANDLE_SWF_TAG( RemoveObject2 );
				HANDLE_SWF_TAG( StartSound );
				HANDLE_SWF_TAG( DoAction );
#undef HANDLE_SWF_TAG
			default:
				idLib::Printf( "Run Sprite: Unhandled tag %s\n", idSWF::GetTagName( command.tag ) );
		}
	}
	
	currentFrame = targetFrame;
}