/* $Revision Header * Header built automatically - do not edit! *************
 *
 *	(C) Copyright 1990 by Olaf 'Olsen' Barthel & MXM
 *
 *	Name .....: termTransfer.c
 *	Created ..: Friday 03-May-91 19:49
 *	Revision .: 0
 *
 *	Date            Author          Comment
 *	=========       ========        ====================
 *	03-May-91       Olsen           Created this file!
 *
 * $Revision Header ********************************************************/

#include "TermGlobal.h"

	/* The action strings to display. */

STATIC UBYTE *SendQuery[3] =
{
	"Upload File(s)",
	"Upload Text",
	"Upload ASCII"
};

STATIC UBYTE *ReceiveQuery[3] =
{
	"Download File(s)",
	"Download Text",
	"Download ASCII"
};

	/* The transfer types to display. */

STATIC UBYTE *TransferTypes[3] =
{
	"binary",
	"text",
	"ASCII"
};

	/* StartXprReceive():
	 *
	 *	Receive files via xpr.
	 */

VOID
StartXprReceive(BYTE Type)
{
	struct FileRequester	*FileRequest;
	UBYTE			 DummyBuffer[256];
	BYTE			 OldStatus = Status;
	UBYTE			*DownloadPath;

		/* Select the download path. */

	switch(Type)
	{
		case TRANSFER_BINARY:	DownloadPath = &Config . BinaryDownloadPath[0];
					break;

		case TRANSFER_TEXT:	DownloadPath = &Config . TextDownloadPath[0];
					break;

		case TRANSFER_ASCII:	DownloadPath = &Config . ASCIIDownloadPath[0];
					break;
	}

	BlockWindows();

		/* Set up the library if necessary. */

	if(!XProtocolBase)
	{
		NewLibrary = FALSE;

		xpr_options(0,NULL);

		if(NewLibrary)
		{
			if(ProtocolSetup())
			{
				SaveProtocolOpts();

				strcpy(Config . Protocol,LastXprLibrary);
			}
		}
	}

	if(XProtocolBase)
	{
			/* Do we need to ask the user for
			 * the destination file name?
			 */

		if(TransferBits & XPRS_NORECREQ)
		{
				/* Obviously not, let's open
				 * the transfer info window as
				 * usual and download the file(s).
				 */

			if(TransferPanel(ReceiveQuery[Type]))
			{
				Status = STATUS_DOWNLOAD;

				FlushSerial();

				LogAction("Initiate %s download.",TransferTypes[Type]);

					/* Receive the data. */

				XProtocolReceive(XprIO);

					/* Wake the user up. */

				if(TransferWindow)
					WakeUp(TransferWindow);

				Say("Transfer completed.");

				Status = OldStatus;

					/* Queue another read request. */

				if(ReadRequest)
				{
					ReadRequest -> IOSer . io_Command	= CMD_READ;
					ReadRequest -> IOSer . io_Data		= ReadBuffer;
					ReadRequest -> IOSer . io_Length	= 1;

					SendIO(ReadRequest);
				}

				DeleteTransferPanel();
			}
		}
		else
		{
				/* Download the file(s). */

			if(FileRequest = GetFile(ReceiveQuery[Type],DownloadPath,"",DummyBuffer,NULL,TRUE,FALSE))
			{
					/* Save the download path. */

				strcpy(DownloadPath,FileRequest -> rf_Dir);

					/* Install the name of the file to receive. */

				XprIO -> xpr_filename = DummyBuffer;

					/* Open the transfer panel. */

				if(TransferPanel(ReceiveQuery[Type]))
				{
					Status = STATUS_DOWNLOAD;

					FlushSerial();

					LogAction("Initiate %s download.",TransferTypes[Type]);

						/* Receive the file. */

					XProtocolReceive(XprIO);

						/* Wake the user up. */

					if(TransferWindow)
						WakeUp(TransferWindow);

					Say("Transfer completed.");

					Status = OldStatus;

						/* Close the transfer panel. */

					DeleteTransferPanel();

						/* Queue another read
						 * request.
						 */

					if(ReadRequest)
					{
						ReadRequest -> IOSer . io_Command	= CMD_READ;
						ReadRequest -> IOSer . io_Data		= ReadBuffer;
						ReadRequest -> IOSer . io_Length	= 1;

						SendIO(ReadRequest);
					}
				}

				FreeAslRequest(FileRequest);
			}
		}
	}

	ReleaseWindows();
}

	/* StartXprSend():
	 *
	 *	Send files via xpr.
	 */

