void SoundManager::PlayOnce( FMOD::Studio::EventInstance& sound )
	{
		FMOD_STUDIO_PLAYBACK_STATE curState;
		sound.getPlaybackState( &curState );
		if( curState != FMOD_STUDIO_PLAYBACK_PLAYING )
			sound.start();
	}
bool SoundManager::isSoundPlaying(void * soundHandle)
{
#ifdef FMOD_ACTIVE
    FMOD::Studio::EventInstance * instance = static_cast<FMOD::Studio::EventInstance *>(soundHandle);
    if ( nullptr != instance && instance->isValid() )
    {
        FMOD_STUDIO_PLAYBACK_STATE instancePlaybackState;
        instance->getPlaybackState(&instancePlaybackState);
        if (instancePlaybackState == FMOD_STUDIO_PLAYBACK_PLAYING
            || instancePlaybackState == FMOD_STUDIO_PLAYBACK_STARTING
            || instancePlaybackState == FMOD_STUDIO_PLAYBACK_SUSTAINING)
        {
            return true;
        }
        else
        {
            return false;
        }
//        FMOD::ChannelGroup * channelGroup;
//        bool isPlaying;
//        ERRCHECK(instance->getChannelGroup(&channelGroup));
//        ERRCHECK(channelGroup->isPlaying(&isPlaying));
//        return isPlaying;
    }
    else
    {
        return false;
    }
#else
    return false;
#endif
}
void SoundManager::updateSoundParameter(void * soundHandle, const char * paramName, const float paramValue, const bool disableOnMax)
{
#ifdef FMOD_ACTIVE
    FMOD::Studio::EventInstance * instance = static_cast<FMOD::Studio::EventInstance *>(soundHandle);
    if ( nullptr != instance && instance->isValid())
    {
        FMOD::Studio::ParameterInstance * parameter = NULL;
        ERRCHECK(instance->getParameter(paramName, &parameter));
        
        if (!parameter->isValid()) return;
        
        if (disableOnMax)
        {
            FMOD_STUDIO_PLAYBACK_STATE instancePlayState;
            ERRCHECK(instance->getPlaybackState(&instancePlayState));
            
            FMOD_STUDIO_PARAMETER_DESCRIPTION paramDescription;
            ERRCHECK(parameter->getDescription(&paramDescription));
            
            if ((instancePlayState == FMOD_STUDIO_PLAYBACK_PLAYING
                 || instancePlayState == FMOD_STUDIO_PLAYBACK_SUSTAINING)
                && paramValue > paramDescription.maximum)
            {
                instance->stop(FMOD_STUDIO_STOP_IMMEDIATE);
                //CCLOG("Suono disabilitato perché troppo distante");
            }
            else if (instancePlayState == FMOD_STUDIO_PLAYBACK_STOPPED && paramValue < paramDescription.maximum)
            {
                instance->start();
                //CCLOG("Suono riabilitato perché abbastanza vicino");
            }
        }
        ERRCHECK(parameter->setValue(paramValue));
//        ERRCHECK(instance->setParameterValue(paramName, paramValue));
    }
#endif
}
void outputEventByID(FMOD::Studio::System* system, const char* ID)
{
	FMOD_RESULT result;

	FMOD::Studio::ID eventID = { 0 };
	ERRCHECK(system->lookupID(ID, &eventID));  //Lookup the ID string from the banks

											   //Use the ID to get the event
	FMOD::Studio::EventDescription* eventDescription = NULL;
	ERRCHECK(system->getEventByID(&eventID, &eventDescription));

	// Create an instance of the event
	FMOD::Studio::EventInstance* eventInstance = NULL;
	ERRCHECK(eventDescription->createInstance(&eventInstance));
	
	//Preload sample data - otherwise some sounds just dont play
	//eventDescription->loadSampleData(); Done need this -  docs say it starts loading sample as soon as eventinstance created
	FMOD_STUDIO_LOADING_STATE  loadingState = FMOD_STUDIO_LOADING_STATE_LOADING;
	system->update();
	ERRCHECK(eventDescription->getSampleLoadingState(&loadingState));
	while (loadingState != FMOD_STUDIO_LOADING_STATE_LOADED)
	{
		//if (eventDescription->getSampleLoadingState(&loadingState)  == FMOD_OK)
		//{
		//	system->update();
		//}
		//else
		//{}
		//Sleep(1);
		ERRCHECK(eventDescription->getSampleLoadingState(&loadingState));
		system->update();
	}

	//Try and stop looping :~ failed
	//FMOD::ChannelGroup* Channels = NULL;
	//eventInstance->getChannelGroup(&Channels);
	//Channels->setMode(FMOD_LOOP_OFF);


	cout << "Dumping " << ID << endl;

	//TODO - delete file if length is 0 - no point having empty files around
	int length = 0;
	result = eventDescription->getLength(&length);
	if (length == 0)
	{
		return;
	}
	float rate = 1024.0f / 48000.0f;
	float newlength = (float)length / 1000; //turn length into seconds
	float totalCalls = (newlength) / rate; // calculate how many calls of our loop we need till the sound has been played
	float totalTime = 0.0f;
	//bool played = false;
	//OutputDebugString(ID); OutputDebugString("\n");

	//Start playback
	ERRCHECK(eventInstance->start()); //starting here seems to work ok
	
	FMOD_STUDIO_PLAYBACK_STATE playbackState = FMOD_STUDIO_PLAYBACK_STOPPED;
	//system->update();
	eventInstance->getPlaybackState(&playbackState);
	while (playbackState != FMOD_STUDIO_PLAYBACK_PLAYING)
	{
		eventInstance->getPlaybackState(&playbackState);
		system->update();
	}

	int TimelinePos = 0;
	int LastPos = -1;
	//for (int i = 0; i < totalCalls; i++)
	while (TimelinePos < length)
	{
		// if(1000 <= totalTime && !played)
		// {
		//// play sound just once
		//  //ERRCHECK( eventInstance->start() );
		//played = true;
		// }


		eventInstance->getTimelinePosition(&TimelinePos);
		char buffer[255 + 1];
		sprintf(buffer, "Timeline Position is %d\n", TimelinePos);
		OutputDebugString(buffer);

		if (LastPos > TimelinePos) //Looping sounds repeat it seems eg mus_loop_tense never reaches timelinepos then starts again
		{
			break;
		}
		LastPos = TimelinePos;
		system->update();
		Sleep(1);
		//Sleep(1.5); //Crucial! Slows it down enough so that sounds start and end at correct time
					//Big hack but still cant fix it. Tried with callbacks and other methods - this
					//Is the only way that 'reliably' works
		//totalTime += (rate * 1000);
		//sprintf(buffer, "TotalTime Position is %f\n", totalTime);
		//OutputDebugString(buffer);
	}

	eventInstance->stop(FMOD_STUDIO_STOP_ALLOWFADEOUT); //FMOD_STUDIO_STOP_ALLOWFADEOUT 

	playbackState = FMOD_STUDIO_PLAYBACK_STOPPING;
	while (playbackState != FMOD_STUDIO_PLAYBACK_STOPPED)
	{
		eventInstance->getPlaybackState(&playbackState);
		system->update();
	}

	eventInstance->release(); //necessary?????
	eventDescription->unloadSampleData();

	system->update();
	loadingState = FMOD_STUDIO_LOADING_STATE_LOADED;
	while (loadingState != FMOD_STUDIO_LOADING_STATE_UNLOADED)
	{
		if (eventDescription->getSampleLoadingState(&loadingState) == FMOD_OK)
		{
			//system->update();
		}
		else
		{
		}
	}

	//eventDescription->releaseAllInstances;
}
bool outputEventByID(FMOD::Studio::System* system, const char* ID)
{
	FMOD_RESULT result;

	FMOD::Studio::ID eventID = { 0 };
	ERRCHECK(system->lookupID(ID, &eventID));  //Lookup the ID string from the banks

	//Use the ID to get the event
	FMOD::Studio::EventDescription* eventDescription = NULL;
	ERRCHECK(system->getEventByID(&eventID, &eventDescription));

	// Create an instance of the event
	FMOD::Studio::EventInstance* eventInstance = NULL;
	ERRCHECK(eventDescription->createInstance(&eventInstance));
	
	//Preload sample data - otherwise some sounds just dont play
	//eventDescription->loadSampleData(); Done need this -  docs say it starts loading sample as soon as eventinstance created
	FMOD_STUDIO_LOADING_STATE  loadingState = FMOD_STUDIO_LOADING_STATE_LOADING;
	system->update();
	ERRCHECK(eventDescription->getSampleLoadingState(&loadingState));
	while (loadingState != FMOD_STUDIO_LOADING_STATE_LOADED)
	{
		ERRCHECK(eventDescription->getSampleLoadingState(&loadingState));
		system->update();
	}

	
	int length = 0;
	result = eventDescription->getLength(&length);
	if (length == 0)
	{
		return false; 
	}


	cout << "Dumping " << ID << endl;

	int TimelinePos = 0;
	int LastPos = -1;
	bool played = false;

	while (TimelinePos < length)
	{
		if (!played)
		{
			ERRCHECK(eventInstance->start()); //Start playback
			played = true;
		}
		
		eventInstance->getTimelinePosition(&TimelinePos);
		//char buffer[255 + 1];
		//sprintf(buffer, "Timeline Position is %d\n", TimelinePos);
		//OutputDebugString(buffer);

		if (LastPos > TimelinePos) //Looping sounds repeat and have wrong getlength value eg mus_loop_tense never reaches timelinepos 
		{						   //Seems to report a longer length than reality. So if we dont manually stop it, the track loops forever
			break;
		}
		LastPos = TimelinePos;
		system->update();
		Sleep(1);   //Crucial! Slows it down enough so that sounds start and end at correct time
					//Big hack but still cant fix it. Tried with callbacks and other methods - this
					//Is the only way that 'reliably' works
	}

	eventInstance->stop(FMOD_STUDIO_STOP_IMMEDIATE); //FMOD_STUDIO_STOP_ALLOWFADEOUT 
	FMOD_STUDIO_PLAYBACK_STATE playbackState = FMOD_STUDIO_PLAYBACK_STOPPING;
	while (playbackState != FMOD_STUDIO_PLAYBACK_STOPPED)
	{
		eventInstance->getPlaybackState(&playbackState);
		system->update();
	}

	eventInstance->release(); //necessary?????
	eventDescription->unloadSampleData();

	system->update();
	loadingState = FMOD_STUDIO_LOADING_STATE_LOADED;
	while (loadingState != FMOD_STUDIO_LOADING_STATE_UNLOADED)
	{
		if (eventDescription->getSampleLoadingState(&loadingState) == FMOD_OK)
		{
			//system->update();
		}
		else
		{
		}
	}

	//eventDescription->releaseAllInstances;
	return true;
}