#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>

#include <fcntl.h>
#include <io.h>
#include <conio.h>
#include <ctype.h>

#include "ModeSet.h"


short PushBuffer( LPCTSTR IPAddress, char *Buffer, char *TargetFileName ) 
{
    char    *cbuf;
    int		TargetPathSize = 0;
    int		TargetFileSize = 0;
    
    if( !connectUnit( IPAddress ) )
        return FALSE;

    cbuf = pkt->body.data.data.file.theFile;

    if ( TargetFileName )
	   strcpy( cbuf, TargetFileName );

	TargetPathSize = strlen( TargetFileName ) + 1;
	TargetFileSize = strlen( Buffer );

    if ( Buffer )
       strcpy( (cbuf + TargetPathSize ), Buffer );

    pkt->header.length			    = htonl(TargetFileSize + sizeof (SLPACKET) + TargetPathSize);
    pkt->header.token			    = SLT_DATA;
    pkt->body.data.type		        = SLD_FILE;
    pkt->body.data.data.file.file.length   = htonl(TargetFileSize);
    pkt->body.data.data.file.file.token    = (SLOPPITOKEN) SLF_FILE;

    sendPacket( (char *)pkt, ntohl( pkt->header.length ));

    disconnectUnit( );
    return TRUE;
}


short PushFile( LPCTSTR IPAddress, LPCTSTR File, LPCTSTR TargetFileName ) 
{
    char        *cbuf;
    int		    TargetPathSize = 0;
    FILE        *newcode;
    struct      stat	cstat;
    SLPACKET   *cpkt	= NULL;
    
    if( !connectUnit( IPAddress ) )
        return FALSE;

    if( !TargetFileName )
        return FALSE;

	TargetPathSize = strlen( TargetFileName ) + 1;

    if ( stat( File, &cstat ))
	    return FALSE;

    cpkt = (SLPACKET *)malloc( cstat.st_size + sizeof (SLPACKET) + TargetPathSize );

    if ( !cpkt )
		return FALSE;

    cbuf = cpkt->body.data.data.file.theFile;

    if ( TargetFileName )
	   strcpy( cbuf, TargetFileName );


    newcode = fopen( File, "rb" );
    
    if ( !newcode )
		return FALSE;

    if ( fread( (cbuf + TargetPathSize ), cstat.st_size, 1, newcode )  !=  1 )
      {
	    free( cpkt );
        fclose( newcode );
	    return FALSE;
      }

    fclose( newcode );

    cpkt->header.length			    = htonl(cstat.st_size + sizeof (SLPACKET) + TargetPathSize);
    cpkt->header.token			    = SLT_DATA;
    cpkt->body.data.type		    = SLD_FILE;
    cpkt->body.data.data.file.file.length   = htonl(cstat.st_size);
    cpkt->body.data.data.file.file.token    = (SLOPPITOKEN) SLF_FILE;

    sendPacket( (char *)cpkt, ntohl( cpkt->header.length ));

    free( cpkt );

    disconnectUnit( );
    return TRUE;
}


