/*  Simple example of using multiple 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 */
	char    temp[128];                  /* Space to retrieve the data from the PrefsHandle */
	LONG    en;                         /* The current entry number within the Tag */


	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 = 2;

			/* We keep track of the current entry number so that we can keep on adding
			 * at the end of the list of data items. You can of course pass any entry
			 * number and the data will be inserted in the correct place in the list,
			 * unless the data item already exists and the size is the same, in which
			 * case the old data will be overwritten
			 */
			en = 0;

			/* A loop which allows the user to enter some data to be stored */
			do
			{
				/* Prompt user and get a string from them */
				printf("Enter a string or leave blank to quit and press return:\n    ");
				gets(temp);

				/* If the string is empty we do not do anything with it, as that
				 * is the condition for quitting the loop
				 */
				if(strlen(temp) > 0)
				{
					SetEntry(prefhandle, ID, Tag, temp, strlen(temp)+1, en);
					en++;
				}
			} while(strlen(temp) > 0);


			/* Now we will show each data item in turn, as well as removing it,
			 * this means we do not need to play around with entry numbers here
			 */
			while(GetEntry(prefhandle, ID, Tag, temp, 128, 0) > 0)
			{
				printf("Retrieved: %s\n", temp);
				if(RemEntry(prefhandle, ID, Tag, 0)) printf("Entry removed\n"); else printf("Entry not removed\n");
			}


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

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

