/*
**	termPhone.c
**
**	Phonebook support routines
**
**	Copyright © 1990-1992 by Olaf `Olsen' Barthel & MXM
**		All Rights Reserved
*/

#include "termGlobal.h"

	/* Are we using the new includes? */

#ifdef ASLSM_FilterFunc

	/* Undefine the following symbols, the preferences header file
	 * will use the same names and the same values.
	 */

#undef PARITY_NONE
#undef PARITY_EVEN
#undef PARITY_ODD
#undef PARITY_MARK
#undef PARITY_SPACE

	/* Include the preferences header files. */

#include <prefs/prefhdr.h>
#include <prefs/serial.h>

	/* Serial preferences data. */

STATIC BYTE			SerialPrefsRead		= FALSE,
				SerialPrefsReadFailed	= FALSE;
STATIC struct SerialPrefs	SerialPrefs;

	/* ReadSerialPrefs():
	 *
	 *	Reads the default serial preferences settings.
	 */

STATIC BYTE
ReadSerialPrefs(VOID)
{
	struct IFFHandle *Handle;

		/* Allocate an IFF handle. */

	if(Handle = AllocIFF())
	{
			/* Open the preferences settings file. */

		if(Handle -> iff_Stream = Open("ENV:sys/serial.prefs",MODE_OLDFILE))
		{
				/* Make it known as a DOS file handle. */

			InitIFFasDOS(Handle);

				/* Open the file for reading. */

			if(!OpenIFF(Handle,IFFF_READ))
			{
					/* Stop at the `body' chunk. */

				if(!StopChunk(Handle,ID_PREF,ID_SERL))
				{
						/* Look for it... */

					if(!ParseIFF(Handle,IFFPARSE_SCAN))
					{
							/* Read the data. */

						if(ReadChunkBytes(Handle,&SerialPrefs,sizeof(struct SerialPrefs)) == sizeof(struct SerialPrefs))
							SerialPrefsRead = TRUE;
					}
				}

					/* Close the handle. */

				CloseIFF(Handle);
			}

				/* Release the handle. */

			Close(Handle -> iff_Stream);
		}

			/* Clean up. */

		FreeIFF(Handle);
	}

		/* Return sucess/failure. */

	return(SerialPrefsRead);
}

#endif	/* ASLSM_FilterFunc */

	/* SetPrefToDefaults():
	 *
	 *	Initialize configuration with default values.
	 */

