#include <stdio.h>
#include "global.h"
#include "mbuf.h"
#include "socket.h"
#include "proc.h"
#include "ftp.h"

/* Send a file (opened by caller) on a network socket */
long
sendfile(fp,s,mode)
FILE *fp;	/* File to be sent */
int s;		/* Socket to be sent on */
int mode;	/* Transfer mode */
{
	register struct mbuf *bp;
	int c,oldf;
	long total = 0;

	switch(mode){
	default:
	case LOGICAL_TYPE:
	case IMAGE_TYPE:
		for(;;){
			if((bp = alloc_mbuf(BLKSIZE)) == NULLBUF)
				return -1;

			if((bp->cnt = fread(bp->data,1,BLKSIZE,fp)) == 0){
				free_p(bp);
				break;
			}
			total += bp->cnt;
			if(send_mbuf(s,bp,0,NULLCHAR,0) == -1){
				return -1;
			}
		}
		break;
	case ASCII_TYPE:
		oldf = setflush(s,-1);
		/* Let the newline mapping code in usputc() do the work */
		while((c = fgetc(fp)) != EOF){
#if !defined(UNIX) && !defined(__TURBOC__) && !defined(__TURBOC__)
			if(c == '\r'){
				/* Needed only if the OS uses a CR/LF
				 * convention and fgetc doesn't do
				 * an automatic translation
				 */
				continue;
			}
#endif
			usputc(s,(char)c);
			total++;
		}
		usflush(s);
		setflush(s,oldf);		
		break;
	}
	return total;
}
long
recvfile(fp,s,mode)
FILE *fp;
int s;
int mode;
{
	int cnt,c;
	struct mbuf *bp;
	long total = 0;

	switch(mode){
	default:
	case LOGICAL_TYPE:
	case IMAGE_TYPE:
		while((cnt = recv_mbuf(s,&bp,0,NULLCHAR,0)) != 0){
			if(cnt == -1)
				return -1;

			total += cnt;
			if(fp != NULLFILE){
				if(write_p(fp,bp) == -1){
					free_p(bp);
					return -1;
				}
				free_p(bp);
			} else {
				send_mbuf(Curproc->output, bp, 0, NULLCHAR, 0);
			}
		}
		break;
	case ASCII_TYPE:
		while((c = recvchar(s)) != EOF){
			if(fp != NULLFILE){
#if !defined(UNIX) && !defined(__TURBOC__) && !defined(AMIGA)
				if(c == '\n'){
					/* Needed only if the OS uses a CR/LF
					 * convention and fputc doesn't do
					 * an automatic translation
					 */
					fputc('\r',fp);
				}
#endif
				if(fputc(c,fp) == EOF){
					total = -1;
					break;
				}
			} else {
				tputc((char)c);
			}
			total++;
		}
		break;
	}
	return total;
}
