/*
 * $Source: /home/nlfm/Working/Zircon/Released/plugins/Dcc/RCS/dccsend.c,v $
 * $Date: 1997/01/09 12:04:57 $
 * $Revision: 1.18.1.7 $
 */
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/time.h>
#include <fcntl.h>

#ifdef _AIX
#include <sys/select.h>
#endif

int main(argc, argv)
int argc;
char *argv[];
{
    int fd, g, port, posn = 0;
    float leng, bps;
    char buffer[4096], host[128];
    int l, tl = 0, i, pid = 1;
    long elt;
    struct timeval timeout;
    fd_set rdset;
    struct stat fs;
    time_t st, td;
    double size;
    FILE *pf;
    extern int errno;

    posn = atoi(argv[2]);    
    if ((g = open(argv[1], O_RDONLY)) < 0)
    {
	printf("%d DCCError Send %s to %s: Cannot read file.\n", pid, 
	        argv[1], argv[3]);
	fflush(stdout);
    }
    else
    {
	fstat(g, &fs);
	leng = (float) (fs.st_size - posn);
        if (posn != 0)
	{
	    if (lseek(g, posn, 0) != posn)
	    {
		printf("%d DCCError Send %s to %s: Seek error.\n", pid, 
	          argv[1], argv[3]);
		fflush(stdout);
		exit(1);
	    }
	}
	
	st = time((time_t *) 0);
	while ((l = read(g, buffer, 2048)) > 0)
	{
	    tl += l;
	    if (write(2, buffer, l) != l) 
	    {
		sprintf(host,
		  "%d DCCError Send %s to %s: Write error.\n", pid, 
		  argv[1], argv[3]);
		l = -1;
		break;
	    }
	    if ((td = time((time_t *) 0) - st) == 0)
	    {
		bps = (float) tl;
	    }
	    else
	    {
		bps = (float) tl / (float) td;
	    }
	    elt = (long) ((leng - (float) tl) / bps);
	    
	    printf("%d DCC Send progress to %s %d %2.1f %f %ld\n", fd, argv[3],
	      tl, ((float) tl / leng) * 100.0, bps , td);
	    fflush(stdout);
	    do
	    {
		FD_ZERO(&rdset);
		FD_SET(0, &rdset);
		timeout.tv_sec = 10;
		timeout.tv_usec = 0;
#ifdef __hpux   
                if (select(fd + 1, (int *)&rdset, NULL, NULL, &timeout) != 1)
#else           
                if (select(fd + 1, &rdset, NULL, NULL, &timeout) != 1)
#endif /* __hpux */
		{
		    l = -1;
		    break;
		}
		else
		{
		    if (read(0, (char *) &i, sizeof(int)) != sizeof(int)) 
		    {
			sprintf(host,
			  "%d DCC Send %s to %s: Read error.\n", pid, 
			  argv[1], argv[3]);
			l = -1;
			break;
		    }
		}
	    }
	    while (ntohl(i) != tl);
	
	}
    }
    (void) close(g);
    (void) shutdown(0, 0);
    (void) close(0);
    (void) shutdown(2, 1);
    (void) close(2);
    if (l >= 0)
    {
	if ((st = time((time_t *) 0) - st) == 0)
	{
	    st = 1;
        }
	sprintf(host, "%d DCC Send %s to %s completed. %f Kbytes/sec", pid, 
		argv[1], argv[3], (((float) tl * 0.001) / (float) st));
    }
    printf("%s", host);
    fclose(stdout);
    exit((l >=0 ) ? 0 : 1);
}