VOID
StartXprSend(BYTE Type)
{
	struct FileRequester	*FileRequest;
	UBYTE			 DummyBuffer[256];
	BYTE			 OldStatus = Status;
	UBYTE			*UploadPath;

		/* Select the upload path. */

	switch(Type)
	{
		case TRANSFER_BINARY:	UploadPath = &Config . BinaryUploadPath[0];
					break;

		case TRANSFER_TEXT:	UploadPath = &Config . TextUploadPath[0];
					break;

		case TRANSFER_ASCII:	UploadPath = &Config . ASCIIUploadPath[0];
					break;
	}

	BlockWindows();

		/* If not initialized, try to set up a new
		 * external transfer protocol.
		 */

	if(!XProtocolBase)
	{
		NewLibrary = FALSE;

		xpr_options(0,NULL);

		if(NewLibrary)
		{
			if(ProtocolSetup())
			{
				SaveProtocolOpts();

				strcpy(Config . Protocol,LastXprLibrary);
			}
		}
	}

	if(XProtocolBase)
	{
			/* Do we need to use our own file requester or
			 * will xpr handle this job for us?
			 */

		if(TransferBits & XPRS_NOSNDREQ)
		{
				/* Open the transfer info window. */

			if(TransferPanel(SendQuery[Type]))
			{
				Status = STATUS_UPLOAD;

					/* Shut up the serial line. */

				FlushSerial();

				LogAction("Initiate %s upload.",TransferTypes[Type]);

					/* Perform upload. */

				XProtocolSend(XprIO);

				if(TransferWindow)
					WakeUp(TransferWindow);

				Say("Transfer completed.");

				Status = OldStatus;

					/* Close the info window. */

				DeleteTransferPanel();

					/* And request another character. */

				if(ReadRequest)
				{
					ReadRequest -> IOSer . io_Command	= CMD_READ;
					ReadRequest -> IOSer . io_Data		= ReadBuffer;
					ReadRequest -> IOSer . io_Length	= 1;

					SendIO(ReadRequest);
				}
			}
		}
		else
		{
				/* We will need the file requester to find
				 * out which file(s) are to be transferred.
				 * Multiple files and wildcards are
				 * supported as well as plain file names.
				 */

			if(FileRequest = GetFile(SendQuery[Type],UploadPath,"",DummyBuffer,"",FALSE,TRUE))
			{
				strcpy(UploadPath,FileRequest -> rf_Dir);

				if(FileRequest -> rf_NumArgs <= 1)
				{
					BPTR OldLock,NewLock;

					MultipleFiles = FileMatch = FALSE;

						/* Clear the pattern match anchor structure. */

					memset(FileAnchor,0,sizeof(struct AnchorPath));

						/* Put the name of the first selected
						 * file into the buffer.
						 */

					if(FileRequest -> rf_NumArgs == 1)
						strcpy(DummyBuffer,FileRequest -> rf_ArgList[0] . wa_Name);

					XprIO -> xpr_filename = DummyBuffer;

						/* To have a valid directory to
						 * read the files from we'll jump
						 * to the directory given in the file
						 * requester. This is due to the fact
						 * that all xpr protocols have referenced
						 * files by their file names (sans path)
						 * yet.
						 */

					if(NewLock = Lock(FileRequest -> rf_Dir,ACCESS_READ))
					{
						if(TransferPanel(SendQuery[Type]))
						{
							OldLock = CurrentDir(NewLock);

							Status = STATUS_UPLOAD;

							FlushSerial();

							LogAction("Initiate %s upload.",TransferTypes[Type]);

							XProtocolSend(XprIO);

							if(TransferWindow)
								WakeUp(TransferWindow);

							Say("Transfer completed.");

							Status = OldStatus;

							DeleteTransferPanel();

							if(ReadRequest)
							{
								ReadRequest -> IOSer . io_Command	= CMD_READ;
								ReadRequest -> IOSer . io_Data		= ReadBuffer;
								ReadRequest -> IOSer . io_Length	= 1;

								SendIO(ReadRequest);
							}

							CurrentDir(OldLock);

							UnLock(NewLock);
						}
						else
							MyEasyRequest(Window,"Failed to locate\ndirectory \"%s\"!","Continue",FileRequest -> rf_Dir);
					}
				}
				else
				{
						/* This looks like a batch file request. */

					if(FileRequest -> rf_NumArgs > 1)
					{
						BPTR OldLock,NewLock;

							/* Set up the array of file names. */

						FileCountMax	= FileRequest -> rf_NumArgs;
						FileArg		= FileRequest -> rf_ArgList;

						MultipleFiles	= TRUE;

							/* If this protocol doesn't support
							 * batch file upload, make sure that
							 * at least the first selected file
							 * is transferred.
							 */

						XprIO -> xpr_filename = FileRequest -> rf_ArgList[0] . wa_Name;

						if(NewLock = Lock(FileRequest -> rf_Dir,ACCESS_READ))
						{
							OldLock = CurrentDir(NewLock);

							if(TransferPanel(SendQuery[Type]))
							{
								Status = STATUS_UPLOAD;

								FlushSerial();

								LogAction("Initiate %s upload.",TransferTypes[Type]);

								XProtocolSend(XprIO);

								if(TransferWindow)
									WakeUp(TransferWindow);

								Say("Transfer completed.");

								Status = OldStatus;

								DeleteTransferPanel();

								if(ReadRequest)
								{
									ReadRequest -> IOSer . io_Command	= CMD_READ;
									ReadRequest -> IOSer . io_Data		= ReadBuffer;
									ReadRequest -> IOSer . io_Length	= 1;

									SendIO(ReadRequest);
								}
							}
							else
								MyEasyRequest(Window,"Failed to locate\ndirectory \"%s\"!","Continue",FileRequest -> rf_Dir);

							CurrentDir(OldLock);

							UnLock(NewLock);
						}
					}
				}

				FreeAslRequest(FileRequest);
			}
		}
	}

	ReleaseWindows();
}

	/* ASCIISetup():
	 *
	 *	Set up xprascii.library for plain ASCII file
	 *	transfer. This routine temporarily selects a
	 *	different protocol than currently set.
	 */