VOID
SetPrefToDefaults(struct Configuration *Config,UBYTE *PathBuffer)
{
	if(!PathBuffer)
		PathBuffer = "TERM:config";

	strcpy(Config -> PathConfig . DefaultStorage,PathBuffer);

#ifdef ASLSM_FilterFunc

		/* The program will only try to read the preferences
		 * settings once; if the first access failed, no
		 * other accesses will be made.
		 */

	if(!SerialPrefsRead && !SerialPrefsReadFailed)
		SerialPrefsReadFailed = ReadSerialPrefs() ^ TRUE;

		/* Did we succeed in reading the file? */

	if(!SerialPrefsRead)
	{
		Config -> SerialConfig . BaudRate		= 2400;
		Config -> SerialConfig . BitsPerChar		= 8;
		Config -> SerialConfig . Parity			= PARITY_NONE;
		Config -> SerialConfig . StopBits		= 1;
		Config -> SerialConfig . HandshakingProtocol	= HANDSHAKING_NONE;
		Config -> SerialConfig . xONxOFF		= TRUE;
		Config -> SerialConfig . SerialBufferSize	= 32768;
	}
	else
	{
			/* Fill in the common data. */

		Config -> SerialConfig . BaudRate		= SerialPrefs . sp_BaudRate;
		Config -> SerialConfig . SerialBufferSize	= SerialPrefs . sp_InputBuffer;
		Config -> SerialConfig . BitsPerChar		= SerialPrefs . sp_BitsPerChar;
		Config -> SerialConfig . StopBits		= SerialPrefs . sp_StopBits;

			/* Convert the handshaking mode. */

		switch(SerialPrefs . sp_InputHandshake)
		{
			case HSHAKE_NONE:	Config -> SerialConfig . HandshakingProtocol	= HANDSHAKING_NONE;
						Config -> SerialConfig . xONxOFF		= FALSE;

						break;

			case HSHAKE_RTS:	Config -> SerialConfig . HandshakingProtocol	= HANDSHAKING_RTSCTS;
						Config -> SerialConfig . xONxOFF		= FALSE;

						break;

			default:		Config -> SerialConfig . HandshakingProtocol	= HANDSHAKING_NONE;
						Config -> SerialConfig . xONxOFF		= TRUE;

						break;
		}

			/* Convert the parity settings. */

		if(SerialPrefs . sp_Parity <= PARITY_SPACE)
			Config -> SerialConfig . Parity = SerialPrefs . sp_Parity;
		else
			Config -> SerialConfig . Parity = PARITY_NONE;
	}

#else

	Config -> SerialConfig . BaudRate		= 2400;
	Config -> SerialConfig . BitsPerChar		= 8;
	Config -> SerialConfig . Parity			= PARITY_NONE;
	Config -> SerialConfig . StopBits		= 1;
	Config -> SerialConfig . Handshaking		= HANDSHAKING_XONXOFF;
	Config -> SerialConfig . SerialBufferSize	= 32768;

#endif	/* ASLSM_FilterFunc */

	strcpy(Config -> SerialConfig . SerialDevice,SERIALNAME);

	Config -> SerialConfig . Duplex			= DUPLEX_FULL;
	Config -> SerialConfig . HighSpeed		= FALSE;
	Config -> SerialConfig . Shared			= FALSE;
	Config -> SerialConfig . BreakLength		= 250000;
	Config -> SerialConfig . UnitNumber		= 0;
	Config -> SerialConfig . StripBit8		= FALSE;
	Config -> SerialConfig . CheckCarrier		= FALSE;
	Config -> SerialConfig . PassThrough		= FALSE;

	/* Modem Preferences. */

	strcpy(Config -> ModemConfig . ModemInit,	"ATZ\\r");
	strcpy(Config -> ModemConfig . ModemExit,	"");
	strcpy(Config -> ModemConfig . ModemHangup,	"~~~~~~~~+++\\r~~~~~~ATH0\\r");
	strcpy(Config -> ModemConfig . DialPrefix,	"~~ATDP");
	strcpy(Config -> ModemConfig . DialSuffix,	"\\r");

	strcpy(Config -> ModemConfig . NoCarrier,	"NO CARRIER");
	strcpy(Config -> ModemConfig . NoDialTone,	"NO DIALTONE");
	strcpy(Config -> ModemConfig . Connect,		"CONNECT");
	strcpy(Config -> ModemConfig . Voice,		"VOICE");
	strcpy(Config -> ModemConfig . Ring,		"RING");
	strcpy(Config -> ModemConfig . Busy,		"BUSY");

	Config -> ModemConfig . RedialDelay		= 2;
	Config -> ModemConfig . DialRetries		= 10;
	Config -> ModemConfig . DialTimeout		= 60;
	Config -> ModemConfig . ConnectAutoBaud		= FALSE;
	Config -> ModemConfig . DropDTR			= FALSE;

	/* Screen preferences. */

	Config -> ScreenConfig . DisplayMode		= DEFAULT_MONITOR_ID|HIRES_KEY;
	Config -> ScreenConfig . ColourMode		= COLOUR_AMIGA;
	Config -> ScreenConfig . MakeScreenPublic	= TRUE;
	Config -> ScreenConfig . ShanghaiWindows	= FALSE;
	Config -> ScreenConfig . TitleBar		= TRUE;
	Config -> ScreenConfig . StatusLine		= STATUSLINE_STANDARD;
	Config -> ScreenConfig . Blinking		= TRUE;
	Config -> ScreenConfig . FasterLayout		= FALSE;

	strcpy(Config -> ScreenConfig . FontName,"topaz.font");
	Config -> ScreenConfig . FontHeight = 8;

	/* Terminal prerences. */

	Config -> TerminalConfig . BellMode		= BELL_AUDIBLE;
	Config -> TerminalConfig . AlertMode		= ALERT_BEEP_SCREEN;
	Config -> TerminalConfig . EmulationMode	= EMULATION_ANSIVT100;
	Config -> TerminalConfig . FontMode		= FONT_STANDARD;

	Config -> TerminalConfig . SendCR		= CR_ASCR;
	Config -> TerminalConfig . SendLF		= LF_ASLF;
	Config -> TerminalConfig . ReceiveCR		= CR_ASCR;
	Config -> TerminalConfig . ReceiveLF		= LF_ASLF;

	Config -> TerminalConfig . NumColumns		= 0;	/* = Maximum size. */
	Config -> TerminalConfig . NumLines		= 0;

	Config -> TerminalConfig . KeyMapFileName[0]	= 0;
	Config -> TerminalConfig . EmulationFileName[0]	= 0;
	Config -> TerminalConfig . BeepFileName[0]	= 0;

	strcpy(Config -> TerminalConfig . TextFontName,"topaz.font");
	Config -> TerminalConfig . TextFontHeight = 8;

	/* Emulation settings. */

	Config -> EmulationConfig . CursorMode		= KEYMODE_STANDARD;
	Config -> EmulationConfig . NumericMode		= KEYMODE_STANDARD;

	Config -> EmulationConfig . NewLineMode		= FALSE;
	Config -> EmulationConfig . InsertMode		= FALSE;

	Config -> EmulationConfig . LineWrap		= TRUE;
	Config -> EmulationConfig . CursorWrap		= FALSE;

	Config -> EmulationConfig . FontScale		= SCALE_NORMAL;
	Config -> EmulationConfig . ScrollMode		= SCROLL_JUMP;
	Config -> EmulationConfig . DestructiveBackspace= FALSE;
	Config -> EmulationConfig . SwapBSDelete	= FALSE;
	Config -> EmulationConfig . PrinterEnabled	= TRUE;
	Config -> EmulationConfig . AnswerBack[0]	= 0;

	/* Clipboard settings. */

	Config -> ClipConfig . ClipboardUnit		= 0;
	Config -> ClipConfig . LineDelay		= 0;
	Config -> ClipConfig . CharDelay		= 0;

	Config -> ClipConfig . InsertPrefix[0] = 0;
	strcpy(Config -> ClipConfig . InsertSuffix,"\\r");

	/* Capture and logfile settings. */

	Config -> CaptureConfig . LogActions		= FALSE;
	Config -> CaptureConfig . LogCall		= FALSE;
	Config -> CaptureConfig . LogFileName[0]	= 0;

	Config -> CaptureConfig . MaxBufferSize		= 0;
	Config -> CaptureConfig . BufferEnabled		= TRUE;

	Config -> CaptureConfig . ConnectAutoCapture	= FALSE;
	Config -> CaptureConfig . CaptureFilterMode	= FILTER_BOTH;
	Config -> CaptureConfig . CapturePath[0]	= 0;

	/* File settings. */

	strcpy(Config -> FileConfig . ProtocolFileName,"xprzmodem.library");

	if(!LastTranslation[0])
	{
		strcpy(LastTranslation,PathBuffer);

		AddPart(LastTranslation,"translation.prefs",256);
	}

	strcpy(Config -> FileConfig . TranslationFileName,LastTranslation);

	if(!LastMacros[0])
	{
		strcpy(LastMacros,PathBuffer);

		AddPart(LastMacros,"functionkeys.prefs",256);
	}

	strcpy(Config -> FileConfig . MacroFileName,LastMacros);

	if(!LastFastMacros[0])
	{
		strcpy(LastFastMacros,PathBuffer);

		AddPart(LastFastMacros,"fastmacros.prefs",256);
	}

	strcpy(Config -> FileConfig . FastMacroFileName,LastFastMacros);

	if(!LastCursorKeys[0])
	{
		strcpy(LastCursorKeys,PathBuffer);

		AddPart(LastCursorKeys,"cursorkeys.prefs",256);
	}

	strcpy(Config -> FileConfig . CursorFileName,LastCursorKeys);

	/* Path preferences. */

	Config -> PathConfig . ASCIIUploadPath[0]	= 0;
	Config -> PathConfig . ASCIIDownloadPath[0]	= 0;
	Config -> PathConfig . TextUploadPath[0]	= 0;
	Config -> PathConfig . TextDownloadPath[0]	= 0;
	Config -> PathConfig . BinaryUploadPath[0]	= 0;
	Config -> PathConfig . BinaryDownloadPath[0]	= 0;

	strcpy(Config -> PathConfig . DefaultStorage,PathBuffer);

	GetEnvDOS(Config -> PathConfig . Editor,"EDITOR");

	/* Miscellaneous settings. */

	Config -> MiscConfig . Priority			= 1;
	Config -> MiscConfig . BackupConfig		= FALSE;

	Config -> MiscConfig . OpenFastMacroPanel	= FALSE;
	Config -> MiscConfig . ReleaseDevice		= TRUE;

	Config -> MiscConfig . TransferServer		= TRUE;
	Config -> MiscConfig . EmulationServer		= TRUE;

	Config -> MiscConfig . OverridePath		= TRUE;
	Config -> MiscConfig . AutoUpload		= TRUE;
	Config -> MiscConfig . SetArchivedBit		= FALSE;
	Config -> MiscConfig . IdentifyFiles		= TRUE;

	/* Command preferences. */

	Config -> CommandConfig . StartupMacro[0]	= 0;
	Config -> CommandConfig . LogoffMacro[0]	= 0;
	Config -> CommandConfig . UploadMacro[0]	= 0;
	Config -> CommandConfig . DownloadMacro[0]	= 0;
}

