#include "bbs.h"


long fsize,tfsize,dtfsize;
int NumFiles;
extern BOOL GET_BIT(int bitnum);
/* local globals */
int LineCount;
int DirScan,StartDir;
extern char prototitle[];
extern struct ZModem ZModemInfo;
extern BOOL LocalUpload;
extern int XIMPort;
static void ListProtocols(void)
{
 AEPutStr("\r\n                              [Z] AMI-Zmodem Batch");
//AEPutStr("\r\n                              [X] XPR-Zmodem Batch\r\n");
}

static void RecvExternal(char *fn,char *bf)
{
}

static void ExceedRatio(void)
{
 AEPutStr("You have exceeded your ratio, you must upload first.\r\n\r\n");
}

static void DownloadPrompt(USHORT RatioType, long mins, long bytes, int filespec, int files, char *str)
{
 if(RatioType==0)
	    sprintf(str,"\r\n%ld mins, %ld bytes, Filespec(%d): ",mins,bytes,filespec);
 if(RatioType==2)
	    sprintf(str,"\r\n%ld mins, %d files, Filespec(%d): ",mins,files,filespec);
 if(RatioType==1)
	    sprintf(str,"\r\n%ld mins, %ld bytes, %d files, Filespec(%d): ",mins,bytes,files,filespec);
}

static int DownloadFile(char *rfinal)
{
 int status;

 switch(User.Protocol) {
	    case 'Z':
              //if(LocalUpload) { BatchASLSend(rfinal); LocalUpload=0; }
		    status=Zmodem_Send(rfinal);     break;
	    case 'C':
		    RecvExternal("ram:testfile","NOTHING");    break;
	}
 return(status);
}



int PGoodbye(void);
extern long Time_limit;

