/* Copyright (C) 1995, 1996 Zlatko Calusic <maverick@fly.cc.fer.hr>
This file is part of DownLoad, FTP Client

The DownLoad is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation.

The DownLoad is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
more details.

You should have received a copy of the GNU General Public License along with
the DownLoad source; see the file COPYING.  If not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */

#include "dl.h"

/* Global variables */

extern int data, local;

extern int retry, nofatal;

extern char file[], buffer[];

extern fd_set fdset;

extern struct timeval ttimer;

extern struct stat statbuf;

int retrieve_file(void)
{
	int bytes, size, sofar = 0, dot = 0;
	time_t now;

	if (local)
	{
		close(local);
		local = 0;
	}
	if (!get_port())
		return ERROR;
	if (!stat(file, &statbuf))
	{
		sprintf(buffer, "%d", (int) statbuf.st_size);
		nofatal = 1;
		if (ftprequest("REST %s\r\n", buffer))
		{
			if ((local = open(file, O_WRONLY | O_APPEND, 0666)) < 0)
				fperror("Error opening local file");
		}
		nofatal = 0;
	}
	if (!local)
		if ((local = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
			fperror("Error opening local file");
	if (!ftprequest("RETR %s\r\n", file) || !accept_data())
		return ERROR;
	now = time(NULL);
	strcpy(buffer, (char *) ctime(&now));
	buffer[24] = 0;
	fprintf(stderr, "DownLoad (#%d) started at %s.\n", retry, buffer);
	fputs("Dot mark printing on (8192 bytes/dot mark).\n", stderr);
	bytes = 0;
	do
	{
		timer_on(data);
		if (select(255, &fdset, NULL, NULL, &ttimer) <= 0)
		{
			if (dot)
				fputc('\n', stderr);
			fputs("Data connection timed out.\n", stderr);
			fputs(rate(bytes, time(NULL) - now - TMOUT), stderr);
			return ERROR;
		}
		if ((size = read(data, buffer, BUFFER)) < 0)
		{
			if (dot)
				fputc('\n', stderr);
			perror("Error reading data socket");
			fputs(rate(bytes, time(NULL) - now), stderr);
			return ERROR;
		}
		if (write(local, buffer, size) != size)
		{
			if (dot)
				fputc('\n', stderr);
			fputs(rate(bytes, time(NULL) - now), stderr);
			fperror("Error writing local file");
		}
		sofar += size;
		bytes += size;
		if (sofar >= 8192)
		{
			fputc('.', stderr);
			fflush(stderr);
			sofar -= 8192;
			dot++;
			if (dot == 64)
			{
				fputc('\n', stderr);
				fflush(stderr);
				dot = 0;
			}
		}
	} while (size);
	if (dot)
	{
		fputc('\n', stderr);
		fflush(stderr);
	}
	fputs(rate(bytes, time(NULL) - now), stderr);
	return get_response();
}