VOID
RemoveDialEntry(LONG Entry)
{
	LONG Count = Phonebook[Entry] -> Count,i;

	for(i = 0 ; i < NumPhoneEntries ; i++)
	{
		if(Phonebook[i] -> Count > Count)
			SPrintf(Phonebook[i] -> Node -> LocalName,"%3ld - %s",Phonebook[i] -> Count--,Phonebook[i] -> Header -> Name);
	}

	Phonebook[Entry] -> Count = -1;

	SPrintf(Phonebook[Entry] -> Node -> LocalName,"      %s",Phonebook[Entry] -> Header -> Name);
}

VOID
RemoveDialNode(struct PhoneNode *Node)
{
	LONG Count = Node -> Entry -> Count,i;

	for(i = 0 ; i < NumPhoneEntries ; i++)
	{
		if(Phonebook[i] -> Count > Count)
			SPrintf(Phonebook[i] -> Node -> LocalName,"%3ld - %s",Phonebook[i] -> Count--,Phonebook[i] -> Header -> Name);
	}

	Node -> Entry -> Count = -1;

	SPrintf(Node -> LocalName,"      %s",Node -> Entry -> Header -> Name);
}

VOID
SortToList(struct PhoneNode *PhoneNode)
{
	if(!DialList)
	{
		if(DialList = (struct List *)AllocVec(sizeof(struct List),MEMF_ANY|MEMF_CLEAR))
			NewList(DialList);
	}

	if(DialList)
	{
		struct PhoneNode *Node = (struct PhoneNode *)DialList -> lh_Head,*NewNode;

		if(NewNode = (struct PhoneNode *)AllocVec(sizeof(struct PhoneNode),MEMF_ANY))
		{
			CopyMem(PhoneNode,NewNode,sizeof(struct PhoneNode));

			while(Node -> VanillaNode . ln_Succ)
			{
				if(Node -> Entry -> Count > NewNode -> Entry -> Count)
				{
					if(Node == (struct PhoneNode *)DialList -> lh_Head)
						AddHead(DialList,&NewNode -> VanillaNode);
					else
						Insert(DialList,&NewNode -> VanillaNode,Node -> VanillaNode . ln_Pred);

					return;
				}

				Node = (struct PhoneNode *)Node -> VanillaNode . ln_Succ;
			}

			AddTail(DialList,&NewNode -> VanillaNode);
		}
	}
}

VOID
FreeDialList()
{
	if(DialList)
	{
		struct PhoneNode *NextNode,*SubNode;

		SubNode = (struct PhoneNode *)DialList -> lh_Head;

		while(SubNode -> VanillaNode . ln_Succ)
		{
			NextNode = (struct PhoneNode *)SubNode -> VanillaNode . ln_Succ;

			FreeVec(SubNode);

			SubNode = NextNode;
		}

		FreeVec(DialList);

		DialList = NULL;
	}
}

	/* CreatePhoneList():
	 *
	 *	Turn the array of pointers to phonebook entries into
	 *	a linked standard Amiga List (gadtools needs this).
	 */

struct List *
CreatePhoneList()
{
	struct List		*PhoneList;
	struct PhoneNode	*PhoneNode;
	LONG			 i;

	if(Phonebook && NumPhoneEntries)
	{
		if(PhoneList = (struct List *)AllocVec(sizeof(struct List) + NumPhoneEntries * sizeof(struct PhoneNode),MEMF_ANY|MEMF_CLEAR))
		{
			NewList(PhoneList);

			PhoneNode = (struct PhoneNode *)(PhoneList + 1);

			for(i = 0 ; i < NumPhoneEntries ; i++)
			{
				if(Phonebook[i] -> Count != -1)
					SPrintf(PhoneNode[i] . LocalName,"%3ld - %s",Phonebook[i] -> Count + 1,Phonebook[i] -> Header -> Name);
				else
					SPrintf(PhoneNode[i] . LocalName,"      %s",Phonebook[i] -> Header -> Name);

				PhoneNode[i] . VanillaNode . ln_Name = PhoneNode[i] . LocalName;

				Phonebook[i] -> Node = &PhoneNode[i];

				PhoneNode[i] . Entry = Phonebook[i];

				AddTail(PhoneList,&PhoneNode[i]);
			}

			return(PhoneList);
		}
	}
	else
	{
		if(PhoneList = (struct List *)AllocVec(sizeof(struct List),MEMF_ANY|MEMF_CLEAR))
		{
			NewList(PhoneList);

			return(PhoneList);
		}
	}

	return(NULL);
}

	/* DeletePhoneList(struct List *PhoneList):
	 *
	 *	Delete the entries listed in the Amiga List
	 *	created by the routine above.
	 */