int Download_A_File(char *str)
{
 extern BYTE FreeDownloads,CNOZOOM,BeenUDd;
 extern long SessionDnBytes;   /* used for max downloaded bytes per session */
 extern struct myst my_struct;
 int tsec,min,secs,x,status,mystat, nad,PROTO;
 long peff,pcps,bad,Tbad;
 char string[100];
// char colorbuff[6]={0x1B, 0x5B, 0x33, 0x31, 0x6D, 0x00};

 PROTO=0;
 nad=0;
 NumFiles=0;
 FreeDFlag=0;
 rfinal[0]='\0';
 str[0]='\0';
 AEPutStr("\r\n");
 if(MaxDirs==0) {
 	MyError(5); //Sorry();
	    return(FAILURE);
	}

 sprintf(GSTR1,"%sDownloadMsg",Screen_Location);
 if(mystat=ChecktoDisplay(GSTR1,GSTR2,0,1)) {
 	DoPause();
	    AEPutStr("\r\n");
	}

 tfsize=0;
 dtfsize=0;

 DisplayULStats(&User);              /* Show User stats.. Num Dnloads, uploads */

 Tbad=BytesADL;    /* User Daily Limit of bytes to dnload */
 if(User.Sec_Library!=0)	{   /* Dont have a zero ratio */
 	if(User.Sec_Board>0) {
 		nad=(User.Sec_Library*(User.Uploads+1))-User.Downloads;
	    	sprintf(string,"Files Avail before UL : %d\r\n",nad);
		    AEPutStr(string);
 		if(nad<1) {
 			(void)ExceedRatio();
	    		return(SUCCESS);
			}
		}
 	if(User.Sec_Board<2) {
 		bad=(User.Sec_Library*User.Bytes_Upload)-User.Bytes_Download;
	    	sprintf(string,"Bytes Avail before UL : %ld\r\n",bad);
		    AEPutStr(string);
 		if(bad<1) {
 			(void)ExceedRatio();
	    		return(SUCCESS);
			}
		    if(bad<BytesADL)			Tbad=bad;
		}
	} else  	AEPutStr("Download to Upload Ratio Disabled.\r\n");

// We can replace this with User.Protocol = 'Z';

 mystat=CommandSplit();

 if(mystat>1&&(strlen(Command[1])==1)) {
 	PROTO=2;
	    strcpy(str,Command[1]);
 	SetProtocol(str);
	} else	{
 	str[0]='\0';
	    SetProtocol(str);
	}

 AEPutStr("Space between filenames.  Wildcards permitted.\r\n");
 //AEPutStr("      Zmodem Uploading & Downloading only\r\n");
 str[0]='\0';
 Sysopdl=0;




 if((Command[0][1]=='S'||Command[0][1]=='s')&&GET_BIT(ACS_SYSOP_DOWNLOAD)) {
 	Sysopdl=1;
	    sprintf(string,"\tSYSOP DOWNLOAD: %s\n",MAINMENU_Li);
 	(void)CallersLog(string);
	    (void)UDLog(string);
 	if(strlen(MAINMENU_Li)>4)
 		strcpy(str,(char *)&MAINMENU_Li[3+PROTO]);
	} else	{
 	str[0]='\0';
	    if(mystat>1) {
 		strcpy(str,(char *)&MAINMENU_Li[1+PROTO]);
	    	strcat(str," ");
		}
 	if(strlen(flaglist)!=0)
 		strcat(str,flaglist);
	}

 if(strlen(str)!=0) 	goto Skip1;
Arestart:
 do {
 	tsec=dtfsize/(Online_Baud/10L);
	    min=tsec/60L;
 	if(((Time_limit/60L)-min)<0) {
 		AEPutStr("Not enough time for requested downloads.\r\n\r\n");
	    	return(SUCCESS);
		}
 	if((Tbad-tfsize)<0&&(User.Sec_Board<2)&&(User.Sec_Library!=0)) {
	    	AEPutStr("Not enough free bytes for requested downloads.\r\n\r\n");
		    return(SUCCESS);
 	}
	    if((nad<FreeDFlag&&User.Sec_Board>0)&&User.Sec_Library!=0) {
		    AEPutStr("Not enough free files for requested number of downloads.\r\n\r\n");
 		return(SUCCESS);
	    }
 	if(nad==FreeDFlag&&User.Sec_Library!=0&&User.Sec_Board>0)  goto Astart;

	    if(User.Sec_Library==0)
		    sprintf(str,"\r\n%ld mins, (Ratio Disabled), Filespec(%d): ",(Time_limit/60L)-min,(NumFiles+1));
 	else
	    	DownloadPrompt(User.Sec_Board,(Time_limit/60L)-min,Tbad-tfsize,(NumFiles+1),nad-FreeDFlag,str);

 	AEPutStr(str);

	    status=LineInput("",str,200,KEYBOARD_TIMEOUT);
 	if(status<0)  return(NO_CARRIER);
	    if((strlen(str)==0)&&(NumFiles==0)) {
 		AEPutStr("\r\n");
	    	return(SUCCESS);
 	}
	    if(strlen(str)==0)  goto Astart;
 	if(((str[0]=='q'||str[0]=='Q')||(str[0]=='a'||str[0]=='A'))&&strlen(str)==1) {
	    	AEPutStr("Aborting...\r\n\r\n");
		    return(SUCCESS);
 	}
Skip1:
 	AEPutStr("\r\nChecking...\r\n");
	    if(!Sysopdl) {
		    for(x=0;x<strlen(str);++x)	{
			    if(str[x]==':' || str[x]=='/') {
				    AEPutStr("\r\nYou may not include any special symbols\r\n");
       			goto Arestart;
		    	}
 		}
	    	if(str[0]=='?'||str[0]=='*') {
		    	AEPutStr("\r\nToo ambigious, start with at least one character.\r\n");
			    goto Arestart;
 		}
	    } else {
 		for(x=0;x<strlen(str);++x) {
	    		if(str[x]=='?' || str[x]=='*' || str[x]=='#') {
		    		AEPutStr("\r\nSysop download doesn't support wildcards\r\n");
 		    	goto Arestart;
 			}
	    	}
 	}
	    strcat(str," ");
 	status=Check_list(str,rfinal);
	    if(status==FAILURE)  return(SUCCESS);
 } while(NULL==0L);

Astart:
 if(NumFiles==0)  return(SUCCESS);
 switch(User.Protocol) {
 	case 'Z':
	    	AEPutStr("\r\nZmodem ");    break;
 	case 'C':
		AEPutStr("\r\nXmodem/CRC ");	break;
	}

 AEPutStr(" Batch Download Estimate:\r\n");

Astart2:
  tsec=dtfsize/(Online_Baud/10L);
  min=tsec/60L;
  secs=tsec-(min*60L);
  sprintf(str,"   %d files, %ldk bytes, %d mins %d secs\r\n",NumFiles,(dtfsize/1024),min,secs);
  AEPutStr(str);

 if(Tbad<tfsize) {
	    AEPutStr("Exceeded bytes limit.\r\n\r\n");
	    return(SUCCESS);
	}


 if( (my_struct.maxdbytes < tfsize) || ((my_struct.sessiondbytes+dtfsize) > my_struct.maxdbytes)) {

	    AEPutStr("Exceeded BBS Max Download Limit!!\r\n\r\n");
	    return(SUCCESS);
	}

 if(min>(Time_limit/60L)) {
	    AEPutStr("  Insufficent time for transfer.\r\n\r\n");
	    return(SUCCESS);
	}
 AEPutStr("\r\nLAST CHANCE!   (Enter) to Start, (G)oodbye after transfer, (A)bort? ");
 do {
	    mystat=Check_Online_Status();
	    if(mystat<0)  return(mystat);
	    mystat=ReadChar(KEYBOARD_TIMEOUT);

	    if(mystat<(-1))         return(NO_CARRIER);

	     if((mystat==65) || (mystat==97)) {
		    AEPutStr("Abort!\r\n\r\n");
		    return(SUCCESS);
	    }
         if((status=='l' || status=='L') && XIMPort==CONSOLE_PORT) {
            LocalUpload=1; status=13; break;
         }
	} while(((mystat!=13L)&&(mystat!=71L)&&(mystat!=103L)));

 if(mystat!=13)	AEPutStr("Goodbye!\r\n\r\n");
 else 	AEPutStr("\r\n\r\n");

SysopDL:

 DTBT=0;
 TBT=0;
 TTTM=NULL;
 TTEFF=NULL;
 TTCPS=NULL;

 if(!BeenUDd) {
	    DisplayUserToCallersLog(1);
	    BeenUDd=1;
	}

 status=DownloadFile(rfinal);


 if(status!=0)
	    flaglist[0]='\0';

 AEPutStr("\r\n\r\nFile transfer Completed.\r\n");
 peff=NULL;
 pcps=NULL;
 if(Online_NFiles!=NULL)	{
	    peff=(TTEFF/Online_NFiles);
	    pcps=(TTCPS/Online_NFiles);
	}
// (RTS) added dnload cps rate Fri Mar 27 13:13:29 1992
 if( (pcps > (long) User_keys.DNcps) || (User_keys.DNcps > 5000)) {
        User_keys.DNcps = (UWORD) pcps;

        /* is this baud higher then max cps up ? */
 }
 if(status==0 && !User.XferProtocol)
 {
    if(ZModemInfo.Filesize==ZModemInfo.RecPos)
    {
      TBT += ZModemInfo.Filesize;
      DTBT +=ZModemInfo.Filesize;
      DONF +=1;
    CallersLog("\tIncomplete 100% Transfer, accumilating Maximum Bytes Downloaded\n");
    UDLog("\tIncomplete 100% Transfer, accumilating Maximum Bytes Downloaded\n");
 
    }
      
 }
 sprintf(string," %d files, %ldk bytes, %ld minutes %ld seconds %ld cps, %ld %% efficiency at %ld"
	    ,Online_NFiles,(TBT/1024L),(TTTM/60L),(TTTM%60L),pcps,peff,Online_Baud);

     if(FreeDownloads)
     {
         my_struct.sessiondbytes += DTBT;   /* add dnloaded bytes to totalsession bytes */
	    User.Bytes_Download+=DTBT;
	    User.Downloads=User.Downloads+DONF;
	}    User.Daily_Bytes_Dld+=DTBT;
	    BytesADL-=DTBT;

 AEPutStr(string);
 AEPutStr("\r\n\r\n");

 strcpy(str,"\t");
 strcat(str,string);
 strcat(str,"\n");
 if(Online_NFiles>0)	{
	    (void)CallersLog(str);
	    (void)UDLog(str);
	} else {
 	(void)CallersLog("\tDownload Failed..\n");
	    (void)UDLog("\tDownload Failed..\n");
	}

 DisplayULStats(&User);          /* Show User stats.. Num Dnloads, uploads */
 AEPutStr("\r\n");

 StatPrintUser(&User);
 if((mystat==71L)||(mystat==103L))  return(PGoodbye());
 return(SUCCESS);
}
