#include <stdio.h>
#include <exec/types.h>

#include "ftp.h"

#include <proto/socket.h>

extern LONG server_socket;

static char buf[BLKSIZE];

/* Send a file (opened by caller) on a network socket */
long sendfile(FILE *fp,LONG s,int mode,int hash)
{
	int c;
	long total = 0;
	long cnt;

	switch(mode) {
		default:
		case LOGICAL_TYPE:
		case IMAGE_TYPE:
			for(;;)
			{
				if((cnt = fread(buf,1,BLKSIZE,fp)) == 0) break;
				total += cnt;
				if(send(s,buf,cnt,0) == -1) return -1;
			}
			break;
		case ASCII_TYPE:
			/* Let the newline mapping code in usputc() do the work */
			while((c = fgetc(fp)) != EOF)
			{
				usputc(s,(char)c);
				total++;
			}
			break;
	}
	return total;
}

long recvfile(FILE *fp,LONG s,int mode,int hash)
{
	int c;
	long total = 0;
	long cnt;

	switch(mode) {
		default:
		case LOGICAL_TYPE:
		case IMAGE_TYPE:
			while((cnt=recv(s,buf,sizeof(buf),0))!=0)
			{
				if(cnt == -1) return -1;
				total += cnt;
				if(fp != NULL)
				{
					if(fwrite(buf,cnt,1,fp)!=1) return -1;
				} 
				else send(server_socket,buf,cnt,0);
			}
			break;
		case ASCII_TYPE:
			while((c = recvchar(s)) != EOF)
			{
				if(fp != NULL)
				{
					if(fputc(c,fp) == EOF)
					{
						total = -1;
						break;
					}
				}
				else tputc((char)c);
				total++;
			}
			break;
	}
	return total;
}

/* Determine if a file appears to be binary (i.e., non-text).
 * Return 1 if binary, 0 if ascii text after rewinding the file pointer.
 *
 * Used by FTP to warn users when transferring a binary file in text mode.
 */
int isbinary(FILE *fp)
{
	int c,i;
	int rval;

	rval = 0;
	for(i=0;i<512;i++)
	{
		if((c = getc(fp)) == EOF) break;
		if(c & 0x80)
		{
			/* High bit is set, probably not text */
			rval = 1;
			break;
		}
	}
	/* Assume it was at beginning */
	rewind(fp);
	
	return rval;
}