VOID
DeletePhoneList(struct List *PhoneList)
{
	if(PhoneList)
		FreeVec(PhoneList);
}

	/* Compare(struct PhoneEntry **A,struct PhoneEntry **B):
	 *
	 *	Comparison subroutine required by the QuickSort
	 *	call below.
	 */

STATIC int __stdargs
Compare(struct PhoneEntry **A,struct PhoneEntry **B)
{
		/* Has entry A been selected? */

	if((*A) -> Count == -1)
	{
			/* If entry B isn't selected either, compare the
			 * names lexically, else entry B is supposed
			 * to be `smaller' than entry A.
			 */

		if((*B) -> Count == -1)
			return(Stricmp((*A) -> Header -> Name,(*B) -> Header -> Name));
		else
			return(1);
	}
	else
	{
			/* If entry B isn't selected, entry A is supposed
			 * to be `smaller' than entry B, else return
			 * the difference between both entries.
			 */

		if((*B) -> Count == -1)
			return(-1);
		else
			return((*A) -> Count - (*B) -> Count);
	}
}

	/* SortPhoneEntries():
	 *
	 *	Sorts the current phone list array in ascending order.
	 */

VOID
SortPhoneEntries()
{
	qsort((APTR)Phonebook,NumPhoneEntries,sizeof(struct PhoneEntry *),Compare);
}

	/* FreeTimeDateNode(struct TimeDateNode *Node):
	 *
	 *	Free the memory allocated for a TimeDateNode and
	 *	the associated data table.
	 */

VOID __regargs
FreeTimeDateNode(struct TimeDateNode *Node)
{
	FreeVec(Node -> Table);

	FreeVec(Node);
}

	/* FreeTimeDateList(struct List *List):
	 *
	 *	Free a list of TimeDateNodes.
	 */

VOID
FreeTimeDateList(struct List *List)
{
	struct Node *Node,*NextNode;

	Node = List -> lh_Head;

	while(NextNode = Node -> ln_Succ)
	{
		Remove(Node);

		FreeTimeDateNode((struct TimeDateNode *)Node);

		Node = NextNode;
	}
}

	/* CopyTimeDateList(struct List *From,struct List *To,BYTE SkipFirst):
	 *
	 *	Copies the TimeDateNode list from one location into
	 *	another.
	 */

VOID
CopyTimeDateList(struct List *From,struct List *To,BYTE SkipFirst)
{
	struct TimeDateNode *FromNode,*ToNode;

	FromNode = (struct TimeDateNode *)From -> lh_Head;

	if(SkipFirst)
		FromNode = (struct TimeDateNode *)FromNode -> VanillaNode . ln_Succ;

	while(FromNode -> VanillaNode . ln_Succ)
	{
		if(ToNode = (struct TimeDateNode *)AllocVec(sizeof(struct TimeDateNode),MEMF_ANY))
		{
			CopyMem(FromNode,ToNode,sizeof(struct TimeDateNode));

			ToNode -> VanillaNode . ln_Name = ToNode -> Buffer;

			if(ToNode -> Table = (struct TimeDate *)AllocVec(sizeof(struct TimeDate) * FromNode -> Table[0] . Count,MEMF_ANY))
			{
				CopyMem(FromNode -> Table,ToNode -> Table,sizeof(struct TimeDate) * FromNode -> Table[0] . Count);

				AddTail(To,&ToNode -> VanillaNode);
			}
			else
				FreeVec(ToNode);
		}

		FromNode = (struct TimeDateNode *)FromNode -> VanillaNode . ln_Succ;
	}
}

	/* AdaptTimeDateNode(struct TimeDateNode *Node):
	 *
	 *	Adapt the title and comment of a TimeDateNode.
	 */

VOID
AdaptTimeDateNode(struct TimeDateNode *Node)
{
	UBYTE *Comment = Node -> Header . Comment[0] ? Node -> Header . Comment : LocaleString(MSG_TERMPHONE_NO_COMMENT_TXT);

	if(Node -> Header . Month == -1)
	{
		if(Node -> Header . Day == -1)
			strcpy(Node -> Buffer,LocaleString(MSG_TERMPHONE_STANDARD_SETTINGS_TXT));
		else
			SPrintf(Node -> Buffer,LocaleString(MSG_TERMPHONE_DAYS_TXT),Comment);
	}
	else
		SPrintf(Node -> Buffer,"%2ld %s » %s",Node -> Header . Day,LocaleString(MSG_TERMPHONE_JAN_TXT + Node -> Header . Month),Comment);
}

	/* TimeCompare(struct TimeDate *A,struct TimeDate *B):
	 *
	 *	Comparison routine required by SortTimeTable().
	 */

STATIC int __stdargs
TimeCompare(struct TimeDate *A,struct TimeDate *B)
{
	return(((LONG)A -> Time) - ((LONG)B -> Time));
}

	/* SortTimeTable(struct TimeDateNode *Node):
	 *
	 *	Sort the time table associated with a
	 *	TimeDateNode in ascending order.
	 */

