#include "sysincludes.h"
#include "msdos.h"
#include "mtools.h"
#include "file.h"
#include "llong.h"

/*
 * Copy the data from source to target
 */

int copyfile(Stream_t *Source, Stream_t *Target)
{
	char buffer[8*16384];
	mt_off_t pos;
	int ret, retw;
/*	size_t len;*/
	mt_size_t mt_len;

	netmessageC("cf01") ;
	if (!Source){
		fprintf(stderr,"Couldn't open source file\n");
		return -1;
	}

	netmessageC("cf02") ;
	if (!Target){
		fprintf(stderr,"Couldn't open target file\n");
		return -1;
	}

	netmessageC("cf03") ;
	pos = 0;
	netmessageC("cf04") ;
	GET_DATA(Source, 0, &mt_len, 0, 0);
	netmessageC("cf05") ;
	while(1){
	netmessageC("cf06") ;
		ret = READS(Source, buffer, (mt_off_t) pos, 8*16384);
	netmessageC("cf07") ;
		if (ret < 0 ){
			perror("file read");
			return -1;
		}
	netmessageC("cf08") ;
		if(!ret)
			break;
		if(got_signal)
			return -1;
		if (ret == 0)
			break;
	netmessageC("cf09") ;
		if ((retw = force_write(Target, buffer, (mt_off_t) pos, ret)) != ret){
			if(retw < 0 )
			{
	netmessageC("cf10") ;
				perror("write in copy");
	netmessageC("cf11") ;
			}
			else
			{
	netmessageC("cf11b") ;
				fprintf(stderr,
					"Short write %d instead of %d\n", retw,
					ret);
	netmessageC("cf11c") ;
			}
			if(errno == ENOSPC)
				got_signal = 1;
	netmessageC("cf11d") ;
			return ret;
		}
	netmessageC("cf12") ;
		pos += ret;
	}
	return pos;
}
