/*  Simple example of using single data items per tag. */

/* 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 */
	STRPTR  prefdata = "This is some example preference data";
	struct PrefsStruct  *prefstruct;    /* Used to find the data in the PrefsHandle */
	char    temp[128];                  /* Space to retrieve the data from the PrefsHandle */
	LONG    datasize;                   /* Size of data retrieved from PrefsHandle */


	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");

			/* 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;

			/* Store the preference data in the PrefsHandle, under the ID and Tag.
			 * The reason we pass a length of strlen()+1 is so that the NULL terminator
			 * for the string will definately be stored as well
			 */
			SetPreferences(prefhandle, ID, Tag, prefdata, strlen(prefdata)+1);

			/* Use FindPreferences to check that the item has been stored */
			if(NULL != (prefstruct = FindPreferences(prefhandle, ID, Tag)) )
			{
				printf("Preference data found\n");
				printf("Size of data stored:   %lu\n", strlen(prefdata)+1);
				printf("Size of preference data: %d\n", prefstruct->ps_Size);

				/* And to show that the data was actually stored, we get it back
				 * using GetPreferences
				 */
				if(0 < (datasize = GetPreferences(prefhandle, ID, Tag, temp, 128)) )
				{
					printf("Bytes retrieved from PrefsHandle: %ld\n", datasize);
					printf("Contents of preference data:\n    %s\n", temp);
				}
			}
			else
			{
				printf("Preference data was not stored :(\n");
			}

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

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