VOID
SortTimeTable(struct TimeDateNode *Node)
{
	qsort((APTR)Node -> Table,Node -> Table[0] . Count,sizeof(struct TimeDate),TimeCompare);
}

	/* BuildTimeList(struct TimeDateNode *Node):
	 *
	 *	Build a read-to-display time table list from a TimeDateNode.
	 */

struct List *
BuildTimeList(struct TimeDateNode *Node)
{
	struct List *List;

	if(List = (struct List *)AllocVec(sizeof(struct List) + Node -> Table[0] . Count * sizeof(struct TimeNode),MEMF_ANY|MEMF_CLEAR))
	{
		struct TimeNode	*Time = (struct TimeNode *)(List + 1);
		LONG		 i;

		NewList(List);

		for(i = 0 ; i < Node -> Table[0] . Count ; i++)
		{
			Time[i] . VanillaNode . ln_Name	= Time[i] . Name;
			Time[i] . Time			= Node -> Table[i] . Time;

			SPrintf(Time[i] . Name,"%2ld:%ld0",Time[i] . Time / 6,Time[i] . Time % 6);

			AddTail(List,&Time[i]);
		}
	}

	return(List);
}

	/* ResizeTimeDateNode(struct TimeDateNode *Node,LONG Count,UBYTE Time):
	 *
	 *	Resize the time table associated with a TimeDateNode.
	 */

BYTE
ResizeTimeDateNode(struct TimeDateNode *Node,LONG Count,UBYTE Time)
{
	if(Count != Node -> Table[0] . Count)
	{
		struct TimeDate *Table;

		if(Table = (struct TimeDate *)AllocVec(sizeof(struct TimeDate) * Count,MEMF_ANY|MEMF_CLEAR))
		{
			LONG i;

			CopyMem(Node -> Table,Table,sizeof(struct TimeDate) * Count);

			if(Count > Node -> Table[0] . Count)
			{
				for(i = Node -> Table[0] . Count ; i < Count ; i++)
				{
					CopyMem(&Node -> Table[0],&Table[i],sizeof(struct TimeDate));

					Table[i] . Time = Time;
				}
			}

			for(i = 0 ; i < Count ; i++)
				Table[i] . Count = Count;

			FreeVec(Node -> Table);

			Node -> Table = Table;

			return(TRUE);
		}
		else
			return(FALSE);
	}
	else
		return(TRUE);
}

	/* DeleteTimeDateNode(struct TimeDateNode *Node,LONG Index):
	 *
	 *	Delete a single timetable entry from a TimeDateNode.
	 */

BYTE
DeleteTimeDateNode(struct TimeDateNode *Node,LONG Index)
{
	struct TimeDate	*Table;
	LONG		 Count = Node -> Table[0] . Count - 1;

	if(Table = (struct TimeDate *)AllocVec(sizeof(struct TimeDate) * Count,MEMF_ANY|MEMF_CLEAR))
	{
		LONG i,j;

		for(i = j = 0 ; i < Node -> Table[0] . Count ; i++)
		{
			if(i != Index)
			{
				CopyMem(&Node -> Table[i],&Table[j],sizeof(struct TimeDate));

				Table[j++] . Count = Count;
			}
		}

		FreeVec(Node -> Table);

		Node -> Table = Table;

		return(TRUE);
	}
	else
		return(FALSE);
}

	/* CreateTimeDateNode(BYTE Month,BYTE Day,UBYTE *Comment,LONG Count):
	 *
	 *	Create a new TimeDateNode including time table entries.
	 */

struct TimeDateNode *
CreateTimeDateNode(BYTE Month,BYTE Day,UBYTE *Comment,LONG Count)
{
	struct TimeDateNode *Node;

	if(Node = (struct TimeDateNode *)AllocVec(sizeof(struct TimeDateNode),MEMF_ANY|MEMF_CLEAR))
	{
		if(Node -> Table = (struct TimeDate *)AllocVec(sizeof(struct TimeDate) * Count,MEMF_ANY|MEMF_CLEAR))
		{
			Node -> VanillaNode . ln_Name			= Node -> Buffer;

			Node -> Header . Month				= Month;
			Node -> Header . Day				= Day;

			Node -> Table[0] . PayPerUnit[DT_FIRST_UNIT]	= 23;
			Node -> Table[0] . SecPerUnit[DT_FIRST_UNIT]	=  6 * 60;
			Node -> Table[0] . PayPerUnit[DT_NEXT_UNIT]	= 23;
			Node -> Table[0] . SecPerUnit[DT_NEXT_UNIT]	=  6 * 60;
			Node -> Table[0] . Time				= DT_GET_TIME( 8,0);
			Node -> Table[0] . Count			= Count;

			if(Count > 1)
			{
				Node -> Table[1] . PayPerUnit[DT_FIRST_UNIT]	= 23;
				Node -> Table[1] . SecPerUnit[DT_FIRST_UNIT]	= 12 * 60;
				Node -> Table[1] . PayPerUnit[DT_NEXT_UNIT]	= 23;
				Node -> Table[1] . SecPerUnit[DT_NEXT_UNIT]	= 12 * 60;
				Node -> Table[1] . Time				= DT_GET_TIME(18,0);
				Node -> Table[1] . Count			= Count;
			}

			strcpy(Node -> Header . Comment,Comment);

			AdaptTimeDateNode(Node);

			return(Node);
		}
		else
			FreeVec(Node);
	}

	return(NULL);
}

	/* RemPhoneEntry(LONG Num):
	 *
	 *	Remove a given entry from the phone book.
	 */

VOID
RemPhoneEntry(LONG Num)
{
	struct PhoneEntry	*Entry;
	LONG			 i;

	Entry = Phonebook[Num];

	for(i = Num ; i < NumPhoneEntries ; i++)
		Phonebook[i] = Phonebook[i + 1];

	Phonebook[NumPhoneEntries--] = NULL;

	FreeTimeDateList((struct List *)&Entry -> TimeDateList);

	FreeVec(Entry);
}

	/* NewPhoneEntry():
	 *
	 *	Create a new phone book entry with default values and
	 *	add it to the array. Expand the phone book if necessary.
	 */

