#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <dos/dostags.h>
#include <stdio.h>
#include <string.h>

#include <proto/exec.h>
#include <proto/dos.h>

#include "/include/server.h"


extern struct List ClientsList;
extern UWORD TotalClients;

#define MAXCLIENTS 100

struct TagItem systags[4] = { SYS_Asynch, TRUE, SYS_Input, NULL, SYS_Output, NULL, TAG_END };


BOOL StartClient( struct ClientNode *node )
{
BPTR lock;
char path[128], *cp;

if ( lock = Lock( node->cn_ClientName, ACCESS_READ ) )
	{
	UnLock( lock );
	strcpy( path, node->cn_ClientName );

	cp = path + strlen( path ) -1;
	while( cp > path && *cp != '/' && *cp != ':' )
		cp--;
	if ( cp > path )
		{
		*cp = 0;
		cp++;
		}
	lock = Lock( path, ACCESS_READ );
	CurrentDir( lock );
	if ( SystemTagList( cp, systags ) != -1 )
		{
		return TRUE;
		}
	}
return FALSE;
}


void AddClient( char *newname )
{
struct ClientNode *node;

if ( node = AllocVec( sizeof(struct ClientNode), MEMF_ANY | MEMF_CLEAR ) )
	{
	strcpy( node->cn_ClientName, newname );
	node->cn_Node.ln_Name = FilePart( node->cn_ClientName );
	AddTail( &ClientsList, (struct Node *)node );
	TotalClients++;
	}
}


void GetClientNames( char *listname )
{
BPTR handle;
struct FileInfoBlock fib;
register ULONG size;
register char *ptr, *current;
register char newclient[CLIENTNAME_MAXLENGTH];
register UBYTE n;

if ( handle = Open( listname, MODE_OLDFILE ) )
	{
	if ( ExamineFH( handle, &fib ) )
		{
		size = fib.fib_Size;
		if ( ptr = AllocVec( size, MEMF_ANY ) )
			{
			Read( handle, ptr, size );

			current = ptr;
			while( current < ( ptr + size ) )
				{
				n = 0;
				while( *current != '\n' && current < ( ptr + size ) )
					newclient[n++] = *current++;
				newclient[n] = 0;
				current++;
				if ( newclient[0] )
					AddClient( newclient );
				}
			FreeVec( ptr );
			}
		}
	Close( handle );
	}
}


void DropClientNames( void )
{
struct ClientNode *node;

while ( node = (struct ClientNode *)RemHead( &ClientsList ) )
	FreeVec( node );
}
