#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "lib.h"
#include "tcplib.h"
#include "lib.h"
#include "debug.h"
#include "lprintf.h"
#include "xfilelib.h"


int xfile_get(Chan *c, char *fname, char *dest, char *result)
{
	int sz,rest;
	char *s;
	char bf[BFSZ];
	FILE *f = NULL;
	int chunk,len;
	int failed=FALSE;
	tcp_printf(c,"xfile_get %s\r\n",fname);
	if (!tcp_pop_response(c,"xfile_get",bf)) goto failed;
	// 	pcmd_write(l,"+OK size=%d time=%d file follows\r\n",size,mtime);
	s = strstr(bf,"size="); if (s==NULL) goto failed;
	sz = atoi(s+5);

	f = fopen(dest,"wb");
	if (f==NULL) goto failed;
	rest = sz;
	for (;rest>0;) {
		chunk = rest;
		if (chunk>(BFSZ-1)) chunk = BFSZ-1;
		len = tcp_read_timed(c,bf,chunk,1000*60);
		if (len<=0) {
			lprintf(result,BFSZ-1,"Read %d error or timeout %s",len,tcp_error(c,bf));
			failed = TRUE;
			break;
		}
		rest -= len;
		if ((f!=NULL) && (int) fwrite(bf,1,len,f)!=len) {
			lprintf(result,BFSZ-1,"write (%s) failed %s",dest,strerror(errno));
			failed = TRUE;	break;
		}
	}
	if (fclose(f)!=0) failed = TRUE;
failed:
	if (failed) return FALSE;
	return TRUE;
}