BYTE
ASCIISetup()
{
	UBYTE Options[256];

		/* Close the currently opened xpr.library. */

	if(XProtocolBase)
	{
		XProtocolCleanup(XprIO);

		CloseLibrary(XProtocolBase);
	}

		/* Clear the interface buffer. */

	memset(XprIO,0,sizeof(struct XPR_IO));

		/* Try to obtain the ASCII settings. */

	if(!GetEnvDOS("xprascii",Options))
		Options[0] = 0;

		/* Initialize the interface buffer. */

	XprIO -> xpr_filename	= Options;
	XprIO -> xpr_fopen	= (APTR)xpr_fopen;
	XprIO -> xpr_fclose	= (APTR)xpr_fclose;
	XprIO -> xpr_fread	= (APTR)xpr_fread;
	XprIO -> xpr_fwrite	= (APTR)xpr_fwrite;
	XprIO -> xpr_sread	= (APTR)xpr_sread;
	XprIO -> xpr_swrite	= (APTR)xpr_swrite;
	XprIO -> xpr_sflush	= (APTR)xpr_sflush;
	XprIO -> xpr_update	= (APTR)xpr_update;
	XprIO -> xpr_chkabort	= (APTR)xpr_chkabort;
	XprIO -> xpr_gets	= (APTR)xpr_gets;
	XprIO -> xpr_setserial	= (APTR)xpr_setserial;
	XprIO -> xpr_ffirst	= (APTR)xpr_ffirst;
	XprIO -> xpr_fnext	= (APTR)xpr_fnext;
	XprIO -> xpr_finfo	= (APTR)xpr_finfo;
	XprIO -> xpr_fseek	= (APTR)xpr_fseek;
	XprIO -> xpr_extension	= 4;
	XprIO -> xpr_options	= (APTR)xpr_options;
	XprIO -> xpr_unlink	= (APTR)xpr_unlink;
	XprIO -> xpr_squery	= (APTR)xpr_squery;
	XprIO -> xpr_getptr	= (APTR)xpr_getptr;

		/* Open xprascii.library... */

	if(XProtocolBase = (struct Library *)OpenLibrary("xprascii.library",0))
	{
			/* Initialize it. */

		TransferBits = XProtocolSetup(XprIO);

			/* Successful initialization? */

		if(!(TransferBits & XPRS_SUCCESS))
		{
			MyEasyRequest(Window,"Failed to set up protocol\n\"%s\"!","Continue","xprascii.library");

			CloseLibrary(XProtocolBase);

			XProtocolBase = NULL;

			ProtocolSetup();

			return(FALSE);
		}
	}
	else
	{
		MyEasyRequest(Window,"Failed to open protocol\n\"%s\"!","Continue","xprascii.library");

		ProtocolSetup();

		return(FALSE);
	}

	BinaryTransfer = FALSE;

	return(TRUE);
}

	/* ASCIIShutdown():
	 *
	 *	Close down xprascii.library and reopen the library
	 *	set in the current configuration.
	 */

VOID
ASCIIShutdown()
{
	XProtocolCleanup(XprIO);

	CloseLibrary(XProtocolBase);

	XProtocolBase = NULL;

	ProtocolSetup();
}
