/* -TAG:LICENSE-
   
   This file is under the DigitalSpark Freeware Class License, see the
   file LICENSE for complete licensing information.
                                                         
                                                         -TAG:LICENSE- */
#include <Threading.h>
#include "tricky.h"

/* This wraps the write() function, and provides locking */

size_t Write( int slot, void *data, size_t size )
{
size_t	ret;
int	i=0;
size_t	tsize =0;

while ( i <= MAX_CLIENTS )
   {
   if ( Client[i].State != CS_FREE )
      {
      if ( Client[i].Sock == slot )
         {
         pthread_mutex_lock(&Client[i].Mutex);
         break;
         }
      }
   i++;
   }

if ( i > MAX_CLIENTS )
   i=-1;

if ( slot == ServerSock )
   pthread_mutex_lock(&serversock_mutex);

//if ( slot != ServerSock )
//   Error(9,data);

if ( size == 0 )
   {
   ret = write(slot,data,strlen(data));
   tsize = strlen(data);
   if ( ret < strlen(data) )
      ret = -1;
   }
else
   {
   ret = write(slot,data,size);
   tsize = size;
   if ( ret < size )
      ret = -1;
   }

if ( slot == ServerSock )
   pthread_mutex_unlock(&serversock_mutex);

if ( i != -1 )
   pthread_mutex_unlock(&Client[i].Mutex);

if ( tsize != ret )
   return -1;

return 0;
}