BYTE
NewPhoneEntry()
{
	struct PhoneEntry	**PrivatePhonebook;
	LONG			 PrivatePhoneSize;
	LONG			 i;

		/* The phone book is filled `to the brim', so let's expand
		 * it.
		 */

	if(NumPhoneEntries + 1 > PhoneSize)
	{
			/* Allocate another phone book. */

		if(PrivatePhonebook = CreatePhonebook(PhoneSize + 1,&PrivatePhoneSize,FALSE))
		{
				/* Copy the data. */

			if(Phonebook && PhoneSize)
			{
				for(i = 0 ; i < PhoneSize ; i++)
					PrivatePhonebook[i] = Phonebook[i];

					/* Remove the old phonebook. */

				DeletePhonebook(Phonebook,PhoneSize,FALSE);
			}

				/* Assign the new pointers. */

			Phonebook = PrivatePhonebook;
			PhoneSize = PrivatePhoneSize;
		}
		else
			return(FALSE);
	}

		/* Allocate another entry and add it to the phone book. */

	if(Phonebook[NumPhoneEntries] = (struct PhoneEntry *)AllocVec(sizeof(struct PhoneEntry) + sizeof(struct PhoneHeader) + sizeof(struct Configuration),MEMF_ANY|MEMF_CLEAR))
	{
		struct TimeDateNode *TimeDateNode;

		Phonebook[NumPhoneEntries] -> Header = (struct PhoneHeader *)(Phonebook[NumPhoneEntries] + 1);
		Phonebook[NumPhoneEntries] -> Config = (struct Configuration *)(Phonebook[NumPhoneEntries] -> Header + 1);

		strcpy(Phonebook[NumPhoneEntries] -> Header -> Name,LocaleString(MSG_TERMPHONE_UNUSED_ENTRY_TXT));

		CopyMem(&Config,Phonebook[NumPhoneEntries] -> Config,sizeof(struct Configuration));

		Phonebook[NumPhoneEntries] -> Count = -1;

		NewList((struct List *)&Phonebook[NumPhoneEntries] -> TimeDateList);

		if(TimeDateNode = CreateTimeDateNode(-1,-1,"",2))
			AddTail((struct List *)&Phonebook[NumPhoneEntries] -> TimeDateList,&TimeDateNode -> VanillaNode);

		NumPhoneEntries++;

		return(TRUE);
	}

	return(FALSE);
}

	/* CreatePhonebook(LONG Size,LONG *AllocSize,BYTE CreateEntries):
	 *
	 *	Create a new phone entry array (so-called phone book).
	 */

struct PhoneEntry **
CreatePhonebook(LONG Size,LONG *AllocSize,BYTE CreateEntries)
{
	struct PhoneEntry **PhoneEntry = NULL;

	if(Size)
	{
			/* Round the number of phone entries to a
			 * multiple of eight.
			 */

		*AllocSize = (Size + 7) & ~7;

			/* Create the list of pointers. */

		if(PhoneEntry = (struct PhoneEntry **)AllocVec(*AllocSize * sizeof(struct PhoneEntry *),MEMF_ANY|MEMF_CLEAR))
		{
				/* And create some entries if necessary. */

			if(CreateEntries)
			{
				LONG i;

				for(i = 0 ; i < Size ; i++)
				{
					if(!(PhoneEntry[i] = (struct PhoneEntry *)AllocVec(sizeof(struct PhoneEntry) + sizeof(struct Configuration) + sizeof(struct PhoneHeader),MEMF_ANY|MEMF_CLEAR)))
					{
						LONG j;

						for(j = 0 ; j < i ; j++)
							FreeVec(PhoneEntry[j]);

						FreeVec(PhoneEntry);

						return(NULL);
					}
					else
					{
						PhoneEntry[i] -> Header = (struct PhoneHeader *)(PhoneEntry[i] + 1);
						PhoneEntry[i] -> Config = (struct Configuration *)(PhoneEntry[i] -> Header + 1);

						NewList((struct List *)&PhoneEntry[i] -> TimeDateList);
					}
				}
			}
		}
	}

	return(PhoneEntry);
}

	/* DeletePhonebook(struct PhoneEntry **PhoneBook,LONG Size,BYTE FreeEntries):
	 *
	 *	Deallocates a given phone book and its entries if necessary.
	 */

VOID
DeletePhonebook(struct PhoneEntry **Phonebook,LONG Size,BYTE FreeEntries)
{
	if(FreeEntries)
	{
		LONG i;

		for(i = 0 ; i < Size ; i++)
		{
			if(Phonebook[i])
			{
				FreeTimeDateList((struct List *)&Phonebook[i] -> TimeDateList);

				FreeVec(Phonebook[i]);
			}
		}
	}

	FreeVec(Phonebook);
}

	/* SavePhonebook(UBYTE *Name):
	 *
	 *	Save the current phone book to a disk file.
	 */

