/*  Simple example of loading and saving preference files. */

/* Always included first */
#include <exec/types.h>

/* So we can use the functions from these libraries */
#include <proto/dos.h>
#include <proto/exec.h>
#include <proto/preferences.h>

/* For the MAKE_ID macro */
#include <libraries/iffparse.h>

/* For the PrefsStruct structure */
#include <scalos/preferences.h>

/* some standard stuff */
#include <stdio.h>
#include <string.h>


/* Pointer to the preferences.library base */
struct Library  *PreferencesBase;


int main(void)
{
	STRPTR  prefname = "Example";       /* Name to refer to our PrefsHandle with */
	APTR    prefhandle;                 /* Handle to our preferences set */
	ULONG   ID, Tag;                    /* ID and Tag are used to access a specific preferences item */
	struct PrefsStruct  *prefstruct;    /* Used to find the data in the PrefsHandle */
	char    temp[128];                  /* Space to retrieve the data from the PrefsHandle */
	STRPTR  preffile = "example.prefs"; /* filename to load and save prefs as (does NOT need to be the same as the name of the PrefHandle) */


	if(NULL != (PreferencesBase = OpenLibrary("preferences.library", 39)) )
	{
		/* First we need to allocate a PrefsHandle by name */
		if(NULL != (prefhandle = AllocPrefsHandle(prefname)) )
		{
			printf("PrefsHandle successfully allocated\n");

			/* Try to load preferences from file */
			ReadPrefsHandle(prefhandle, preffile);

			/* We need an ID and Tag value to refer to a specific preference.
			 * so we create that here (you could always just put them in the library calls).
			 * Remember that the ID must be created from 4 ASCII characters and the Tag
			 * cannot be 0
			 */
			ID = MAKE_ID('M','A','I','N');
			Tag = 1;

			/* Use FindPreferences to check that the item has been stored */
			if(NULL != (prefstruct = FindPreferences(prefhandle, ID, Tag)) )
			{
				printf("Preference data found\n");

				/* And to show that the data was actually stored, we get it back
				 * using GetPreferences
				 */
				GetPreferences(prefhandle, ID, Tag, temp, 128);
				printf("Contents of preference data:\n    %s\n", temp);
			}


			/* Now we set a new value for the data */
			printf("Enter new string for pref (blank string to not change value) and press return:\n    ");
			gets(temp);

			if(strlen(temp) > 0)
			{
				SetPreferences(prefhandle, ID, Tag, temp, strlen(temp)+1);

				/* Save the preferences out again. Run this program again if you want to check the changes */
				WritePrefsHandle(prefhandle, preffile);
			}

			/* Finally, we free the PrefsHandle */
			FreePrefsHandle(prefhandle);
		}

		CloseLibrary(PreferencesBase);
	}
	return(0);
}

