#include "Glue.h"
#include "Gain.h"
#include "ModSetups.h"

#define	kNumDialogItems	3


pascal OSErr settings(ModParamsPtr modInfo, GluePtr glue, ModSettingsHandle *prefs)
{
	ItemInfoHandle	myItemInfo;
	long			myGain;
	OSErr			error;
	
	
	// load the last used settings.
	
	error = GetModSettings(modInfo, glue, prefs);
	if (error)
		return error;
	
	myGain = (**prefs)->gain;
	DisposHandle((Handle)*prefs);
	*prefs = 0L;
	
	
	// set up and show the settings dialog.
	
	myItemInfo = (ItemInfoHandle)NewHandleClear(sizeof(ItemInfoRec) * kNumDialogItems);
	if (myItemInfo == 0L)
		return kModNotEnoughMemory;
	
	(*myItemInfo)[0].type = type_ignore;
	(*myItemInfo)[0].param = 0L;
	(*myItemInfo)[1].type = type_ignore;
	(*myItemInfo)[1].param = 0L;
	(*myItemInfo)[2].type = type_editFieldNumerical;
	(*myItemInfo)[2].param = (long)&myGain;
	
	error = (*glue->ModDoSettingsDialog)(modInfo, myItemInfo, false, 0L, 0L, 0L);
	DisposHandle((Handle)myItemInfo);
	if (error)
		return error;
	
	
	// save the new settings in the *prefs handle.
	
	*prefs = (ModSettingsHandle)NewHandle(sizeof(ModSettingsRec));
	if (*prefs)
	{
		if (myGain > 32767)
			myGain = 32767;
		(**prefs)->gain = myGain;
		
		error = (*glue->SaveEffectSettings)(kModSignature, prefs);
		
		// we must not dispose of the handle, since the ÔeffectÕ routine may be called
		// immediately after us, and itÕll need it. If the handle  is not needed, it
		// will be automatically disposed of.
	}
	else
		return kModNotEnoughMemory;
	
	return noErr;
}


pascal OSErr GetModSettings(ModParamsPtr modInfo, GluePtr glue, ModSettingsHandle *prefs)
{
	// this routine loads the settings. If no settings can be found, but the
	// module requires them, it has to store default settings in a new handle.
	//
	// If the module doesnÕt require any parameters, this routine can just return.
	
	OSErr		error;
	
	error = (*glue->LoadEffectSettings)(kModSignature, prefs);
	if (error || *prefs == 0L)
	{
		*prefs = (ModSettingsHandle)NewHandle(sizeof(ModSettingsRec));
		
		if (*prefs)
		{
			// Set the default settings.
			
			(**prefs)->gain = 200;
			
			error = kModNoError;
		}
		else
			error = kModNotEnoughMemory;
	}
	
	return error;
}