BYTE
SavePhonebook(UBYTE *Name)
{
	struct IFFHandle	*Handle;
	BYTE			 Success = FALSE;

	if(Phonebook && NumPhoneEntries)
	{
		if(Handle = (struct IFFHandle *)AllocIFF())
		{
			if(Handle -> iff_Stream = Open(Name,MODE_NEWFILE))
			{
				InitIFFasDOS(Handle);

				if(!OpenIFF(Handle,IFFF_WRITE))
				{
					if(!PushChunk(Handle,ID_TERM,ID_CAT,IFFSIZE_UNKNOWN))
					{
						if(!PushChunk(Handle,ID_TERM,ID_FORM,IFFSIZE_UNKNOWN))
						{
							if(!PushChunk(Handle,0,ID_VERS,IFFSIZE_UNKNOWN))
							{
								struct TermInfo TermInfo;

								TermInfo . Version	= TermVersion;
								TermInfo . Revision	= TermRevision;

								if(WriteChunkRecords(Handle,&TermInfo,sizeof(struct TermInfo),1) == 1)
								{
									if(!PopChunk(Handle))
									{
										UBYTE *TempBuffer = NULL;

										if(PhonePasswordUsed)
										{
											if(!PushChunk(Handle,0,ID_PSWD,20))
											{
												Success = TRUE;

												if(WriteChunkBytes(Handle,PhonePassword,20) != 20)
													Success = FALSE;

												if(PopChunk(Handle))
													Success = FALSE;

												if(Success)
												{
													if(!(TempBuffer = AllocVec(MAX(sizeof(struct Configuration),sizeof(struct PhoneHeader)),MEMF_ANY)))
														Success = FALSE;
												}
											}
										}
										else
											Success = TRUE;

										if(Success)
										{
											Success = FALSE;

											if(!PushChunk(Handle,0,ID_DIAL,IFFSIZE_UNKNOWN))
											{
												if(WriteChunkBytes(Handle,&NumPhoneEntries,sizeof(LONG)) == sizeof(LONG))
												{
													if(!PopChunk(Handle))
													{
														if(!PopChunk(Handle))
														{
															LONG i;

															Success = TRUE;

															for(i = 0 ; Success && i < NumPhoneEntries ; i++)
															{
																Success = FALSE;

																if(!PushChunk(Handle,ID_TERM,ID_FORM,IFFSIZE_UNKNOWN))
																{
																	if(!PushChunk(Handle,0,ID_PHON,sizeof(struct PhoneHeader)))
																	{
																		if(TempBuffer)
																		{
																			Encrypt((UBYTE *)Phonebook[i] -> Header,sizeof(struct PhoneHeader),TempBuffer,PhonePassword,20,TRUE);

																			if(WriteChunkRecords(Handle,TempBuffer,sizeof(struct PhoneHeader),1) == 1)
																			{
																				if(!PopChunk(Handle))
																				{
																					if(!PushChunk(Handle,0,ID_PREF,sizeof(struct Configuration)))
																					{
																						Encrypt((UBYTE *)Phonebook[i] -> Config,sizeof(struct Configuration),TempBuffer,PhonePassword,20,TRUE);

																						if(WriteChunkRecords(Handle,TempBuffer,sizeof(struct Configuration),1) == 1)
																						{
																							if(!PopChunk(Handle))
																								Success = TRUE;
																						}
																					}
																				}
																			}
																		}
																		else
																		{
																			if(WriteChunkRecords(Handle,Phonebook[i] -> Header,sizeof(struct PhoneHeader),1) == 1)
																			{
																				if(!PopChunk(Handle))
																				{
																					if(!PushChunk(Handle,0,ID_PREF,sizeof(struct Configuration)))
																					{
																						if(WriteChunkRecords(Handle,Phonebook[i] -> Config,sizeof(struct Configuration),1) == 1)
																						{
																							if(!PopChunk(Handle))
																							{
																								struct TimeDateNode *TimeDateNode;

																								Success = TRUE;

																								TimeDateNode = (struct TimeDateNode *)Phonebook[i] -> TimeDateList . mlh_Head;

																								while(TimeDateNode -> VanillaNode . ln_Succ)
																								{
																									if(!PushChunk(Handle,0,ID_DATE,IFFSIZE_UNKNOWN))
																									{
																										if(WriteChunkBytes(Handle,&TimeDateNode -> Header,sizeof(struct TimeDateHeader)) != sizeof(struct TimeDateHeader))
																										{
																											Success = FALSE;

																											break;
																										}
																										else
																										{
																											if(WriteChunkBytes(Handle,TimeDateNode -> Table,TimeDateNode -> Table[0] . Count * sizeof(struct TimeDate)) != TimeDateNode -> Table[0] . Count * sizeof(struct TimeDate))
																											{
																												Success = FALSE;

																												break;
																											}
																										}

																										if(PopChunk(Handle))
																										{
																											Success = FALSE;

																											break;
																										}
								
																										TimeDateNode = (struct TimeDateNode *)TimeDateNode -> VanillaNode . ln_Succ;
																									}
																								}
																							}
																						}
																					}
																				}
																			}
																		}
																	}

																	if(PopChunk(Handle))
																		Success = FALSE;
																}
															}
														}
													}
												}
											}
										}

										if(TempBuffer)
											FreeVec(TempBuffer);
									}
								}
							}
						}

						if(PopChunk(Handle))
							Success = FALSE;
					}

					CloseIFF(Handle);
				}

				Close(Handle -> iff_Stream);
			}

			FreeIFF(Handle);
		}

		if(Success)
			SetProtection(Name,FIBF_EXECUTE);
		else
			DeleteFile(Name);
	}

	return(Success);
}

	/* LoadPhonebook(UBYTE *Name):
	 *
	 *	Restore a phone book from a disk file.
	 */

BYTE
LoadPhonebook(UBYTE *Name)
{
	STATIC ULONG Stops[6 * 2] =
	{
		ID_TERM,ID_VERS,
		ID_TERM,ID_DIAL,
		ID_TERM,ID_PREF,
		ID_TERM,ID_DATE,
		ID_TERM,ID_PHON,
		ID_TERM,ID_PSWD
	};

	struct PhoneEntry	**PrivatePhonebook;
	LONG			 PrivatePhoneSize = 0;
	LONG			 Size = 0,Count = 0,Last = -1;
	struct IFFHandle	*Handle;
	BYTE			 Success = FALSE;
	struct ContextNode	*Chunk;
	BYTE			 LastHadTime	= TRUE,
				 HadPassword	= FALSE;
	struct TimeDateNode	*TimeDateNode;

	if(Handle = AllocIFF())
	{
		if(Handle -> iff_Stream = Open(Name,MODE_OLDFILE))
		{
			InitIFFasDOS(Handle);

			if(!OpenIFF(Handle,IFFF_READ))
			{
				if(!StopChunks(Handle,Stops,6))
				{
					while(!ParseIFF(Handle,IFFPARSE_SCAN))
					{
						Chunk = CurrentChunk(Handle);

						if(Chunk -> cn_ID == ID_VERS)
						{
							struct TermInfo TermInfo;

							if(ReadChunkBytes(Handle,&TermInfo,sizeof(struct TermInfo)) == sizeof(struct TermInfo))
							{
								if((TermInfo . Version > TermVersion) || (TermInfo . Version == TermVersion && TermInfo . Revision > TermRevision) || TermInfo . Version < 1 || (TermInfo . Version == 2 && TermInfo . Revision < 4))
									break;
							}
							else
								break;
						}

						if(Chunk -> cn_ID == ID_PSWD)
						{
							UBYTE DummyBuffer[20];

							HadPassword = TRUE;

							if(ReadChunkBytes(Handle,DummyBuffer,20) == 20)
							{
								if(PhonePasswordUsed)
								{
									if(!memcmp(PhonePassword,DummyBuffer,20))
										continue;
								}

								SharedBuffer[0] = 0;

								if(GetString(FALSE,TRUE,21,LocaleString(MSG_PHONEPANEL_PLEASE_ENTER_PASSWORD_TXT),SharedBuffer))
								{
									UBYTE AnotherBuffer[20];

									Encrypt(SharedBuffer,20,AnotherBuffer,SharedBuffer,strlen(SharedBuffer),TRUE);

									if(!memcmp(DummyBuffer,AnotherBuffer,20))
									{
										memcpy(PhonePassword,DummyBuffer,20);

										PhonePasswordUsed = TRUE;

										continue;
									}
									else
									{
										MyEasyRequest(Window,LocaleString(MSG_TERMPHONE_WRONG_PASSWORD_TXT),LocaleString(MSG_GLOBAL_CONTINUE_TXT),Name);

										break;
									}
								}
								else
									break;
							}
							else
								break;
						}

						if(Chunk -> cn_ID == ID_DIAL)
						{
							if(ReadChunkBytes(Handle,&Size,sizeof(LONG)) == sizeof(LONG))
							{
								if(!(PrivatePhonebook = CreatePhonebook(Size,&PrivatePhoneSize,TRUE)))
									break;
							}
							else
								break;
						}

						if(Chunk -> cn_ID == ID_PHON)
						{
							WORD Size = MIN(sizeof(struct PhoneHeader),Chunk -> cn_Size);

							if(ReadChunkBytes(Handle,PrivatePhonebook[Count] -> Header,Size) != Size)
								break;
						}

						if(Chunk -> cn_ID == ID_PREF)
						{
							if(Last != -1)
							{
								if(!LastHadTime)
								{
									if(TimeDateNode = CreateTimeDateNode(-1,-1,"",2))
										AddTail((struct List *)&PrivatePhonebook[Last] -> TimeDateList,&TimeDateNode -> VanillaNode);
								}
							}

							if(Size && Count < Size)
							{
								WORD LastSize = sizeof(struct Configuration);

								PhonePasswordUsed = HadPassword;

								if(Chunk -> cn_Size < LastSize)
									LastSize = Chunk -> cn_Size;

								SetPrefToDefaults(PrivatePhonebook[Count] -> Config,NULL);

								if(ReadChunkBytes(Handle,PrivatePhonebook[Count] -> Config,LastSize) == LastSize)
								{
									if(PhonePasswordUsed)
										Decrypt((UBYTE *)PrivatePhonebook[Count] -> Config,LastSize,(UBYTE *)PrivatePhonebook[Count] -> Config,PhonePassword,20,TRUE);

									Last = Count;

									PrivatePhonebook[Count] -> Count = -1;

									Count++;

									LastHadTime = FALSE;
								}
								else
								{
									if(Count)
										Size = Count - 1;
									else
										Size = 0;

									break;
								}
							}
						}

						if(Chunk -> cn_ID == ID_DATE)
						{
							if(Last != -1)
							{
								WORD Count = (Chunk -> cn_Size - sizeof(struct TimeDateHeader)) / sizeof(struct TimeDate);

								if(TimeDateNode = CreateTimeDateNode(-1,-1,"",Count))
								{
									if(ReadChunkBytes(Handle,&TimeDateNode -> Header,sizeof(struct TimeDateHeader)) == sizeof(struct TimeDateHeader))
									{
										if(ReadChunkBytes(Handle,TimeDateNode -> Table,sizeof(struct TimeDate) * Count) == sizeof(struct TimeDate) * Count)
										{
											AdaptTimeDateNode(TimeDateNode);

											AddTail((struct List *)&PrivatePhonebook[Last] -> TimeDateList,&TimeDateNode -> VanillaNode);

											LastHadTime = TRUE;
										}
										else
											FreeTimeDateNode(TimeDateNode);
									}
									else
										FreeTimeDateNode(TimeDateNode);
								}
							}
						}
					}

					if(Size)
					{
						if(!LastHadTime && Last != -1)
						{
							if(TimeDateNode = CreateTimeDateNode(-1,-1,"",2))
								AddTail((struct List *)&PrivatePhonebook[Last] -> TimeDateList,&TimeDateNode -> VanillaNode);
						}

						if(Phonebook)
							DeletePhonebook(Phonebook,PhoneSize,TRUE);

						Phonebook = PrivatePhonebook;
						PhoneSize = PrivatePhoneSize;

						NumPhoneEntries = Size;

						Success = TRUE;
					}
					else
					{
						if(PrivatePhoneSize)
						{
							DeletePhonebook(PrivatePhonebook,PrivatePhoneSize,TRUE);

							Success = FALSE;
						}
					}

					FreeDialList();
				}

				CloseIFF(Handle);
			}

			Close(Handle -> iff_Stream);
		}

		FreeIFF(Handle);
	}

	return(Success);
}
