/*  Project Tec3270

	 SUBSYSTEM:    Tec3270.exe (Tec3270 application)
	 FILE:         alffnmd1.cpp
	 AUTHOR:       Alcindo Ferreira Filho

	 OVERVIEW:

    ALFFMDIChild Class Implementation, the Tec3270 session class.
    Sessions are childs of class ALFFMDIClient, the MDI manager.

    COPYRIGHT:    © 1998-2007
                  Alcindo Ferreira Filho
                  <alcindo@inttec.com.br>

    LICENSE:      Tec3270_License (docs/Tec3270_License.txt)
*/
#include "alffnall.h"

// Controls For Session Simulation On Debugging
//#define  DEBUG32    1
//#define  DEBUG_TN3270
//#define  TEST_TN3270E
//#define  DEBUG_NVT
//#define  DEBUG_PRT_DLG 1
//----------------------------------------------

//{{ALFFMDIChild Implementation}}
//
// Build a response table for all messages/commands handled
// by ALFFMDIChild derived from TMDIChild
//
DEFINE_RESPONSE_TABLE1(ALFFMDIChild, TMDIChild)
//{{ALFFMDIChildRSP_TBL_BEGIN}}
	 EV_WM_SIZE,
	 EV_WM_TIMER,
	 EV_MESSAGE(MSG_CLUSTER_NOTIFY, DoClusterNotification),
	 EV_MESSAGE(MSG_LINE_NOTIFY, DoLineNotification),
	 EV_MESSAGE(MSG_NET_INPUT_NOTIFY, DoNetInputProcess),
	 EV_MESSAGE(MSG_OUTPUT_NOTIFY, DoNetOutputProcess),
	 EV_MESSAGE(MSG_OUTPUT_ECHO, DoNetOutputEcho),
	 EV_MESSAGE(MSG_KEYB_MOUSE_ACTIVITY, EvResetTimer),
	 EV_MESSAGE(MSG_INIT_TERMINAL,EvInitTerminal),
    EV_MESSAGE(MSG_REMPRT_NOTIFY, EvRemPrtNotify),
    EV_MESSAGE(MSG_START_TLS, EvStartTLS),
    EV_MESSAGE(MSG_START_PRINTER, EvStartPrinter),
    EV_MESSAGE(MSG_OIA_CHANGED, EvOIAChanged),
    EV_MESSAGE(MSG_DOWNLOAD_FILE, EvLogMessage),
    EV_MESSAGE(MSG_CERTIFICATE_VERIFY, EvLogMessage),
    EV_MESSAGE(MSG_SET_LOG_MESSAGE, EvLogMessage),

	 /* Session Menu Command Handlers */
	 EV_COMMAND(CM_CONNECT, CmConnect),
	 EV_COMMAND(CM_DISCONNECT, CmDisconnect),
	 EV_COMMAND_ENABLE(CM_CONNECT, CmConnectEnable),
	 EV_COMMAND_ENABLE(CM_DISCONNECT, CmDisconnectEnable),

	 /* Find/Replace menu command handlers */
	 EV_COMMAND(CM_ALFFEDITFIND, CmEditFind),
	 EV_COMMAND_ENABLE(CM_ALFFEDITFIND, CeEditFindReplace),
	 EV_COMMAND(CM_ALFFEDITREPLACE, CmEditReplace),
	 EV_COMMAND_ENABLE(CM_ALFFEDITREPLACE, CeEditFindReplace),
	 EV_COMMAND(CM_ALFFEDITFINDNEXT, CmEditFindNext),
	 EV_COMMAND_ENABLE(CM_ALFFEDITFINDNEXT, CeEditFindNext),
	 EV_REGISTERED(FINDMSGSTRING, EvFindMsg),

	 /* Cut, Copy, and Paste Menu Command Handlers */
	 EV_COMMAND(CM_ALFFEDITCUT, CmEditCut),
	 EV_COMMAND(CM_ALFFEDITCOPY, CmEditCopy),
	 EV_COMMAND(CM_ALFFEDITPASTE, CmEditPaste),
	 EV_COMMAND(CM_ALFFEDITDELETE, CmEditDelete),
	 EV_COMMAND(CM_ALFFEDITCLEAR, CmEditClear),
	 EV_COMMAND(CM_ALFFEDITUNDO, CmEditUndo),
	 EV_COMMAND_ENABLE(CM_ALFFEDITCUT, CmSelectEnable),
	 EV_COMMAND_ENABLE(CM_ALFFEDITCOPY, CmSelectEnable),
	 EV_COMMAND_ENABLE(CM_ALFFEDITDELETE, CmSelectEnable),
	 EV_COMMAND_ENABLE(CM_ALFFEDITPASTE, CmPasteEnable),
	 EV_COMMAND_ENABLE(CM_ALFFEDITCLEAR, CmCharsEnable),
	 EV_COMMAND_ENABLE(CM_ALFFEDITUNDO, CmModEnable),

    /* Security Menu Command Handlers */
    EV_COMMAND(CM_ALFFCERTIFICATE, CmShowCertificate),
    EV_COMMAND_ENABLE(CM_ALFFCERTIFICATE,CmShowCertificateEnable),
    EV_COMMAND(CM_SECURITYINFO, CmShowSecurityInfo),
    EV_COMMAND_ENABLE(CM_SECURITYINFO,CmShowCertificateEnable),
    EV_MESSAGE(MSG_CHANGE_SECURITY_OPTIONS, UpdateSecurityOptions),
    
	 /* Options Menu Command Handlers */
	 EV_MESSAGE(MSG_CHANGE_FONT, UpdateFont),
	 EV_MESSAGE(MSG_CHANGE_COLORS, UpdateColors),
	 EV_MESSAGE(MSG_CHANGE_KEYBOARD, UpdateKeyboard),
	 EV_COMMAND(CM_TRACESESSION, CmTraceSession),
	 EV_COMMAND(CM_TOOLSLOGSCREEN, CmToolsLogScreen),
	 EV_COMMAND(CM_CHOOSECURSOR, CmChooseCursor),
	 EV_COMMAND(CM_OPTIONSCHANGESESSION, CmChangeSession),
	 EV_COMMAND_ENABLE(CM_TRACESESSION, CmTraceSessionEnable),
	 EV_COMMAND_ENABLE(CM_TOOLSLOGSCREEN, CmToolsLogScreenEnable),
	 EV_COMMAND_ENABLE(CM_CHOOSECURSOR, CmSessionEnable),
	 EV_COMMAND_ENABLE(CM_OPTIONSCHANGESESSION, CmSessionEnable),

//{{ALFFMDIChildRSP_TBL_END}}
END_RESPONSE_TABLE;


//////////////////////////////////////////////////////////
// ALFFMDIChild
// ==========
// Construction/Destruction handling.
ALFFMDIChild::ALFFMDIChild (TMDIClient &parent, const char far *title,
                                  ALFFDate::DateFormat fmt,
											 TWindow *clientWnd, int childCount,
											 bool shrinkToClient,
											 TModule *module) :
											 TMDIChild (parent, title, clientWnd == 0 ?
											 new ALFFVirtualTerm(0, 0, 0) :  clientWnd,
											 shrinkToClient, module),
											 nLineState(nIdle),
											 dataSent(true),
											 SearchData(FR_DOWN)
{
	 MDIParent = TYPESAFE_DOWNCAST(&parent,ALFFMDIClient);

	 /* Get the Application IniFile Pointer*/
	 Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
	 ALFFIniFile* iniFile = theApp->GetIniFile();

    dateFormat = fmt;

	 // Set Connection Data Up
    /* All ALFFConnData members initialization is done on its constructor */
	 connData = new ALFFConnData();

    char iniSection[21];
	 strcpy(iniSection,"DEFAULT COLORS");

	 connData->scrCharColor = iniFile->GetLong(iniSection,"TEXTCOLOR",TERMCHAR);
	 connData->scrBkgdColor = iniFile->GetLong(iniSection,"BKGDCOLOR",TERMBKGD);
	 connData->scr3270BkgdColor = iniFile->GetLong(iniSection,"BKGD3270COLOR",BKGD3270);
	 connData->scrNormalUnprotTextColor = iniFile->GetLong(iniSection,"NORMNPRTTEXT",NORMALUNPROT);
	 connData->scrHighlightUnprotTextColor = iniFile->GetLong(iniSection,"HIGHNPRTTEXT",HIGHUNPROT);
	 connData->scrNormalProtTextColor = iniFile->GetLong(iniSection,"NORMPROTTEXT",NORMALPROT);
	 connData->scrHighlightProtTextColor = iniFile->GetLong(iniSection,"HIGHPROTTEXT",HIGHPROT);
	 connData->neutral = iniFile->GetLong(iniSection,"NEUTRAL",DEFNEUTRAL);
	 connData->blue = iniFile->GetLong(iniSection,"BLUE",DEFBLUE);
	 connData->red = iniFile->GetLong(iniSection,"RED",DEFRED);
	 connData->pink = iniFile->GetLong(iniSection,"PINK",DEFPINK);
	 connData->green = iniFile->GetLong(iniSection,"GREEN",DEFGREEN);
	 connData->turquoise = iniFile->GetLong(iniSection,"TURQUOISE",DEFTURQUOISE);
	 connData->yellow = iniFile->GetLong(iniSection,"YELLOW",DEFYELLOW);
	 connData->inverseNeutral =  iniFile->GetLong(iniSection,"INVERSENEUTRAL",DEFINVNEUTRAL);
	 connData->black = iniFile->GetLong(iniSection,"BLACK",DEFBLACK);
	 connData->deepBlue = iniFile->GetLong(iniSection,"DEEPBLUE",DEFDEEPBLUE);
	 connData->orange = iniFile->GetLong(iniSection,"ORANGE",DEFORANGE);
	 connData->purple = iniFile->GetLong(iniSection,"PURPLE",DEFPURPLE);
	 connData->paleGreen = iniFile->GetLong(iniSection,"PALEGREEN",DEFPALEGREEN);
	 connData->paleTurquoise = iniFile->GetLong(iniSection,"PALETURQUOISE",DEFPALETURQUOISE);
	 connData->gray = iniFile->GetLong(iniSection,"GRAY",DEFGRAY);
	 connData->white = iniFile->GetLong(iniSection,"WHITE",DEFWHITE);

    /* Not yet created */
    pScript = NULL;
    scriptProcessing = false;

	 // Save Initial Child Title
	 connInitialTitle = title;
	 connStatusTitle = connInitialTitle;
	 connTextTitle = "";
	 connTraceTitle = "";
	 div_t res;
	 if (childCount>0)
		 res = div(childCount-1,MAXCHILDPERTIME);
	  else res = div(1,MAXCHILDPERTIME);
	 connNumber = res.rem+1;
	 connShift  = res.quot;

#ifdef DEBUG32
	MessageBox("Criando Buffers...","Tec3270 Debug",MB_OK);
#endif

	 // Create Ring Buffers For Send & Receive Data
	 pLineInBuf   = new ALFFBuffer(5*BUFSIZE);
	 pLineOutBuf  = new ALFFBuffer(10*BUFSIZE);
	 pNetInBuf  = new ALFFBuffer(15*BUFSIZE);
	 pNetOutBuf = new ALFFBuffer(10*BUFSIZE);
	 pOOBData    = new ALFFBuffer(BUFSIZE/2);

#ifdef DEBUG32
	MessageBox("Criando ALFFCommLine...","Tec3270 Debug",MB_OK);
#endif

	 // Create Line Communication Object
	 pLineComm = new ALFFCommLine(this, theApp->GetSecurityObj(), dateFormat);

    // Use Asynchronous Line Mode
    pLineComm->StartLineNotification();

	 timerOn   = false;

#ifdef DEBUG32
	MessageBox("Criando ALFFNvt...","Tec3270 Debug",MB_OK);
#endif

	 // Create NVT Object for processing Basic Terminal stream
#define TERMINALBUFFER false
	 pNVTBuf = new ALFFNvt(connData, TERMINALBUFFER);

#ifdef DEBUG32
	MessageBox("Criando ALFF3270...","Tec3270 Debug",MB_OK);
#endif
	 // Create Terminal 3270 Object for processing 3270 stream
	 p3270Buf = new ALFF3270(connData);
	 termBufferInitialized = false;

#ifdef DEBUG32
	MessageBox("Criando ALFFTelnet...","Tec3270 Debug",MB_OK);
#endif
	 // Create Telnet Object for processing Telnet Data
	 pTelnet = new ALFFTelnet(this, connData);

	 // Setup Event driven Process Controls
	 netInputProcessing = false;
	 netInputQueue    = 0;
    dataTypeQueue    = new WPARAM[32];
	 receiving = false;
	 recvQueue = 0;
	 sending = false;
	 sendQueue = 0;

	 // Setup Log Data Trace Status Off
	 traceON = false;
	 SetScrLogOn(false);
	 pTrcFile = NULL;
	 pConnLog = NULL;

	 // Setup ALFF Messages Object
	 pMsgs = new ALFFMsgs(this);

	 /* Find/Replace Controls Setup */
	 SearchDialog = NULL;
	 SearchCmd = 0;
	 strReplaced = false;
	 strFound = false;
	 lastOper = 0;

	 autoConnect = false;
	 numReconnTries = 0;
    disconnectedByHost = false;

    /* SSL Controls */
    connectPendingForReadWrite = false;
    receiveDataPendingForReadWrite = false;
    sendDataPendingForReadWrite    = false;
    disconnectPendingForReadWrite = false;

    /* Remote Printer (TN3270E Sessions Only) */
    pRemotePrt = NULL;

    // WHLLAPI controls
    SetWHLLSession(false);
    SetWHLLClosing(false);
    SetWaitingHostResponse(false);
    SetWHLLPSChanged(PSNOTCHANGED);
    sessionNotifyPSChanges = PSNONOTIFY;
    hllCertPath = NULL;
    hllCertPwd = NULL;
}

ALFFMDIChild::~ALFFMDIChild ()
{
 Destroy();

 delete pTerminal;
 delete pLineComm;
 delete pTelnet;
 delete p3270Buf;
 delete pNVTBuf;
 delete pLineInBuf;
 delete pLineOutBuf;
 delete pNetInBuf;
 delete pNetOutBuf;
 delete pOOBData;

 if (SearchDialog)
	    delete SearchDialog;
 delete pMsgs;
 delete [] dataTypeQueue;

 // If Remote Printer is still active, disconnect and delete it
 // See Disconnect() method, as it would be deleted there !
 if (pRemotePrt)
  {
   pRemotePrt->Disconnect();
   delete pRemotePrt;
   pRemotePrt = NULL;
  }

 delete connData;

 if (pTrcFile)
  {
	pTrcFile->LogText(IDS_ALFFSESSTRACEEND, GetApplication()->GetInstance());
	pTrcFile->LogText(IDS_ALFFSESSTRCLOGEND, GetApplication()->GetInstance());
	delete pTrcFile;
  }
 if (pConnLog)
  {
	pConnLog->LogText(IDS_ALFFSESSTRCLOGEND, GetApplication()->GetInstance());
	delete pConnLog;
  }

 // Delete Certificate info if it is still available
 if (hllCertPath != NULL)
   delete [] hllCertPath;

 if (hllCertPwd != NULL)
     delete [] hllCertPwd;
}

void
ALFFMDIChild::SetWindowTitle()
{
 string wTitle;
 if (connData->scriptOn && strlen(connData->sessTitle))
  wTitle = connStatusTitle + connData->sessTitle + connSSLStatus + connTraceTitle;
 else wTitle = connStatusTitle + connData->connName + connSSLStatus + connTraceTitle;
 SetCaption(wTitle.c_str());
}

void
ALFFMDIChild::SetupWindow()
{
 TMDIChild::SetupWindow();

 SetWindowTitle();

#ifdef DEBUG32
	MessageBox("ALFFMDIChild:SetupWindow - Inicio...","Tec3270 Debug",MB_OK);
#endif
#ifdef DEBUG32
	MessageBox("ALFFMDIChild:SetupWindow - Criando ALFFVirtualTerm...","Tec3270 Debug",MB_OK);
#endif

 // Set Session Menu
 SetMenuDescr(TMenuDescr(IDM_ALFFSESS,0,2,0,0,2,0));

 if (!GetClientWindow())
   {
    pTerminal = new ALFFVirtualTerm(this,connInitialTitle.c_str());
    TWindow* oldClient = SetClientWindow(pTerminal);
    if (oldClient)
      {
		 oldClient->Destroy();
       delete oldClient;
      }
    }
 else { pTerminal = TYPESAFE_DOWNCAST(GetClientWindow(),ALFFVirtualTerm); }

 if (SearchCmd)
	PostMessage(WM_COMMAND, SearchCmd);

 SendMessage(MSG_INIT_TERMINAL,0,0);
}

LRESULT
ALFFMDIChild::EvInitTerminal(WPARAM, LPARAM)
{
#ifdef DEBUG32
	MessageBox("ALFFMDIChild:EvInitTerminal - InitTerminal...","Tec3270 Debug",MB_OK);
#endif
 char* line = new char[256];
 line[0] = NULL;
 if (pTerminal != NULL)
  {
	 // Initialize Terminal on TELNET Network Virtual Terminal (NVT)
	 pTerminal->InitTerminal(this, p3270Buf, pNVTBuf, connData);
	 InitTerminalBuffer(NVTMODE);
#ifdef DEBUG32
	MessageBox("ALFFMDIChild:EvInitTerminal - GetApplication...","Tec3270 Debug",MB_OK);
#endif
	 /* Access the Application Scope */
	 Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(), Tec3270App);

#ifdef DEBUG32
	MessageBox("ALFFMDIChild:EvInitTerminal - LoadStringLINECLUSTER...","Tec3270 Debug",MB_OK);
#endif
   int lineSize = pTerminal->GetScrLineSize();

	// Display Initial Informations On Screen
	theApp->LoadString(IDS_LINECLUSTER,line,lineSize);
	strcat(line,theApp->GetClusterInfo());
   if (strlen(line) > lineSize)
     memset(line+lineSize,0x00,1);
	pTerminal->WriteNVTLine(line);

#ifdef DEBUG32
	MessageBox("ALFFMDIChild:EvInitTerminal - LoadStringCOMPUTERNAME...","Tec3270 Debug",MB_OK);
#endif
	line[0] = NULL;
	theApp->LoadString(IDS_COMPUTERNAME,line,lineSize);
	strcat(line,theApp->GetComputerName());
   if (strlen(line) > lineSize)
     memset(line+lineSize,0x00,1);
	pTerminal->WriteNVTLine(line);

#ifdef DEBUG32
	MessageBox("ALFFMDIChild:EvInitTerminal - LoadStringCOMPUTERADDRESS...","Tec3270 Debug",MB_OK);
#endif
	line[0] = NULL;
	theApp->LoadString(IDS_COMPUTERADDRESS,line,lineSize);
	strcat(line,theApp->GetComputerAddress());
   if (strlen(line) > lineSize)
     memset(line+lineSize,0x00,1);
	pTerminal->WriteNVTLine(line);
  }

 delete [] line;

#ifdef DEBUG_PRT_DLG
   // Check for remote printer connection option (connData->.....)
   //=============================================================
   pRemotePrt = new ALFFRemotePrinter(this,
                                         connData,
                                         connNumber);
   pRemotePrt->Create();
   pRemotePrt->ShowWindow(SW_SHOW);
#endif
 return 1L;
}

LRESULT
ALFFMDIChild::EvRemPrtNotify(WPARAM wParam, LPARAM lParam)
{
#define PRINTER true
 if (wParam != 0)
   SessionMessage(wParam, PRINTER);
 else if (lParam != 0)
   SessionMessage ((const char*) lParam, PRINTER);
 return 1L;
}

LRESULT
ALFFMDIChild::EvStartPrinter(WPARAM, LPARAM)
{
#ifndef DEBUG_PRT_DLG
 /* This event is started on ALFFTelnet on SetIn3270 Method,
  *  when connection is put on 3270 Mode (either TN3270 or TN3270E)
  */
 if ((!pRemotePrt) && (!connData->printerInact))
  {
   pRemotePrt = new ALFFRemotePrinter(this,
                                         dateFormat,
                                         connData,
                                         connNumber);
   pRemotePrt->Create();
   pRemotePrt->ShowWindow(SW_SHOW);
  }
#endif
 return 1L;
}


void
ALFFMDIChild::SessionMessage(const int errorId, bool fromPrinter)
{
 char* errText = NULL;
 if (fromPrinter)
  {
   errText = new char[STRINGMSGLEN];
   pMsgs->LoadString(IDS_REMPRTHEADER, errText, STRINGMSGLEN-1);
  }

 pTerminal->WriteNVTLine(errorId, errText);

 /* If log option was set then log connection begin */
 if (connData->connLog)
	  pConnLog->LogText(errorId, GetApplication()->GetInstance(), errText);

 if (errText != NULL)
  delete [] errText;
}

void
ALFFMDIChild::SessionMessage(const char* errorMsg, bool fromPrinter)
{
#define MAXMESSAGELENGTH  256
 char* errText = NULL;
 char  messageErr[MAXMESSAGELENGTH];
 int errorMsgLen = strlen(errorMsg);
 if (fromPrinter)
  {
   errText = new char[STRINGMSGLEN];
   pMsgs->LoadString(IDS_REMPRTHEADER, errText, STRINGMSGLEN-1);
   int excess = (errorMsgLen + strlen(errText)) - MAXMESSAGELENGTH ;
   if (excess > 0)
     strncpy(messageErr, errorMsg, errorMsgLen-excess-1);
   else strcpy(messageErr, errorMsg);
   strcat(messageErr," (");
   strcat(messageErr,errText);
   strcat(messageErr,")");
  }
 else strncpy (messageErr, errorMsg, MAXMESSAGELENGTH-1);

 pTerminal->WriteNVTLine(messageErr);

 /* If log option was set then log connection begin */
 if (connData->connLog)
	  pConnLog->LogText(messageErr, strlen(messageErr));

 if (errText != NULL)
  delete [] errText;
}

void
ALFFMDIChild::TimeMessage()
{
 /* Register Date and Time at what connection was ended */
 char text[STRINGMSGLEN];
 Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
 theApp->GetTimeStamp(text);

 /* If log option was set then log connection begin or end */
 if (connData->connLog)
	 pConnLog->LogText(text,strlen(text));

 /* Show Message on Terminal */
 pTerminal->WriteNVTLine(text);
}

void
ALFFMDIChild::LineError(int cError)
{
	char stringError[STRINGMSGLEN];
	char msgError[STRINGMSGLEN*2];

	if (cError == INVALID_CONNECTION_STATE)
		{
        if (!IsWHLLSession())
          pMsgs->Message(IDS_ALFFINVSESSSTATE, IDS_ALFFSESSTITLE);
        else SessionMessage(IDS_ALFFINVSESSSTATE);
      }
	else
		{
		 pMsgs->LoadString(IDS_ALFFCOMMCLUSTERERR,stringError,STRINGMSGLEN);
		 sprintf(msgError,stringError,cError);
		 strncpy(stringError,
					  ALFFLineError(cError).ReportError(),
					  LINE_STRING_ERROR_LENGTH);
		 strcat(msgError,"\n");
		 strcat(msgError,stringError);
       if (!IsWHLLSession())
		   pMsgs->StrMessage(msgError,0,IDS_ALFFSESSTITLE);
       else
         /* Log Error on Screen and Log File if is active*/
  	      SessionMessage(stringError);

		}
	  /* Log Error on Screen and Log File if is active*/
	  SessionMessage(stringError);

	  /* Register the error message and Disconnect Session */
	  SessionMessage(IDS_LINECLOSEDBYERROR);
	  Disconnect(false);
}

LRESULT
ALFFMDIChild::DoClusterNotification(WPARAM, LPARAM lParam)
{
	int cError;
	cError = pLineComm->DoClusterNotification(lParam);

	/* If there is any timer running, reset it !! */
	ResetTimer();

	if (cError)
	 { LineError(cError); }
	 else
	  {
		//  This call of LineConnect need no parameters because
		//   previous call was passed them.
		//  At this point LineConnect MUST be in waitingforhostaddress
		//   state.
		cError = pLineComm->LineConnect("  ","  ");
		if (cError)
        { LineError(cError); }
	  }
	return 1L;
}

void
ALFFMDIChild::ActivateConnection()
{
	char text[STRINGMSGLEN];
   int  statusId;

   // The session was disconnect by host, so do the session cleanup
   if (disconnectedByHost)
    {
     DisconnectedByHost();
     return;
    }

	// Update Child Caption To Reflect Connection Status
   if (IsSSLConnecting())
    {
     SetSSLConnectedState();
     statusId = IDS_LINESTATSECURECONNECTED;
    }
   else if (IsConnecting())
    {
     SetConnectedState();
     statusId =  IDS_LINESTATCONNECTED;
    }
   else
    {
      if (!IsWHLLSession())
         pMsgs->StrMessage("ActivateConnection",IDS_ALFFINVSESSSTATE, IDS_ALFFSESSTITLE);
      else
      {
       SessionMessage("ActivateConnection");
       SessionMessage(IDS_ALFFINVSESSSTATE);
      }
      pTerminal->Disconnect();
    }

	pMsgs->LoadString(statusId, text, STRINGMSGLEN-1);
	connStatusTitle = text;
	text[0] = NULL;
	strcat(text, connStatusTitle.c_str());
   if ( (connData->sessTitle[0]) &&  (strlen(connData->sessTitle)) )
   	strcat(text, connData->sessTitle);
	else strcat(text, connData->connName);

	/* Log Connection status on Screen and Log File if it is active*/
	SessionMessage(text);

	/* Register Date and Time at what connection begins */
	TimeMessage();
   text[0] = CR;
   text[1] = LF;
   text[2] = NULL;
   SessionMessage(text);
   
	/* Update Connection Window caption and icon */
	SetWindowTitle();

 	if (!autoConnect)
	   Show(SW_SHOWMAXIMIZED);

   /* Put Terminal State in Connected State - ALFFVirtualTerm - Not really connect*/
	pTerminal->Connect(false,true); // TERM TYPE INDEPENDENT

   /* Further will we receive telnet commands from telnet server
    * through an Line_Read notification on DoLineNotification
    * method that are in following
    */
}

LRESULT
ALFFMDIChild::DoLineNotification(WPARAM, LPARAM lParam)
{
	int nEvent = LOWORD(lParam);
	int lError = HIWORD(lParam);
	char stringError[LINE_STRING_ERROR_LENGTH];

	/* Access the Application Scope */
	Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(), Tec3270App);

	if (!lError)
	 nEvent = pLineComm->DoLineNotification(nEvent);

	/* If there is any timer running, reset it !! */
	ResetTimer();

	//--------------------------TRACE---------------------------------
	#ifdef ALFFTrace
	char message[50];
	char evento [10];
	switch (nEvent)
	 {
	  case LINE_CONNECT  : strcpy(evento,"LINE_CONNECT");
								  break;
	  case LINE_READ     : strcpy(evento,"LINE_READ");
								  break;
	  case LINE_WRITE    : strcpy(evento,"LINE_WRITE");
								  break;
	  case LINE_CLOSE    : strcpy(evento,"LINE_CLOSE  ");
								  break;
	  case LINE_ACCEPT   : strcpy(evento,"LINE_ACCEPT ");
								  break;
	  case LINE_OOB      : strcpy(evento,"LINE_OOB");
								  break;
	  default            : strcpy(evento,"UNKNOW ");
								  break;
	 }
	sprintf(message,"Line Notification Received : Event %s",evento);
	MessageBox(message,
				  "Tec3270 Trace Info",
				  MB_OK | MB_ICONEXCLAMATION);
	#endif
	//----------------------------------------------------------------

	/* If option specified for this session, bring this window to top */
	if (connData->bringTop)
	  BringWindowToTop();

	/* Process line event */
	if (nEvent == LINE_WRITE)
	 {
     ///////////////////////////  Event LINE_WRITE /////////////////////////////
	  if ( (connectPendingForReadWrite)   // Connect  	Pending Read/Write  (SSL)
        ||(sendDataPendingForReadWrite)  // SendData 	Pending Read/Write  (SSL)
        ||(receiveDataPendingForReadWrite) // ReceiveData Pending Read/Write(SSL)
        ||(!dataSent) )
	  {
		if(lError)
		 {
			stringError[0]=NULL;
			strncpy(stringError,
					  ALFFLineError(lError).ReportError(),
					  LINE_STRING_ERROR_LENGTH);
         if (!IsWHLLSession())
			   pMsgs->StrMessage(stringError,0,IDS_ALFFSESSTITLE);

			/* Log Error on Screen and Log File if is active*/
			SessionMessage(stringError);
		 }

      else if ( IsConnecting() )
       {
         // It would never occurs, but if it comes, advise user as an error
         if (!IsWHLLSession())
           pMsgs->StrMessage("LINE_WRITE/IsConnecting",IDS_ALFFINVSESSSTATE,IDS_ALFFSESSTITLE);
         SessionMessage("LINE_WRITE/IsConnecting");
         SessionMessage(IDS_ALFFINVSESSSTATE);
       }
		else if (IsSSLConnecting())    //(nEvent == LINE_WRITE)
       {
        if (connectPendingForReadWrite)
         {
          connectPendingForReadWrite = false;
          // Re-Initiate SSL Negotiation
          int rc = ConnectSecurity();
          if (rc == SSL_CONNECTION_OK)
			    ActivateConnection();
         }
       }

      else if (IsSSLConnected() || IsConnected())
       {
        if (receiveDataPendingForReadWrite)
         {
			 // receiveDataPendingForReading = false;  (will be done on following method)
          ReceiveDataEnqueued();
         }

        else if (sendDataPendingForReadWrite)
         {
          sendDataPendingForReadWrite = false;
           // Redo writing of data !!
			 SendData();
         }
       }

		else if (IsSSLDisconnecting())    //(nEvent == LINE_WRITE)
       {
        if (disconnectPendingForReadWrite)
         // Re-Initiate SSL Disconnecting ....
         Disconnect(false);
        //else ignore LINE_WRITE event
       }

      else if (IsIdle())
       {
			// Ignore event:  Nothing to do !!
       }
      else
       {
        if (!IsWHLLSession())
           pMsgs->StrMessage("Unknow", IDS_ALFFINVSESSSTATE,IDS_ALFFSESSTITLE);
        SessionMessage("Unknow");
        SessionMessage(IDS_ALFFINVSESSSTATE);
       }
	  }
     /////////////////////////// End Event LINE_WRITE //////////////////////////
	 }
	else if(nEvent == LINE_READ)
	  {
     /////////////////////////// Event LINE_READ ///////////////////////////////
		if(lError)
		 {
			stringError[0]=NULL;
			strncpy(stringError,
					  ALFFLineError(lError).ReportError(),
					  LINE_STRING_ERROR_LENGTH);
         if (!IsWHLLSession())
    			pMsgs->StrMessage(stringError,0,IDS_ALFFSESSTITLE);

			/* Log Error on Screen and Log File if is active*/
			SessionMessage(stringError);
		 }
      else if ( IsConnecting() )
       {
#ifdef ALFFDebug
         ReceiveDataEnqueued();
#else
         // It would never occurs, but if it comes, enqueue it until
         //  LINE_CONNECT is received.
         receiveDataPendingForReadWrite = true;
#endif
       }
		else if (IsSSLConnecting())    //(nEvent == LINE_READ)
       {
        if (connectPendingForReadWrite)
         {
          connectPendingForReadWrite = false;
          // Re-Initiate SSL Negotiation
          int rc = ConnectSecurity();
          if (rc == SSL_CONNECTION_OK)
			    ActivateConnection();
         }
       }
      else if ( IsConnected() || IsSSLConnected() )
		 {
        if (sendDataPendingForReadWrite)
         {
          sendDataPendingForReadWrite = false;
          // Redo writing of data !!
          SendData();
         }
        else
         {
          // At this state we must have sendData or Receive Data being
          //  enqueued waiting for LINE_READ, so if it is not sendDataPendingForReadWrite
          //  it must be receiveDataPendingForReadWrite
          ReceiveDataEnqueued();
          SetWaitingHostResponse(false);
         }
		 }
		else if (IsSSLDisconnecting())    //(nEvent == LINE_READ)
       {
        if (disconnectPendingForReadWrite)
         {
          disconnectPendingForReadWrite = false;
          // Re-Initiate SSL Disconnecting ....
          Disconnect(false);
         }
       }

      else if (IsIdle())
       {
			// Ignore event:  Nothing to do !!
       }

      else
       {
        if (!IsWHLLSession())
          pMsgs->StrMessage("Unknow", IDS_ALFFINVSESSSTATE,IDS_ALFFSESSTITLE);
        SessionMessage("Unknow");
        SessionMessage(IDS_ALFFINVSESSSTATE);
       }

      ///////////////////////////  End Event LINE_READ /////////////////////////
	  }

	else if(nEvent == LINE_OOBDATA)
	  {
      //////////////////// Event LINE_OOBDATA (Read) ///////////////////////////

		/////////////////////////////////////////////////////////////////////////
		//   VERIFICAR:    DEVE PREVER O SSL ?????????????
		/////////////////////////////////////////////////////////////////////////
		if(lError)
		 {
			stringError[0]=NULL;
			strncpy(stringError,
					  ALFFLineError(lError).ReportError(),
					  LINE_STRING_ERROR_LENGTH);
         if (!IsWHLLSession())
			   pMsgs->StrMessage(stringError,0,IDS_ALFFSESSTITLE);

			/* Log Error on Screen and Log File if is active*/
			SessionMessage(stringError);
		 }
		else
		 {
        ReceiveDataEnqueued(URGENT);
		 }
      //////////////////// End of Event LINE_OOBDATA (Read) ////////////////////
	  }

	else if(nEvent == LINE_CONNECT)
	  {
      //////////////////// Event LINE_CONNECT //////////////////////////////////
		if(lError)
		  {
			strncpy(stringError,
					  ALFFLineError(lError).ReportError(),
					  LINE_STRING_ERROR_LENGTH);
         if (!IsWHLLSession())
				pMsgs->StrMessage(stringError,IDS_ALFFLINECONNERR,
													IDS_ALFFSESSTITLE);

			/* Log Error on Screen and Log File if is active*/
			SessionMessage(stringError);

			/* Inform Date and Time when connection error ocurred
				and reset all session status to Idle  */
			SessionMessage(IDS_LINECLOSEDBYERROR);
			Disconnect(false);
		  }
		else if (IsConnecting())
		  {
         // Check for SSL connections
         if (IsSecureConnection())
          {
           // Initiate SSL-TLS  Negotiation
           SetSSLConnectingState();

           int rc = ConnectSecurity();
           if (rc == SSL_CONNECTION_OK)
     				ActivateConnection();
          }
         else ActivateConnection();

         // If there is any LINE_READ received before do the read
         //    operation
         if (receiveDataPendingForReadWrite == true)
             ReceiveDataEnqueued();
		  }
      else // Any other state is invalid
        {
         char stateNumber[10];
         sprintf (stateNumber, "< %i >", nLineState);
         if (!IsWHLLSession())
            pMsgs->StrMessage(stateNumber, IDS_ALFFINVSESSSTATE,IDS_ALFFSESSTITLE);
         SessionMessage(IDS_ALFFINVSESSSTATE);
         SessionMessage(stateNumber);
        }
      //////////////////// End of Event LINE_CONNECT ///////////////////////////
	  }

	else if (nEvent == LINE_CLOSE)
	  {
      //////////////////// Event LINE_CLOSE ////////////////////////////////////
		if(lError)
		 {
		  stringError[0]=NULL;
		  strncpy(stringError,
					 ALFFLineError(lError).ReportError(),
					 LINE_STRING_ERROR_LENGTH);
        if (!IsWHLLSession())
		     pMsgs->StrMessage(stringError,0,IDS_ALFFSESSTITLE);

		  /* Log Error on Screen and Log File if is active*/
		  SessionMessage(stringError);

        if ( IsConnecting() || IsConnected() || IsSSLConnected() )
         {
   		 SessionMessage(IDS_LINECLOSEDBYERROR);

		    CloseTerminal();

		    /* Register Date and Time at what connection was ended */
		    TimeMessage();

	       /* If connection remains active set initial state */
  	       SetIdleState();
         }
        else if ( IsSSLConnecting() || IsSSLDisconnecting() )
         {
          // register host disconnection for further processing
          //  on SSL routines, only if SSLSocket status isn't
          //  SSL_WANT_READ
          if (connectPendingForReadWrite)
           {
            connectPendingForReadWrite  = false;
            DisconnectedByHost();
           }
          else disconnectedByHost = true;
         }
        // else ignore this event as we are in Disconnecting process.
		 }
      else if ( IsConnecting() || IsConnected() || IsSSLConnected() )
       {
         DisconnectedByHost();
       }
      else if ( IsSSLConnecting() || IsSSLDisconnecting() )
       {
         // register host disconnection for further processing
         //  on SSL routines, only if SSLSocket status isn't
         //  SSL_WANT_READ
         if (connectPendingForReadWrite)
          {
           connectPendingForReadWrite  = false;
           DisconnectedByHost();
          }
         else disconnectedByHost = true;
       }
       // else ignore this event as we are in Disconnecting process.
      //////////////////// End of Event LINE_CLOSE /////////////////////////////
	  }

   //////////////////// INTERNAL ERROR ////////////////////////////////////////
	else
    {
     char eventErr[128];
     sprintf (eventErr,"[ %i ]",nEvent);
     if (!IsWHLLSession())
        pMsgs->StrMessage(eventErr,IDS_SESSNETEVENTUNKNOW,IDS_ALFFSESSTITLE);
     SessionMessage(IDS_SESSNETEVENTUNKNOW);
     SessionMessage(eventErr);
    }

	return 1L;
}

void
ALFFMDIChild::ReceiveDataEnqueued(bool urgent)
{
 // This method enqueues all  LINE_READ / LINE_WRITE events
 //  that must be directed to ReceiveData method.
 //
 // Note that SSL Connections may want read or write in read or
 // write data operations, because SSL protocol may want to renegotiate
 // encryption keys on any operation.
 //
 // All variables are global for having its scope available for each
 // operation that may be called from.
 //
 recvQueue++;
 if (!receiving)
  {
   receiving=true;
   while (recvQueue)
    {
     receiveDataPendingForReadWrite=false;
     ReceiveData(urgent);
     if (IsWHLLSession() && IsWHLLHostNotifying() )
      {
       if (GetWHLLPSChangeType() == PSOIAUPDATED)
        SetWHLLPSChanged(PSBOTHUPDATED);
       else SetWHLLPSChanged(PSUPDATED);
      }
	  recvQueue-=1;
    }
   receiving=false;
  }
}

LRESULT
ALFFMDIChild::EvLogMessage(WPARAM /*wParam*/, LPARAM msgId)
{
 if (msgId < 32767)
    SessionMessage(msgId, false);
 else
    SessionMessage((char*)msgId, false);
 return 1L;
}

LRESULT
ALFFMDIChild::EvOIAChanged(WPARAM, LPARAM)
{
 if (IsWHLLSession() )
  {
   if (GetWHLLPSChangeType() == PSUPDATED)
     SetWHLLPSChanged(PSBOTHUPDATED);
   else SetWHLLPSChanged(PSOIAUPDATED);
  }
 return 1L;
}

short
ALFFMDIChild::CopyPSToString(unsigned char** byString, short byStringLen,
                                short psPosition, bool noAttrb, bool noEAB,
                                bool eabXlat, bool noDisplay)
{
 // Size of Screen buffer to be copied must be greater than 0 !!
 if ( !(byStringLen > 0) )
   return WHLLPARAMETERERROR;

 // Terminal must be connected to Host (either NVT or 3270 Mode)
 if (!pTerminal->IsConnected())
   return WHLLNOTCONNECTED;

 // PS (3270 Buffer) position must be inside of NVT or 3270 Buffer limits
 int bufferSize;
 if (pTerminal->IsMode3270())
   bufferSize = p3270Buf->Get3270BufSize();
 else return WHLLNOTCONNECTED; // bufferSize = pNVTBuf->GetNVTBufSize();

 int fromPos = psPosition-1;
 int endPos   = fromPos+byStringLen; // Must be in that way because of DataToScreen behavior

 if ( (fromPos >= 0)
    &&(fromPos < bufferSize) )
  {
   // Set 3270 Buffer Selection
   if (!p3270Buf->SetSelection(fromPos, endPos))
     return WHLLPARAMETERERROR;

   // Copy control fields
   Field*      fdCopy;
   int textOffset = 0;
   int suboption = TOENDOFFIELD;
   // Do the copy
   while (fromPos != -1)
    {
     fdCopy = p3270Buf->DataToScreen(fromPos, SELECTION, suboption, ASCII,
                                     noAttrb, eabXlat, noDisplay);
     if (!noEAB)
      {
       //Extended attributtes must be created from fdCopy Attrs
       //Don't forget to verify max string len on output !!!
      }
     int textLen = strlen(fdCopy->fdText);
     if ( (textLen)
        &&((textOffset+textLen) <= byStringLen) )
      {
       memcpy(*byString+textOffset, fdCopy->fdText, textLen);
       textOffset += textLen;
       suboption = CONTINUE;
      }
    }

   //Remove 3270 Buffer Selection
   p3270Buf->SetSelection(-1,-1);

   if (textOffset)
    {
      if (pTerminal->IsKeyboardLocked())
       return WHLLINHIBITED;
      else if ( IsWaitingHostResponse() )
       return  WHLLPSBUSY;
      else return WHLLOK;
    }
   else return WHLLSYSERROR;
  }
 else return WHLLPOSITIONERROR;
}

short
ALFFMDIChild::CopyStringToPS(unsigned char* byString, short byStringLen,
                                short psPosition)
{
 // Size of Screen buffer to be copied must be greater than 0 !!
 if ( !(byStringLen > 0) )
   return WHLLPARAMETERERROR;

 // Terminal must be connected to Host (either NVT or 3270 Mode)
 if (!pTerminal->IsConnected())
   return WHLLNOTCONNECTED;

 // If Host PS is protected from input ...
 if (pTerminal->IsKeyboardLocked())
   return WHLLINHIBITED;

 // PS (3270 Buffer) position must be inside of NVT or 3270 Buffer limits
 int bufferSize;
 if (pTerminal->IsMode3270())
   bufferSize = p3270Buf->Get3270BufSize();
 else return WHLLNOTCONNECTED; // bufferSize = pNVTBuf->GetNVTBufSize();

 int fromPos = psPosition-1;
 int endPos   = fromPos+byStringLen; // Must be in that way because of DataToScreen behavior

 if ( (fromPos >= 0)
    &&(fromPos < bufferSize) )
  {
    p3270Buf->SetCursorPos(fromPos);
    pTerminal->SetCursorPos(fromPos);
	 int rc = p3270Buf->DataFromKeyboard((char*)&byString[0],byStringLen,false); // Not in Insert Mode
	 if (rc < 0)
	  {
		char err[12];
		if (rc == PROTECTEDFIELD)
			 strcpy(err,PROTECTEDFD);
		else if (rc == NUMERICFIELD)
					strcpy(err,NUMERICFD);
		else strcpy(err,XSYSTEM);
      pTerminal->PaintScreen();
		pTerminal->LockKeyboard(err);
      if (p3270Buf->GetKeyCount())
          return WHLLTRUNCATED;
      else return WHLLINHIBITED;
	  }
    else pTerminal->PaintScreen();
  }
 else return WHLLPOSITIONERROR;

 return WHLLOK;
}

short
ALFFMDIChild::SendKeyStrokes(unsigned char* byString, short& byStringLen,
                                bool autoReset, char escapePFKChar)
{
 register int byte;
 short returnCode = WHLLOK;

 // Size of Screen buffer to be copied must be greater than 0 !!
 if ( !(byStringLen > 0) )
   return WHLLPARAMETERERROR;

 // Terminal must be connected to Host and in 3270 Mode
 if (!pTerminal->IsConnected() || (!pTerminal->IsMode3270()) )
  {
   byStringLen = 0;
   return WHLLNOTCONNECTED;
  }

 // If this session option is set to AUTORESET,
 // a reset code is always added to the beginning of the keystroke string,
 // resetting all states that can be reset (except input-inhibited states).
 if (autoReset)
  {
   SetWHLLHostNotification(PSNONOTIFY);
  }

 short keyStrokesLen = byStringLen;
 char escKey = escapePFKChar;
 unsigned char pos;
 unsigned char* strokeBuf = byString;
 bool insertMode, aid,  alt = false, shift = false;
 int fdBegin, command = -1;

#define BEGIN_STROKE      1
#define PROCESS_FUNCTION_KEY    2
 int strokeState = BEGIN_STROKE;
 while ((returnCode == WHLLOK) && (keyStrokesLen))
  {
   pos = *strokeBuf;
   byte = HEX(*strokeBuf++); keyStrokesLen--;
   switch (strokeState)
    {
     case BEGIN_STROKE:
          if (pos == escKey)
            strokeState = PROCESS_FUNCTION_KEY;
          else
           {
             if (!pTerminal->IsKeyboardLocked())
              {
               insertMode = pTerminal->GetInsertMode();
 		         fdBegin = p3270Buf->DataFromKeyboard((char*)&pos, 1, insertMode);
		         /* Update Terminal Screen */
		         pTerminal->UpdateScreen(fdBegin,LASTUPDATED,insertMode);
		        }
             else returnCode = WHLLINHIBITED;
           }
          break;

     case PROCESS_FUNCTION_KEY:
          aid = false;
          switch (pos)
		     {
            case     'A': // ALT Key
                     alt = true;
                     command = 0;
                     break;
            case     'S': // SHIFT Key
                     shift = true;
                     command = 0;
                     break;
            case     'Q': //  New Line
                     if (alt)
                      {
                       command = IDS_NEWLINE;
                       alt = false;
                      }
                     else
                      {
                       command = 0;
                       returnCode = WHLLINHIBITED;
                      }
                     break;
            case     '<': // BackSpace Key
                     command = IDS_BACKSPACE;
                     break;
            case     'B': // BackTAB
                     command = IDS_PREVFIELD;
                     break;
            case     'C': // Clear
                     command = IDS_CLEAR;
                     aid     = true;
                     break;
            case     'V': // Cursor Down
                     command = IDS_CURSORDOWN;
                     break;
            case     'L': // Cursor Left
                     command =  IDS_CURSORLEFT;
                     break;
            case     'Z': // Cursor Right
                     command =  IDS_CURSORRIGHT;
                     break;
            case     'U': // Cursor Up
                     command =  IDS_CURSORUP;
                     break;
            case     'J': //  Cursor Select
                     if (alt)
                      {
                       command =  IDS_CURSEL;
                       alt = false;
                      }
                     else
                      {
                       command = 0;
                       returnCode = WHLLINHIBITED;
                      }
                     break;
            case     'D': // Del
                     command = IDS_DEL;
                     break;
            case     'q': //  Cursor End
                     command = IDS_CURSOREND;
                     break;
            case     'E': //   ENTER
                     command = IDS_ENTERCOMMAND;
                     aid     = true;
                     break;
            case     'F': //   ERASEOF
                     if (alt)
                      {
                       command = IDS_ERASINPUT;
                       alt = false;
                      }
                     else command = IDS_ERASEOF;
                     break;
            case     '0': // Home
                     command = IDS_CURSORHOME;
                     break;
            case     'I': // Insert / Insert Toggle
                     if (alt)
                      {
                       command = IDS_INSERTCHAR; // Insert Toggle
                       alt = false;
                      }
                     else command = IDS_INSERTCHAR;
                     break;
            case     'N': //  New Line
                     command = IDS_NEWLINE;
                     break;

            case     'R': //  Reset
                     command = IDS_RESET;
                     break;
            case     'T': //  TAB
                     command = IDS_NEXTFIELD;
                     break;
            case     'x': //   PA1
                     command = IDS_PA1;
                     aid     = true;
                     break;
            case     'y': // Field Mark or PA2
                     if (shift)
                      {
                       command = IDS_FIELDMARK;
                       shift = false;
                      }
                     else
                      {
                       command = IDS_PA2;
                       aid     = true;
                      }
                     break;
            case     'z': // PA3
                     command = IDS_PA3;
                     aid     = true;
                     break;
            case     '1': // PF1
                     command = IDS_PF1;
                     aid     = true;
                     break;
            case     '2': // PF2
                     command = IDS_PF2;
                     aid     = true;
                     break;
            case     '3': //  PF3
                     command = IDS_PF3;
                     aid     = true;
                     break;
            case     '4': // PF4
                     command = IDS_PF4;
                     aid     = true;
                     break;
            case     '5': // PF5
                     command = IDS_PF5;
                     aid     = true;
                     break;
            case     '6': // PF6
                     command = IDS_PF6;
                     aid     = true;
                     break;
            case     '7': // PF7
                     command = IDS_PF7;
                     aid     = true;
                     break;
            case     '8': // PF8
                     command = IDS_PF8;
                     aid     = true;
                     break;
            case     '9': // PF9
                     command = IDS_PF9;
                     aid     = true;
                     break;
            case     'a': //  PF10
                     command = IDS_PF10;
                     aid     = true;
                     break;
            case     'b': //  PF11
                     command = IDS_PF11;
                     aid     = true;
                     break;
            case     'c': //  PF12
                     command = IDS_PF12;
                     aid     = true;
                     break;
            case     'd': //  PF13
                     command = IDS_PF13;
                     aid     = true;
                     break;
            case     'e': //  PF14
                     command = IDS_PF14;
                     aid     = true;
                     break;
            case     'f': // PF15
                     command = IDS_PF15;
                     aid     = true;
                     break;
            case     'g': // PF16
                     command = IDS_PF16;
                     aid     = true;
                     break;
            case     'h': // PF17
                     command = IDS_PF17;
                     aid     = true;
                     break;
            case     'i': // PF18
                     command = IDS_PF18;
                     aid     = true;
                     break;
            case     'j': // PF19
                     command = IDS_PF19;
                     aid     = true;
                     break;
            case     'k': // PF20
                     command = IDS_PF20;
                     aid     = true;
                     break;
            case     'l': // PF21
                     command = IDS_PF21;
                     aid     = true;
                     break;
            case     'm': // PF22
                     command = IDS_PF22;
                     aid     = true;
                     break;
            case     'n': // PF23
                     command = IDS_PF23;
                     aid     = true;
                     break;
            case     'o': // PF24
                     command = IDS_PF24;
                     aid     = true;
                     break;

            default: returnCode = WHLLINHIBITED;
                     break;
           }
          if (command)
           {
            if (pTerminal->ProcessCommand(command))
             {
              if (aid)
               {
                byStringLen -= keyStrokesLen;
                keyStrokesLen = 0;
                returnCode = WHLLPSBUSY;
               }
             }
            else returnCode = WHLLINHIBITED;
           }
          strokeState = BEGIN_STROKE;
          break;
     default:
          returnCode = WHLLSYSERROR;
          break;
    }
  }

 return returnCode;
}

string
ALFFMDIChild::QueryCertInfo(bool isClient, int queryType)
{
 string certInfo = "";
 if (pLineComm != NULL)
   return pLineComm->QueryCertificate(isClient, queryType, dateFormat);
 return certInfo;
}

void
ALFFMDIChild::DisconnectedByHost()
{
  // The session was disconnect by host, so do the session cleanup

  // Clear Flag for SSL Routines, because we are trueing disconnecting
  disconnectedByHost = false;

  SessionMessage(IDS_LINECLOSEDBYHOST);
  CloseTerminal();

  /* Register Date and Time at what connection was ended */
  TimeMessage();

  /* If connection remains active set initial state */
  SetIdleState();

  /* If Option Close Connection ... */
  if (connData->connExit)
     Parent->PostMessage(MSG_CLOSE_IMMED,0,0);
  else
   {
    /* If Option is Reconnect the session ... */
    if (connData->connReconn)
     {
	   if (numReconnTries++ < 3)
	     Connect();
	   else
	    {
        if (!IsWHLLSession())
	         pMsgs->Message(IDS_SESSCANNOTRECONNECT,IDS_ALFFSESSTITLE);
        SessionMessage(IDS_SESSCANNOTRECONNECT);
	     numReconnTries=0;
	     connStatusTitle = connInitialTitle;
	     connData->connName[0] = NULL;
	     connData->sessTitle[0] = NULL;
        connSSLStatus = " ";
	     SetWindowTitle();
	    }
	  }
    else
     {
      /* Nothing to do: Reset all connection data to initial values */
   	connStatusTitle = connInitialTitle;
      connData->connName[0] = NULL;
      connData->sessTitle[0] = NULL;
		connSSLStatus = " ";
		SetWindowTitle();
	  }
   }
}

int
ALFFMDIChild::ConnectSecurity()
{
   // The session was disconnect by host, so do the session cleanup
   if (disconnectedByHost)
    {
     DisconnectedByHost();
     return SSL_CONNECTION_ERROR;
    }

	/* Access the Application Scope */
	Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(), Tec3270App);

   // Initiate Application Security Lib
   if (theApp->GetSecurityObj())
    {
      if (!theApp->GetSecurityObj()->IsSecurityOn())
        	theApp->SetSecurityOn();
    }
   else throw ALFFSecurityException();

   char iniSection[24] = "SECURITY OPTIONS";

   /* Get the Application IniFile Pointer  */
   ALFFIniFile* iniFile = theApp->GetIniFile();

   /*******************************************************
   * Getting Secure Connection Options previous defined   *
   *******************************************************/
   bool verify_server_cert = false;
   bool verify_revoked = false;

   connectPendingForReadWrite = false;

   // Start (or Re-Start) the Secured connection
   int rc = pLineComm->SSLLineConnect(connData->securityMethod,
                                      verify_server_cert,
                                      verify_revoked,
                                      IsWHLLSession(),
                                      hllCertPath,
                                      hllCertPwd);
   if ((rc == SSL_WANT_READ) || (rc == SSL_WANT_WRITE))
      connectPendingForReadWrite = true;
   else if (rc == SSL_CONNECTION_ERROR)
    {
      bool hasError = false;
      string sslErrMsg = pLineComm->GetSSLErrors(hasError);
      int msgId;
      if (hasError)
        msgId = IDS_ALFFSSLERROR;
      else if (disconnectedByHost)
        msgId = IDS_LINECLOSEDBYHOST;
      else  msgId = IDS_LINECLOSEDBYTIMEOUT;

      if (!IsWHLLSession())
         pMsgs->StrMessage(connData->hostName,msgId,IDS_ALFFSESSTITLE);

      if (hasError)
       {
         /* Log Error on Screen and Log File if is active*/
         SessionMessage(sslErrMsg.c_str());
         SessionMessage(pLineComm->GetSSLErrorString().c_str());
         SessionMessage(IDS_LINECLOSEDBYERROR);
       }
      else if (!disconnectedByHost)
         SessionMessage(msgId);
      
      /* Inform Date and Time when connection error ocurred
         and reset all session status to Idle  */
      Disconnect(false);
    }
  if (hllCertPwd != NULL)
   {
    delete hllCertPwd;
    hllCertPwd = NULL;
   }
  return rc;
}

LRESULT
ALFFMDIChild::EvStartTLS(WPARAM, LPARAM)
{
 char iniSection[24] = "SECURITY OPTIONS";

 /* Get the Application IniFile Pointer  */
 Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
 ALFFIniFile* iniFile = theApp->GetIniFile();

 /*******************************************************
 * Getting TLS Connection Method previous defined      *
 *******************************************************/
 connData->securityMethod =
         iniFile->GetInt(iniSection,"TLSMETHOD",ALFFSSLComm::ALFFSSLV3);

 // Initiate SSL-TLS  Negotiation
 SetSSLConnectingState();

 int rc = ConnectSecurity();
 if (rc == SSL_CONNECTION_OK)
		ActivateConnection();

 return 1L;
}


LRESULT
ALFFMDIChild::DoNetInputProcess(WPARAM dataType, LPARAM messageCtrl)
// LU2 (Terminal): "messageCtrl" is the TN3270E message header, except dataType.
//                   Byte     Ctrl
//                    0        requestFlag
//                    1        responseFlag
//                   2-3       sequence number
// These values have meaning when  RESPONSE function was active, otherwise are zero.
{
 int  netLength, retCode, index;
 char err3270[12] = {"X PROGxxx "};
 int  errorId, titleId;
 int  terminalStatus;
 bool needResponse = false;
 bool keyboardLockedHere = false;

 /* If there is any timer running, reset it !! */
 ResetTimer();

 netInputQueue++;
 dataTypeQueue[netInputQueue-1] = dataType;

 if (!netInputProcessing)
  {
	netInputProcessing = true;
   index = 0;
	while (netInputQueue)
	 {
	  /*
		* Is There any data to terminal screen ?
		*/
     WPARAM dtaType = dataTypeQueue[index++];
     terminalStatus = DEVICE_READY;

	  netLength = pNetInBuf->ring_full_consecutive();
	  if (netLength)
		{
       // No error at this moment...
       errorId = 0;

		 /* Lock Terminal Keyboard During Stream receiving operation */
       if (!pTerminal->IsKeyboardLocked())
        {
         pTerminal->LockKeyboard();
         keyboardLockedHere = true;
        }

       /* Checking for TN3270E switching from NVTMode to 3270Mode and vice-versa */
       if (dtaType & 0x80)
        {
          dtaType &= 0x7F;
          if (dtaType == T3270_DATA)
           {
            p3270Buf->ClearBuf();
            pTerminal->SetMode3270(true);
           }
          else if (dtaType == NVT_DATA)
           {
            pNVTBuf->ClearBuf();
            pTerminal->SetMode3270(false);
           }
          else
           {
            if (!IsWHLLSession())
                pMsgs->StrMessage("MDIChild::DoNetInputProcess",IDS_UNEXPECTED3270ERROR,IDS_TITTELNETERR);
            SessionMessage("MDIChild::DoNetInputProcess");
            SessionMessage(IDS_UNEXPECTED3270ERROR);
           }
        }

  		 /* Update 3270 or NVT Buffer Cursor Position from Screen cursor
		  * position and do receiving operation
		  */
		 if (pTerminal->IsMode3270())
		  {
			p3270Buf->SetCursorPos(pTerminal->GetCursorPos());
			retCode = p3270Buf->DataFromNetwork(pNetInBuf);
			titleId = IDS_TIT3270ERR;
		  }
		 else
		  {
			retCode = pNVTBuf->DataFromNetwork(pNetInBuf);
			titleId = IDS_TITNVTERR;
		  }


		 /* Update Screen Cursor Position from NVT or 3270 Buffer Cursor position
        * after receiveing data from host ...
        */
		 if (pTerminal->IsMode3270() )
			 pTerminal->SetCursorPos(p3270Buf->GetCursorPos());
		 else pTerminal->SetCursorPos(pNVTBuf->GetCursorPos());


		 /* On Terminal Models Above Model 2 There is a Alternate Screen */
		 if ((retCode >= 0) && (retCode & SETALTERNATESCREEN))
		  pTerminal->SetScreen(ALTERNATESCREEN);
		 else /* Must use default screen */
		  pTerminal->SetScreen(DEFAULTSCREEN);

		 if (retCode < 0)  // Error when receiving data or Read Command or QUERY REPLY
		  {
			switch (retCode)
			 {
			  /* (INVALIDCOMMAND) Invalid 3270 Or NVT COMMAND Code */
			  /* Error Valid Exclusively For 3270 Terminal State */
			  case INVALIDCOMMAND:
				 {
				  /* Must Reject With Sense X'1003' */
				  errorId = IDS_INV3270COMMCODE;
				  strcpy(err3270,PROG401);
				  break;
				 }

			  /* (INVALIDOUT3270CMND) Invalid OutBound 3270DS COMMAND Code */
			  /* Error Valid Exclusively For 3270 Terminal State */
			  case INVALIDOUT3270CMND:
				 {
				  /* Must Reject With Sense X'1003' */
				  errorId = IDS_INVOUT3270DSCOMMCODE;
				  strcpy(err3270,PROG401);
				  break;
				 }

			  /* (INVALIDREADPARTYPE) Invalid Read Partition Type Code */
			  /* Error Valid Exclusively For 3270 Terminal State */
			  case INVALIDREADPARTYPE:
				 {
				  /* Must Reject With Sense X'1003' */
				  errorId = IDS_INVREADPARTYPE;
				  strcpy(err3270,PROG401);
				  break;
				 }

			  /* (INVALIDRPLYMODE) Invalid Reply Mode Code */
			  /* Error Valid For NVT or 3270 Terminal State */
			  case INVALIDREPLYMODE:
				 {
				  /* Must Reject With Sense X'1003' */
				  errorId = IDS_INVALIDREPLYMODE;
				  strcpy(err3270,PROG401);
				  break;
				 }

			  /* (UNSUPPORTEDSTRFIELD) Invalid Read Partition Type Code */
			  /* Error Valid Exclusively For 3270 Terminal State */
			  case UNSUPPORTEDSTRFIELD:
				 {
				  /* Must Reject With Sense X'1003' */
				  errorId = IDS_UNSUPPSTRFIELD;
				  strcpy(err3270,PROG401);
				  break;
				 }

			  /* (DATAFOLLOWEAUREAD) Invalid Data Follows READ or EAU COMMAND */
			  /* Error Valid Exclusively For 3270 Terminal State */
			  case DATAFOLLOWEAUREAD:
				 {
				  /* Must Reject With Sense X'1003' */
				  errorId = IDS_DATAFOLLOWREAD;
				  strcpy(err3270,PROG403);
				  break;
				 }

			  /* (INVALIDORDER) Invalid 3270 or NVT ORDER Code */
			  /* Error Valid For NVT or 3270 Terminal State */
			  case   INVALIDORDER:
				 {
				  /* Must Reject With Sense X'1003' */
				  if (pTerminal->IsMode3270() )
					 errorId = IDS_INV3270ORDERCODE;
				  else errorId = IDS_INVNVTORDERCODE;
				  strcpy(err3270,PROG404);
				  break;
				 }

			  /* (INVALIDBUFADDR) Invalid Buffer Address */
			  /* Error Valid Exclusively For 3270 Terminal State */
			  case INVALIDBUFADDR:
				 {
				  /* Must Reject With Sense X'1005' */
				  errorId = IDS_INVBUFFERADDR;
				  strcpy(err3270,PROG402);
				  break;
				 }

			  /* (INVALIDATTRTYPE) Invalid Attribute Type */
			  /* Error Valid Exclusively For 3270 Terminal State */
			  case INVALIDATTRTYPE:
				 {
				  /* Must Reject With Sense X'1005' */
				  errorId = IDS_INVATTRTYPE;
				  strcpy(err3270,PROG406);
				  break;
				 }

			  /* (INVALIDATTRVALUE) Invalid Attribute Value */
			  /* Error Valid Exclusively For 3270 Terminal State */
			  case INVALIDATTRVALUE:
				 {
				  /* Must Reject With Sense X'1003' */
				  errorId = IDS_INVATTRVALUE;
				  strcpy(err3270,PROG406);
				  break;
				 }

			  /* (BUFFERNOTAVAIL) 3270 Buffer Not Available */
			  /* Error Valid For NVT or 3270 Terminal State */
			  case   BUFFERNOTAVAIL:
				 {
				  if (pTerminal->IsMode3270())
					 errorId = IDS_BUFNOTAVAIL;
				  else errorId = IDS_NVTBUFNOTAVAIL;
				  break;
				 }

			  /* Read Modified Command (Read Modified Fields and Send to Host) */
			  case READMODIFIEDCOMMAND:
				 {
				  /* Valid Only For 3270 Mode */
				  if (pTerminal->IsMode3270() )
					  retCode = p3270Buf->DataToNetwork(pNetOutBuf,MODIFIED);
				  else retCode = IDS_DATANOTSENT;

				  if ( retCode == DATASENT)
					{
					 if (pTelnet->MessageSend(pLineOutBuf,pNetOutBuf))
					  {
						SendData();
						errorId = 0;
					  }
					 else errorId = IDS_DATANOTSENT ;
					}
				  else errorId = retCode;
				  break;
				 }

			  /* Read Buffer Command (Read Entire Buffer and Send to Host) */
			  case READBUFFERCOMMAND:
				 {
				  /* Valid Only For 3270 Mode */
				  if (pTerminal->IsMode3270())
					  retCode = p3270Buf->DataToNetwork(pNetOutBuf,ALLBUFFER);
				  else retCode = IDS_DATANOTSENT;

				  if ( retCode == DATASENT)
					{
					 if (pTelnet->MessageSend(pLineOutBuf,pNetOutBuf))
					  {
						SendData();
						errorId = 0;
					  }
					 else errorId = IDS_DATANOTSENT;
					}
				  else errorId = retCode;
				  break;
				 }

			  /* (QUERY REPLY ) Structured Fields */
			  case QUERYREPLY:
			  case QUERYREPLYLIST:
				 {
				  /* Must Reject With Sense X'1003' */
				  /* Valid Only For 3270 Mode */
				  if (pTerminal->IsMode3270())
					  retCode = p3270Buf->DataToNetwork(pNetOutBuf,QUERYREPLY);
				  else retCode = IDS_DATANOTSENT;
				  if ( retCode == DATASENT)
					{
					 if (pTelnet->MessageSend(pLineOutBuf,pNetOutBuf))
					  {
						SendData();
						errorId = 0;
					  }
					 else errorId = IDS_DATANOTSENT ;
					}
				  else errorId = retCode;
				  break;
				 }

			  /* Something Wrong: Unexpected Return Code */
			  default:
				 {
				  if (pTerminal->IsMode3270())
					  errorId = IDS_UNEXPECTED3270ERROR;
				  else errorId = IDS_UNEXPECTEDNVTERROR;
				  strcpy(err3270,PROG999);
				  break;
				 }

			 } // end switch

			/* Check for any error on command processing */
			if (errorId)
			 {
			  /* Shows Error Message Dialog With Error Message Selected */
			  pNetOutBuf->ring_reset();
			  pTerminal->WriteNVTLine(errorId,&err3270[1]);
			  pTerminal->LockKeyboard(&err3270[0]);
           //Need no more unlocks....
           keyboardLockedHere = false;

           if (!IsWHLLSession())
 			     pMsgs->Message(errorId,titleId);
           SessionMessage(errorId);

			  /* if Log connection option active */
			  if (connData->connLog)
				{
				 pConnLog->LogText(errorId, GetApplication()->GetInstance(), &err3270[1]);
				 if (pTerminal->IsMode3270())
				  {
					pConnLog->LogData('R',
										  p3270Buf->GetLastStream3270(),
										  p3270Buf->GetLastStreamSize(),
										  false,
										  true,
										  p3270Buf->GetTabEbcAsc());
				  }
				 else
				  {
					pConnLog->LogData('R',
										  pNVTBuf->GetLastStreamNVT(),
										  pNVTBuf->GetLastStreamSize(),
										  false,
										  false,
										  NULL);
				  }
				}
           // Set printer status on error for sending back to the server
           terminalStatus = DEVICE_NOT_READY;
			 }
         else terminalStatus = DEVICE_READY;
		  } // end (if retCode < 0)
		 else
		  {
			/* Redraw 3270 Screen on Window */
			pTerminal->PaintScreen();

         // End of input processing: restore keyboard operations if it should be done
         if (retCode & KEYBOARDRESTORE)
          {
           pTerminal->UnlockKeyboard();
           //Need no more unlocks....
           keyboardLockedHere = false;
          }

         // If this is an TN3270E session  and RESPONSE function was
         // negotiated we must sent back the device status message
         // depending upon RESPONSE_FLAG
         terminalStatus = DEVICE_READY;
		  } // (end else (if retCode ......) )

       // If session is TN3270E and RESPONSE function is active we must check
       //  for needing of an response.
       if (pTelnet->Is3270EMode())
        {
         unsigned char senseCode;
         if (retCode < 0)
           senseCode = p3270Buf->Get3270SenseCode(retCode);
         else senseCode = NO_DEVICE_ERROR;

         needResponse = pTelnet->SetNeededResponse(pNetOutBuf, messageCtrl,
                                                   terminalStatus,
                                                   senseCode);
        }

       //After receiving network input we must release keyboard only
       //if it was locked here, at the beginning of this method, and
       //there is no abnormally end on data processing....
       if (keyboardLockedHere)
        pTerminal->UnlockKeyboard();

		}  // end if ( pTelnet->....)
     else if (pTelnet->Is3270EMode())
         needResponse = pTelnet->SetNeededResponse(pNetOutBuf, messageCtrl,
                                                   DEVICE_READY,
                                                   NO_DEVICE_ERROR);
     // Sending back the response message if it is needed
     if (needResponse)
      {
       //  true == no TN3270E Header: needed hdr was set before
       //                             on SetNeededResponse method
       if (pTelnet->MessageSend(pLineOutBuf,pNetOutBuf, true ))
           SendData();
       else
        {
         if (!IsWHLLSession())
             pMsgs->Message(IDS_DATANOTSENT,titleId);
         SessionMessage(IDS_DATANOTSENT);
        }
      }

	  netInputQueue--;

	 } // end while (....)

	netInputProcessing = false;

  }  // end if (!netInput...)

 pTelnet->ResetEor();

 /***************************************************************************
 * Script File Processing - 2st Stage: From command after CONNECT statement *
 *                                     until end of Script file.            *
 ***************************************************************************/
 if (connData->scriptOn && (!netInputProcessing)
     && (retCode > 0) && (!scriptProcessing)
     && (!pTerminal->IsKeyboardLocked()) )
  {
   scriptProcessing = true;
#ifdef TRACESCRIPT
   pTerminal->GetCursorPos();
#endif
   if ( (pScript != NULL) && (pScript->IsOpened()) )
    {
     int rc = OPERATIONOK;
     ScriptCommand comando;
     while ( rc == OPERATIONOK)
      {
       /*
        * Processar script até o fim do arquivo...  (2a. etapa)
        */
       rc = pScript->GetNextCommand(&comando);
       if (rc == OPERATIONOK)
        {
         rc = ProcessScript(&comando);
         /* If Return code is MUSTSENDDATA, we'll wait for
          * an new screen reception, before continuing script
          * file processing...
          */
         if ( (rc != OPERATIONOK) && (rc != ENDOFFILE)
          && (rc != MUSTSENDDATA) && (rc != LOOKFORNOTFOUND) )
          {
           scriptProcessing = false;
           delete pScript;
           pScript = NULL;
           SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
           Disconnect(true);
           return 1L;
          }
         else if (rc == LOOKFORNOTFOUND)
          {
           if (!pScript->SetNextCommandSame())
            {
             scriptProcessing = false;
             char msgLook[64];
             strcpy(msgLook,"LOOKFOR/ESPERARPOR -> ");
             strcat(msgLook,comando.parm[0].c_str());
             if (!IsWHLLSession())
               pMsgs->StrMessage(msgLook,IDS_ALFFSCRIPTTXTNOTFND,IDS_ALFFSESSSCPTTITLE);
             SessionMessage(IDS_ALFFSCRIPTTXTNOTFND);
             delete pScript;
             pScript = NULL;
             SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
             Disconnect(true);
             return 1L;
            }
          }
         else if (rc == ENDOFFILE)
          {
           delete pScript;
           pScript = NULL;
          }
        }
       else if (rc == INVALIDSCRIPTTAG)
        {
         scriptProcessing = false;
         if (!IsWHLLSession())
            pMsgs->Message(IDS_ALFFSCRIPTINVPARM,IDS_ALFFSESSSCPTTITLE);
         SessionMessage(IDS_ALFFSCRIPTINVPARM);
         delete pScript;
         pScript = NULL;
         SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
         Disconnect(true);
         return 1L;
        }
       else if (rc == ENDOFFILE)
        {
#ifdef DEBUG32
         MessageBox("Script file ended","Tec3270 Debug",MB_OK);
#endif
         delete pScript;
         pScript = NULL;
        }
       else if (rc == INVALIDPARM)
        {
         scriptProcessing = false;
         char comDescription[32];
         strcpy(comDescription,pScript->GetCommandDescription(&comando).c_str());
         if (!IsWHLLSession())
            pMsgs->StrMessage(comDescription,IDS_ALFFSCRIPTINVPARM,IDS_ALFFSESSSCPTTITLE);
         SessionMessage(IDS_ALFFSCRIPTINVPARM);
         delete pScript;
         pScript = NULL;
         SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
         Disconnect(true);
         return 1L;
        }
       else
        {
         scriptProcessing = false;
         if (!IsWHLLSession())
             pMsgs->StrMessage("GetNextCommand: Invalid return code",IDS_ALFFSESSSCPTTITLE,MB_OK);
         SessionMessage("GetNextCommand: Invalid return code");
         delete pScript;
         pScript = NULL;
         SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
         Disconnect(true);
         return 1L;
        }
      } // end while
    } // if (pScript != NULL ....
   scriptProcessing = false;
  } // if (connData->scriptOn .....

 return 1L;
}


LRESULT
ALFFMDIChild::DoNetOutputProcess(WPARAM command, LPARAM)
{
#ifdef ALFFDebug
 char destString[32];
 GetApplication()->LoadString(command, destString, 31);
 char msgString[256];
 sprintf(msgString,"Session%i : %s Key Pressed",connNumber,destString);
 MessageBox(msgString,"Tec3270 DEBUG", MB_OK | MB_ICONEXCLAMATION);
#endif
 int retCode;
 int titleId;

 /* If there is any timer running, reset it !! */
 ResetTimer(true); //Force Timer To Be Set

 int readType;
 if (pTerminal->IsMode3270())
  {
	/* Check For 3270 Special Commands */
	if ( (command == IDS_CLEAR) || (command == IDS_PA1)
	  ||(command == IDS_PA2  ) || (command == IDS_PA3)
	  ||(command == IDS_ATTN ) || (command == IDS_SYSREQ) )
	 {
	  if (command == IDS_ATTN)
		{
		 pTelnet->SendControl(pLineOutBuf,IDS_ATTN);
		 SendData();
		 return 1L;
		}
	  else if (command == IDS_SYSREQ)
		{
		 pTelnet->SendControl(pLineOutBuf,IP);
		 SendData();
		 pTelnet->SendControl(pLineOutBuf,SYNC);
		 SendData(URGENT);
		 pTelnet->SendControl(pLineOutBuf,IDS_SYSREQ);
		 SendData();
		 return 1L;
		}
	  else 	readType = SHORTREAD;
	 }
	else readType = MODIFIED;

	/* Send Data To NetWork Output Buffer */
	titleId = IDS_TIT3270ERR;
	retCode = p3270Buf->DataToNetwork(pNetOutBuf,readType);
  }
 else
  {
	/* Check For NVT Special Commands */
	if (command == IDS_ATTN)
	 {
	  pTelnet->SendControl(pLineOutBuf,IDS_ATTN);
	  SendData();
	  return 1L;
	 }

	/* Send Data To NetWork Output Buffer */
	titleId = IDS_TITNVTERR;
	retCode = pNVTBuf->DataToNetwork(pNetOutBuf,MODIFIED);
  }

 if (retCode == DATASENT)
  {
	  if (pTelnet->MessageSend(pLineOutBuf,pNetOutBuf))
      {
		 SendData();
       SetWHLLPSChanged(PSNOTCHANGED);
       SetWaitingHostResponse(true);
      }
	  else
      {
       if (!IsWHLLSession())
         pMsgs->Message(IDS_DATANOTSENT,titleId);
       SessionMessage(IDS_DATANOTSENT);
      }
  }
 else
  {
   if (!IsWHLLSession())
     pMsgs->Message(IDS_DATANOTSENT,titleId);
   SessionMessage(IDS_DATANOTSENT);
  }
 return 1L;
}

LRESULT
ALFFMDIChild::DoNetOutputEcho(WPARAM key, LPARAM)
{
 /*
  * This Method is used only by NVT sessions with Echo
  */
 char byte = LOBYTE(key);
 int titleId = IDS_TITNVTERR;

 /* If there is any timer running, reset it !! */
 ResetTimer();

 if (pTelnet->SendEcho(pLineOutBuf,&byte))
	 SendData();
 else
  {
   if (!IsWHLLSession())
   	pMsgs->Message(IDS_DATANOTSENT,titleId);
   SessionMessage(IDS_DATANOTSENT);
  }

 return 1L;
}


void
ALFFMDIChild::CmTraceSessionEnable(TCommandEnabler &ce)
{
 ce.Enable(!MDIParent->IsMonitoring()
           && !pTerminal->IsLogOn());
}

void
ALFFMDIChild::CmTraceSession()
{
  int rcOpenTrace;
  if (!traceON)
	{
	 pTrcFile = new ALFFLogFile(this);
	 rcOpenTrace = pTrcFile->OpenTrace();
	 if (rcOpenTrace == SUCCESSFULOPEN)
	  {
		string wFileName(pTrcFile->GetFileName());
		char traceText[STRINGMSGLEN];
		traceText[0] = NULL;
		pMsgs->LoadString(IDS_ALFFTRACETIT,traceText,STRINGMSGLEN-1);
		connTraceTitle = traceText + wFileName + ")";
		SetWindowTitle();
		traceON = true;
		pTerminal->SetTraceOn(traceON);
		/*
		 * Setup Trace File Title For Identifying What IS Going On
		 */
		char trcHeader[STRINGMSGLEN];
		char msgHeader[STRINGMSGLEN];
		pMsgs->LoadString(IDS_ALFFSESSTRACEHDR, trcHeader,STRINGMSGLEN);
		sprintf(msgHeader,trcHeader,connNumber);
		pTrcFile->SetLogTitle(msgHeader, dateFormat);
	  }
	  else if (rcOpenTrace == INVALIDOPEN)
			  pMsgs->Message(IDS_ALFFTRACEOPENERR,IDS_ALFFSESSTITLE);
	  else if (rcOpenTrace == NOFILENAME)
			  pMsgs->Message(IDS_ALFFTRACEFILENAMERR,IDS_ALFFSESSTITLE);
	}
	else
	 {
	  pTrcFile->LogText(IDS_ALFFSESSTRACEEND, GetApplication()->GetInstance());
	  delete pTrcFile;
	  pTrcFile = 0;
	  traceON = false;
	  pTerminal->SetTraceOn(traceON);
	  connTraceTitle = "";
	  SetWindowTitle();
	 }

  /* Update Trace Submenu */
  pTerminal->SetMenuTraceStat();
}

void
ALFFMDIChild::CmToolsLogScreenEnable(TCommandEnabler &ce)
{
 ce.Enable( pTerminal->IsConnected()
			&& pTerminal->IsMode3270()
			&& !MDIParent->IsMonitoring());
}

void
ALFFMDIChild::SetLogScreenMenu()
{
 HMENU  mainMenu = GetApplication()->GetMainWindow()->GetMenu();
 TMenu* theMenu = new TMenu(mainMenu);
 char* menuMsg = new char[STRINGMSGLEN];
 int menuFlag;
 if (theMenu)
  {
	if (GetScrLogOn())
	 {
	  pMsgs->LoadString(IDS_ALFFLOGON,menuMsg,STRINGMSGLEN);
	  menuFlag = MF_BYCOMMAND | MF_CHECKED;
	 }
	else
	 {
	  pMsgs->LoadString(IDS_ALFFLOGOFF,menuMsg,STRINGMSGLEN);
	  menuFlag = MF_BYCOMMAND | MF_UNCHECKED;
	 }
	theMenu->ModifyMenu(CM_TOOLSLOGSCREEN, MF_BYCOMMAND,CM_TOOLSLOGSCREEN,menuMsg);
	theMenu->CheckMenuItem(CM_TOOLSLOGSCREEN,menuFlag);
	GetApplication()->GetMainWindow()->DrawMenuBar();
  }
 delete theMenu;
 delete [] menuMsg;
}

void
ALFFMDIChild::CmToolsLogScreen()
{
 if (!GetScrLogOn())
  {
	pTerminal->SetLogOn(true);
	pTerminal->ClearScr(connData->scrBkgdColor);
	pTerminal->LockKeyboard();
	pTerminal->PaintScreen();
	SetScrLogOn(true);
  }
 else
  {
	pTerminal->SetLogOn(false);
	pTerminal->ClearScr(connData->scr3270BkgdColor);
	pTerminal->PaintScreen();
	pTerminal->UnlockKeyboard();
	SetScrLogOn(false);
  }
 SetLogScreenMenu();
}

void
ALFFMDIChild::CmSessionEnable(TCommandEnabler &ce)
{
 ce.Enable(!pTerminal->IsKeyboardLocked()
			&& pTerminal->IsConnected()
			&& !MDIParent->IsMonitoring());
}

void
ALFFMDIChild::CmChooseCursor()
{
 pTerminal->ChangeCursor();
}

void
ALFFMDIChild::CmChangeSession()
{
 /* Turn Timer Functions Off For Having no Interferences */
 if (timerOn)
  {
	timerOn = false;
	KillTimer(connNumber);
  }

 /* Call Session Configurator Dialog For Doing Any Modifications Desired */
 ALFFConnectDlg(this,connData,IDD_ALFFCONNECT,SESSCHANGE).Execute();

 /* Restore Timer Functions If User Set Any Of Them */
 if ((connData->actOption != NO_TIMER)&&(connData->intvTime))
  {
	timerType = connData->actOption;
	timerOn = true;
	ResetTimer(true);  //Force Timer To Be Set
  }
}

/* Security menu command handlers  */
void
ALFFMDIChild::CmShowCertificateEnable(TCommandEnabler &ce)
{
 if (IsSSLConnected())
   ce.Enable(true);
 else ce.Enable(false);
}

void
ALFFMDIChild::ShowCertificate()
{
 if (IsSSLConnected())
      CmShowCertificate();
}

void
ALFFMDIChild::CmShowCertificate()
{
 pLineComm->ShowSSLCertificate();
}


void
ALFFMDIChild::CmShowSecurityInfo()
{
  pMsgs->StrMessage(pLineComm->GetSecurityInfo().c_str(),0,IDS_ALFFSESSTITLE);
}


void
ALFFMDIChild::CmConnectEnable(TCommandEnabler &ce)
{
 if (pTerminal->IsConnected() || IsConnecting()
   || IsSSLConnecting()
	|| MDIParent->IsMonitoring())
	ce.Enable(false);
  else
	ce.Enable(true);
}

void
ALFFMDIChild::CmConnect()
{
	if(nLineState == nIdle)
	 {
	  //--------------------------TRACE---------------------------------
	  #ifdef ALFFTrace
		 MessageBox("Starting Session connection dialog...","Tec3270 Trace Info", MB_OK);
	  #endif
	  //--------------------------TRACE---------------------------------
	  //
     ALFFConnectDlg* connDlg = new ALFFConnectDlg(this, connData, IDD_ALFFCONNECT);
     connDlg->Execute();
     int connDlgResponse = connDlg->GetButtonPressed();
     delete connDlg;
	  if (connDlgResponse == IDOK)
		 Connect();
	  else
      {
       connData->connName[0] = NULL;
       connData->sessTitle[0] = NULL;
      }
	 }
}

#ifdef TRACESCRIPT
/*   --------------- DEBUG ------------------------------------------  */
void
ALFFMDIChild::TraceScript(ScriptCommand* comando)
{
 char msgString[128];
 char command[64];
 switch (comando->commandId)
  {
    case             IF: strcpy(command,"IF");
                         break;
	 case        CONNECT: strcpy(command,"CONNECT");
                         break;
    case CONNECT_TEC3270: strcpy(command,"CONNECT_TEC3270");
                          break;
    case    CONNECTPORT: strcpy(command,"CONNECTPORT");
                         break;
    case       TERMINAL: strcpy(command,"TERMINAL");
                         break;
    case          TITLE: strcpy(command,"TITLE");
                         break;
    case           PORT: strcpy(command,"PORT");
                         break;
    case      GOTOLABEL: strcpy(command,"GOTOLABEL");
                         break;
    case     MOVECURSOR: strcpy(command,"MOVECURSOR");
                         break;
    case           TYPE: strcpy(command,"TYPE");
                         break;
    case            KEY: strcpy(command,"KEY");
                         break;
    case       PASSWORD: strcpy(command,"PASSWORD");
                         break;
    case        LOOKFOR: strcpy(command,"LOOKFOR");
                         break;
    case       LOOKLIST: strcpy(command,"LOOKLIST");
                         break;
    case          LABEL: strcpy(command,"LABEL");
                         break;
    case         PROMPT: strcpy(command,"PROMPT");
                         break;
    case           EXIT: strcpy(command,"EXIT");
                         break;
                default: strcpy(command,"UNKNOW");
                         break;
  }


 sprintf(msgString,"Command: %s   Parm1 = %s, Parm2 = %s,"
 			"Parm3 = %s, Parm4 = %s", command,
         comando->parm[0].c_str(), comando->parm[1].c_str(),
         comando->parm[2].c_str(), comando->parm[3].c_str());

 MessageBox(msgString,"Tec3270 DEBUG",MB_OK);
}
/*   --------------- DEBUG -------------------------------------------  */
#endif

void
ALFFMDIChild::WriteScriptText(char* text)
{
  /* Write script text on terminal screen, beginning at
   current cursor position           */
  if (pTerminal->IsMode3270())
    p3270Buf->DataFromKeyboard(text,strlen(text), false); // Not in InsertMode
  else pNVTBuf->DataFromKeyboard(text,strlen(text), false); // Not in InsertMode

  /* Update Screen Cursor Position from NVT
     or 3270 Buffer Cursor position */
  if (pTerminal->IsMode3270())
    pTerminal->SetCursorPos(p3270Buf->GetCursorPos());
  else pTerminal->SetCursorPos(pNVTBuf->GetCursorPos());
  /* Update Terminal Screen */
  pTerminal->PaintScreen();
}

int
ALFFMDIChild::ProcessScript(ScriptCommand* comando)
{
 /* Script file command processing */
 ALFFConnectDlg*  connDlg;
 ALFFInputDialog* inputDlg;
 ScriptCommand com;
 int i,rc,command, length = 0;
 string tempStr;
 bool found;
 TPoint newCursorPos;
 char temp[SCRIPTLINESIZE];
 char desComando[64];
 char parm0[64];
 char parm1[64];
 char parm2[64];
 char parm3[64];
 strcpy(desComando,pScript->GetCommandDescription(comando).c_str());
 strcpy(parm0,comando->parm[0].c_str());
 strcpy(parm1,comando->parm[1].c_str());
 strcpy(parm2,comando->parm[2].c_str());
 strcpy(parm3,comando->parm[3].c_str());

#ifdef TRACESCRIPT
 char msgScript[128];
 strcpy(msgScript,"Script: ");
 strcat(msgScript,desComando);
 strcat(msgScript," - Parameter: ");
 strcat(msgScript,parm0);
 strcat(msgScript,", "); 
 strcat(msgScript,parm1);
 SessionMessage(msgScript);
#endif
 switch (comando->commandId)
  {
    case             IF: // Command not yet developed //
                         break;
	 case        CONNECT: /* Connect to specified HOST (WWW name or  IP Addr.) */
                         if (pScript->GetState() == ALFFScript::BEFORECONNECT)
                          {
                           strcpy(connData->hostName,parm0);
                           pScript->SetState(ALFFScript::AFTERCONNECT);
                           return CONNECTOK;
                          }
                         else
                          {
                           if (!IsWHLLSession())
                               pMsgs->Message(IDS_ALFFSCRIPTDUPCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(IDS_ALFFSCRIPTDUPCONN);
                           return INVALIDSCRIPTTAG;
                          }
    case CONNECT_TEC3270: /* Connect using already defined TEC3270 session parameters
                            If there is any script file defined in this session it will
                            be ignored. */
                         if (pScript->GetState() == ALFFScript::BEFORECONNECT)
                          {
                           if (!strcmp(parm0,"*"))
                            {
                             /* Should connect with this connection parms */
                             pScript->SetState(ALFFScript::AFTERCONNECT);
                             return CONNECTOK;
                            }
	                        else
                            {
                             /* Load specified connection */
                             connDlg = new ALFFConnectDlg(this, connData, IDD_ALFFCONNECT);
	                          if (!connDlg->LoadConnection(parm0))
                              {
                               if (!IsWHLLSession())
                                   pMsgs->Message(IDS_ALFFSESSNAMEERROR,IDS_ALFFSESSSCPTTITLE);
                               SessionMessage(IDS_ALFFSESSNAMEERROR);
                               delete connDlg;
                               return INVALIDPARM;
                              }
                             else delete connDlg;
                             connData->scriptOn = true;
                             pScript->SetState(ALFFScript::AFTERCONNECT);
                             return CONNECTOK;
                            }
                          }
                         else
                          {
                           if (!IsWHLLSession())
                              pMsgs->Message(IDS_ALFFSCRIPTDUPCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(IDS_ALFFSCRIPTDUPCONN);
                           return INVALIDSCRIPTTAG;
                          }
    case    CONNECTPORT: /* Connect to specified Host and Port */
                         if (pScript->GetState() == ALFFScript::BEFORECONNECT)
                          {
                           strcpy(connData->hostName,parm0);
    							   connData->portNumber = atoi(parm1);
                           pScript->SetState(ALFFScript::AFTERCONNECT);
                           return CONNECTOK;
                          }
                         else
                           {
                            if (!IsWHLLSession())
                                 pMsgs->Message(IDS_ALFFSCRIPTDUPCONN,IDS_ALFFSESSSCPTTITLE);
                            SessionMessage(IDS_ALFFSCRIPTDUPCONN);
                            return INVALIDSCRIPTTAG;
                           }
    case       TERMINAL: /* Load Connection Terminal Type */
    							 if (pScript->GetState() == ALFFScript::BEFORECONNECT)
                          {
                           length = 1;
                           connData->termType = -1;
                           for (i = IDS_ALFFTERMBASE+1; length; i++)
	                         {
	                          length = pMsgs->LoadString(i,temp,SESSNAMELEN-1);
                             if (length)
                              {
                               string tempStr = temp;
                               tempStr = tempStr.strip(string::Both,' ');
                               if (!comando->parm[0].compare(tempStr))
                                {
                                 connData->termType = i-IDS_ALFFTERMBASE-1;
                                 length = 0;
                                }
                              }
	                         }
                            if (connData->termType == -1)
                             {
                              if (!IsWHLLSession())
                                 pMsgs->Message(IDS_ALFFSCRIPTTERMERROR,IDS_ALFFSESSSCPTTITLE);
                              SessionMessage(IDS_ALFFSCRIPTTERMERROR);
                              connData->termType = 0;
                              pScript->Close();
                              delete pScript;
                              pScript = NULL;
                              return INVALIDPARM;
                             }
                          }
                         else
                          {
                           if (!IsWHLLSession())
                              pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVAFTCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVAFTCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;
    case          TITLE: /* Session window title */
                         if (pScript->GetState() == ALFFScript::BEFORECONNECT)
                           strcpy(connData->sessTitle,parm0);
                         else
                          {
                           if (!IsWHLLSession())
                             pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVAFTCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVAFTCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;
    case           PORT: /* TELNET Port where session shoud be connected */
                         if (pScript->GetState() == ALFFScript::BEFORECONNECT)
                            connData->portNumber = atoi(comando->parm[0].c_str());
                         else
                          {
                           if (!IsWHLLSession())
                           	pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVAFTCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVAFTCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;
    case      GOTOLABEL: /* Alter command flow to proceed to other Script File part */
                         found = false;
                         while (!found)
                          {
                           rc = pScript->GetNextCommand(&com);
                           if (rc == OPERATIONOK)
                            {
                             com.parm[0] = com.parm[0].strip(string::Both,' ');
                             if ((com.commandId == LABEL) &&
                                 !com.parm[0].compare(comando->parm[0]) )
                               {
                                 /* Label solicitado foi encontrado */
                                 found = true;
                                 break;
                               }
                             }
                           else if (rc == ENDOFFILE)
                             {
                              if (!IsWHLLSession())
                                 pMsgs->StrMessage(parm0,IDS_ALFFSCRIPTLABNOTFND,IDS_ALFFSESSSCPTTITLE);
                              SessionMessage(parm0);
                              SessionMessage(IDS_ALFFSCRIPTLABNOTFND);
                              return ENDOFFILE;
                             }
                           else if (rc == INVALIDPARM)
                             {
                              if (!IsWHLLSession())
                                 pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVPARM,IDS_ALFFSESSSCPTTITLE);
                              SessionMessage(desComando);
                              SessionMessage(IDS_ALFFSCRIPTINVPARM);
                              return INVALIDPARM;
                             }
                          }
                         break;
    case     MOVECURSOR: /* Move cursor to informed line and column */
                         if (pScript->GetState() == ALFFScript::AFTERCONNECT)
                          {
                           newCursorPos.x = atoi(parm1)-1; // Linha
                           newCursorPos.y = atoi(parm0)-1; // Coluna
                           pTerminal->SetCursorPos(newCursorPos);
                           pTerminal->UpdateCursor();
                          }
                         else
                          {
                           if (!IsWHLLSession())
                             pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVBEFCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVBEFCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;
    case           TYPE:
                         if (pScript->GetState() == ALFFScript::AFTERCONNECT)
                          {
#ifdef TRACESCRIPT
     pTerminal->GetCursorPos();
#endif
                           WriteScriptText(parm0);
                          }
                         else
                          {
                           if (!IsWHLLSession())
                              pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVBEFCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVBEFCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;
    case            KEY:
                         if (pScript->GetState() == ALFFScript::AFTERCONNECT)
                          {
#ifdef TRACESCRIPT
     pTerminal->GetCursorPos();
#endif
                           tempStr = comando->parm[0];
                           tempStr.to_upper();
                           strcpy(parm0,tempStr.c_str());
                           command = pScript->GetKeyCommand(parm0);
                           if ((command != INVALIDPARM) &&
                                pTerminal->ProcessCommand(command,true))  // ignore kblocked
                            {
                              if (command != IDS_NEXTFIELD)
                                 return MUSTSENDDATA;
                            }
                           else
                            {
                             if (!IsWHLLSession())
                                pMsgs->StrMessage(desComando,
                                               IDS_ALFFSCRIPTINVPARM,IDS_ALFFSESSSCPTTITLE);
                             SessionMessage(desComando);
                             SessionMessage(IDS_ALFFSCRIPTINVPARM);
                             return INVALIDPARM;
                            }
                          }
                         else
                          {
                           if (!IsWHLLSession())
                           			pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVBEFCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVBEFCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;
    case       PASSWORD: /* Get password and write it on screen buffer */
                         if (pScript->GetState() == ALFFScript::AFTERCONNECT)
                          {
                           strcpy(temp,"");
                           inputDlg = new ALFFInputDialog(this,"Tec3270 Script - PASSWORD/SENHA",
                                                       parm0,temp,SCRIPTLINESIZE,true,'#'); //true=>Password
                           rc = inputDlg->Execute();
                           delete inputDlg;

								   if(rc == IDOK)
                               WriteScriptText(temp);
                           else return ENDOFFILE;
                          }
                         else
                          {
                           if (!IsWHLLSession())
                             pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVBEFCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVBEFCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;
    case        LOOKFOR:
                         if (pScript->GetState() == ALFFScript::AFTERCONNECT)
                          {
#ifdef TRACESCRIPT
     pTerminal->GetCursorPos();
#endif
                            found = false;
                            if (pTerminal->IsMode3270())
                               // Do not match case, whole word and search down
                               found = p3270Buf->Search(0, parm0, false,false,false,false) >= 0;
		                      else
                               found = pNVTBuf->Search(0, parm0, false,false,false,false) >= 0;
                            if (!found)
                              return LOOKFORNOTFOUND;
                          }
                         else
                          {
                           if (!IsWHLLSession())
                           	pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVBEFCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVBEFCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;
    case       LOOKLIST:
                         if (pScript->GetState() == ALFFScript::AFTERCONNECT)
                          {
                           found = false;
                           i = 0;
                           strcpy(temp,parm0);
                           while (!found)
                            {
                             if (pTerminal->IsMode3270())
                               // Do not match case, whole word and search down
                               found = p3270Buf->Search(0, temp, false,false,false,false) >= 0;
		                       else
                               found = pNVTBuf->Search(0, temp, false,false,false,false) >= 0;
                             if (!found)
                              {
                               i += 1;
                               if (i > 1)
                                 break;
                               else strcpy(temp,parm2);
                              }
                            }
                           if (found)
                            {
                             found = false;
                             if (i == 0)
                               tempStr =  parm1;
                             else tempStr = parm3;
                             while (!found)
                              {
                               rc = pScript->GetNextCommand(&com);
                               if (rc == OPERATIONOK)
                               {
                                com.parm[0] = com.parm[0].strip(string::Both,' ');
                                if ((com.commandId == LABEL) &&
                                   !com.parm[0].compare(tempStr))
                                 {
                                  /* Label was found */
                                  found = true;
                                  break;
                                 }
                               }
                              else if (rc == ENDOFFILE)
                               {
                                if (!IsWHLLSession())
                                   pMsgs->StrMessage(parm0,IDS_ALFFSCRIPTLABNOTFND,IDS_ALFFSESSSCPTTITLE);
                                SessionMessage(parm0);
                                SessionMessage(IDS_ALFFSCRIPTLABNOTFND);
                                return ENDOFFILE;
                               }
                              else if (rc == INVALIDPARM)
                               {
                                if (!IsWHLLSession())
                                		pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVPARM,IDS_ALFFSESSSCPTTITLE);
                                SessionMessage(parm0);
                                SessionMessage(IDS_ALFFSCRIPTINVPARM);
                                return INVALIDPARM;
                               }
                              }
                            }
                           else return LOOKFORNOTFOUND;
                          }
                         else
                          {
                           if (!IsWHLLSession())
                           		pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVBEFCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVBEFCONN);
                           return INVALIDSCRIPTTAG;
                          }

                         break;
    case          LABEL: /* Paragraph begin on Script file - do nothing */
                         break;
    case         PROMPT:
                         if (pScript->GetState() == ALFFScript::AFTERCONNECT)
                          {
                           strcpy(temp,"");
                           inputDlg = new ALFFInputDialog(this,"Tec3270 Script - PROMPT",
                                                       parm0,temp,SCRIPTLINESIZE);
                           rc = inputDlg->Execute();
                           delete inputDlg;

                           if (rc == IDOK)
                           	WriteScriptText(temp);
                           else return ENDOFFILE;
                          }
                         else
                          {
                           if (!IsWHLLSession())
                           		pMsgs->StrMessage(desComando,IDS_ALFFSCRIPTINVBEFCONN,IDS_ALFFSESSSCPTTITLE);
                           SessionMessage(desComando);
                           SessionMessage(IDS_ALFFSCRIPTINVBEFCONN);
                           return INVALIDSCRIPTTAG;
                          }
                         break;

    case        MESSAGE:
                         if (strlen(parm1))
                          {
                           if (pMsgs->StrMessage(parm0,0,IDS_ALFFSESSSCPTTITLE,true) == IDCANCEL)
                             return ENDOFFILE;
                          }
                         else pMsgs->StrMessage(parm0,0,IDS_ALFFSESSSCPTTITLE);
                         break;

    case           EXIT: return ENDOFFILE;

                default: if (!IsWHLLSession())
                           pMsgs->Message(IDS_ALFFSCRIPTUNKNOWCOMM,IDS_ALFFSESSSCPTTITLE);
                         SessionMessage(IDS_ALFFSCRIPTUNKNOWCOMM);
                         return INVALIDSCRIPTTAG;
  }
 return OPERATIONOK;
}

bool
ALFFMDIChild::Connect(char* sessName, bool isWHLL, char* certPath, char* certPwd)
{
	char text[STRINGMSGLEN];
	char portNumber[10];

   // Set Session type (Normal or WinHLLApi started)
   SetWHLLSession(isWHLL);
   if ((IsWHLLSession()) && (certPath != NULL) && (certPwd != NULL) )
    {
     // Store certPath if it was supplied
     if (hllCertPath != NULL)
       delete [] hllCertPath;
     hllCertPath = new char[strlen(certPath)+1];
     strcpy (hllCertPath, certPath);

     // Store certPwd too
     if (hllCertPwd != NULL)
       delete [] hllCertPwd;
     hllCertPwd = new char[strlen(certPwd)+1];
     strcpy (hllCertPwd, certPwd);
    }

#ifdef DEBUG32
	MessageBox("Connecting...","Tec3270 Debug",MB_OK);
#endif
	/* If sessName is Not NULL it should be Loaded from ini File */
	if (sessName)
	 {
#ifdef DEBUG32
	MessageBox("Connection: LoadConnection ...","Tec3270 Debug",MB_OK);
#endif
//	  ALFFConnectDlg(this, connData, IDD_ALFFCONNECT).LoadConnection(sessName);
	  ALFFConnectDlg* connDlg;
	  connDlg = new ALFFConnectDlg(this, connData, IDD_ALFFCONNECT);
	  if ( (!connDlg->LoadConnection(sessName))
        ||(!strcmp(connData->hostName,"Enter HostName")) )
      {
       // Show user that this session is invalid
       if (!IsWHLLSession())
          pMsgs->StrMessage(sessName,IDS_ALFFSESSNAMEERROR,IDS_ALFFSESSTITLE);

       // Register this error on screen too !
       SessionMessage(sessName);
       SessionMessage(IDS_ALFFSESSNAMEERROR);

       delete connDlg;
       Disconnect(true);
       return false;
      }
     else delete connDlg;

	  strcpy(connData->connName,sessName);
	  autoConnect = true;
	 }
	 else autoConnect = false;

	// If Connection Log File then create it
	if ((connData->connLog) || IsWHLLSession())
	 {
	  if (pConnLog != NULL)
      {
     	 pConnLog->LogText(IDS_ALFFSESSTRCLOGEND, GetApplication()->GetInstance());
       delete pConnLog;
       pConnLog = NULL;
      }
	  char logName[MAXPATH];
	  wsprintf(logName,"Sess%03i_%s.log",connNumber,connData->connName);
	  pConnLog = new ALFFLogFile(this);
	  int rcOpenLog = pConnLog->OpenLog(logName);
	  if (rcOpenLog == SUCCESSFULOPEN)
	   {
	    char logHeader[STRINGMSGLEN];
		 char msgHeader[STRINGMSGLEN];
		 pMsgs->LoadString(IDS_ALFFSESSLOGHDR, logHeader,STRINGMSGLEN);
		 wsprintf(msgHeader,logHeader,connNumber);
		 pConnLog->SetLogTitle(msgHeader, dateFormat);
	   }
	  else if (rcOpenLog == INVALIDOPEN)
      {
       if (!IsWHLLSession())
	  	       pMsgs->Message(IDS_ALFFSESSLOGOPENERR,IDS_ALFFSESSTITLE);
       SessionMessage(IDS_ALFFSESSLOGOPENERR);
       delete pConnLog;
       pConnLog = NULL;
      }
	  else if (rcOpenLog == NOFILENAME)
      {
       if (!IsWHLLSession())
	  	     pMsgs->Message(IDS_ALFFSESSLOGFILENAMERR,IDS_ALFFSESSTITLE);
       SessionMessage(IDS_ALFFSESSLOGFILENAMERR);
       delete pConnLog;
       pConnLog = NULL;
      }
	 }

#ifdef DEBUG32
	MessageBox("Connection: SetConnectingState...","Tec3270 Debug",MB_OK);
#endif

	// Set Connection State:
	SetConnectingState();

	// Assume no timer yet (it will be verified some steps ahead)
	timerType = NO_TIMER;

   /*************************************************************************
   * Script File Processing - 1st Stage: From begin until CONNECT statement *
   **************************************************************************/
   if (connData->scriptOn)
    {
      if (!pScript)
        pScript = new ALFFScript(this);
      else
       {
        delete pScript;
        pScript = new ALFFScript(this);
       }
      if (pScript->Open(connData->scriptFile) == SUCCESSFULOPEN)
       {
         int rc = OPERATIONOK;
         ScriptCommand comando;
         while ( rc == OPERATIONOK)
          {
           /*
            * Process script till CONNECT command...(1st. part)
            * Rest of commands will be processed after session is successfully
            *  connected to host, because they depend upon screen receiving ....
            */
           rc = pScript->GetNextCommand(&comando);
           if (rc == OPERATIONOK)
            {
             /*
              * Return code may be CONNECTOK and in this case process
              * will be finished at this point and resumed after connection
              * was successfuly done
              */
             rc = ProcessScript(&comando);
             if ((rc != OPERATIONOK) && (rc != CONNECTOK) )
              {
               delete pScript;
               pScript = NULL;
               SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
               Disconnect(true);
               return false;
              }
            }
           else if (rc == INVALIDSCRIPTTAG)
            {
         	 if (!IsWHLLSession())
                pMsgs->Message(IDS_ALFFSCRIPTINVPARM,IDS_ALFFSESSSCPTTITLE);
             SessionMessage(IDS_ALFFSCRIPTINVPARM);
             delete pScript;
             pScript = NULL;
             SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
             Disconnect(true);
             return false;
            }
           else if (rc == ENDOFFILE)
            {
#ifdef DEBUG32
             MessageBox("Script file ended","Tec3270 Debug",MB_OK);
#endif
             delete pScript;
             pScript = NULL;
            }
           else if (rc == INVALIDPARM)
            {
             char comDescription[32];
             strcpy(comDescription,pScript->GetCommandDescription(&comando).c_str());

             if (!IsWHLLSession())
                pMsgs->StrMessage(comDescription,IDS_ALFFSCRIPTINVPARM,IDS_ALFFSESSSCPTTITLE);
             SessionMessage(comDescription);
             SessionMessage(IDS_ALFFSCRIPTINVPARM);

             delete pScript;
             pScript = NULL;
             SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
             Disconnect(true);
             return false;
            }
           else
            {
             if (!IsWHLLSession())
                pMsgs->Message(IDS_ALFFSCRIPTINTERNALERROR,IDS_ALFFSESSSCPTTITLE);
             SessionMessage(IDS_ALFFSCRIPTINTERNALERROR);
             delete pScript;
             pScript = NULL;
             SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
             Disconnect(true);
             return false;
            }
          }
       }
      else
       {
        if (!IsWHLLSession())
            pMsgs->Message(IDS_ALFFSCRIPTFILEERR,IDS_ALFFSESSTITLE);
        SessionMessage(IDS_ALFFSCRIPTFILEERR);
        delete pScript;
        pScript = NULL;
        SessionMessage(IDS_LINECLOSEDBYSCRIPTERR);
        Disconnect(true);
        return false;
       }
    }
	// Setup Connection IP Address and Port and Update Title
	connHostAddress = connData->hostName;
	itoa(connData->portNumber, portNumber, 10);
	connPortAddress = portNumber;
	GetApplication()->LoadString(IDS_LINESTATCONNECTING, text,sizeof text-1);
	connStatusTitle = text;
	connTextTitle = connHostAddress + " : " + connPortAddress;

   // if this an secure connection inform ssl method
   if (connData->securityMethod == ALFFSSLComm::ALFFSSLV23)
      connSSLStatus = " (SSLV2/SSLV3)";
   else if (connData->securityMethod == ALFFSSLComm::ALFFSSLV2)
      connSSLStatus = " (SSLV2)";
   else if (connData->securityMethod == ALFFSSLComm::ALFFSSLV3)
      connSSLStatus = " (SSLV3)";
   else connSSLStatus = " ";

	text[0] = NULL;
	strcat(text, connStatusTitle.c_str());
   if (strlen (connData->sessTitle))
		strcat(text, connData->sessTitle);
	else strcat(text, connData->connName);
	strcat(text, " (");
	strcat(text, connTextTitle.c_str());
	strcat(text,")");
   strcat(text,connSSLStatus.c_str());
#ifdef DEBUG32
	MessageBox("Connection: SessionMessage...","Tec3270 Debug",MB_OK);
#endif
	/* Log Begin on Screen and Log File if is active*/
	SessionMessage(text);

#ifdef DEBUG32
	MessageBox("Connection: TimeMessage...","Tec3270 Debug",MB_OK);
#endif

	/* Register Date and Time at what connection begins */
	TimeMessage();

#ifdef DEBUG32
	MessageBox("Connection: SetWindowTitle ...","Tec3270 Debug",MB_OK);
#endif
	/* Update Connection Window Title */
	SetWindowTitle();

#ifndef ALFFDebug
	int pError;
	char stringError[LINE_STRING_ERROR_LENGTH];
#ifndef DEBUG_PRT_DLG
   /* Check for connecting option:  Only Remote Printer must be connected ? */
   if ((!connData->printerInact)&&(connData->printerOnly))
    {
      pMsgs->LoadString(IDS_REMPRTCONNECTONLY, stringError, LINE_STRING_ERROR_LENGTH-1);
      strcat (stringError, "(Netname: ");
      strcat (stringError, connData->printerNetName);
      strcat (stringError, ")");

      /* Register user Remote Printer connection only */
      SessionMessage(stringError);

      /* Do create and connect the Remote Printer     */
      pRemotePrt = new ALFFRemotePrinter(this, dateFormat,
                                         connData,
                                         connNumber);
      pRemotePrt->Create();
      pRemotePrt->ShowWindow(SW_SHOW);

      return true;
    }
#endif
   /* Connect the terminal session and further (InitTerminalBuffer)
    *  check for connecting the remote printer */

	pError = pLineComm->LineConnect(connData->hostName, portNumber);
	if (pError)
	 {
	  if (pError == INVALID_CONNECTION_STATE)
      {
       if (!IsWHLLSession())
   		 pMsgs->Message(IDS_ALFFINVSESSSTATE, IDS_ALFFSESSTITLE);
       SessionMessage(IDS_ALFFINVSESSSTATE);
      }
	  else
		{
		 strncpy(stringError,
					ALFFLineError(pError).ReportError(),LINE_STRING_ERROR_LENGTH);
       if (!IsWHLLSession())
		    pMsgs->StrMessage(stringError,0,IDS_ALFFSESSTITLE);

		 /* Log Error on Screen and Log File if it is active */
		 SessionMessage(stringError);

		 /* Inform Date and Time when connection error ocurred */
		 SessionMessage(IDS_LINECLOSEDBYERROR);
		 Disconnect(false);
		}
	  return false;
	 }
	else
	 {
		 /* further, we will receive LINE_CONNECT Event */
		 if ((connData->actOption != NO_TIMER)&&(connData->intvTime))
		  {
			timerType = connData->actOption;
			timerOn = true;
			ResetTimer(true);  //Force Timer To Be Set
		  }
	  }
   return true;
// ---------------End of normal processing (No debug or trace active)
#endif

//--------------------------TRACE---------------------------------
#ifdef ALFFTrace
	MessageBox("Connection Ok ........", "Tec3270 Trace Info", MB_OK);
#endif
//---------------------------------------------------------------

//----------------------------------------------------------------//
//----------------------Tec3270 DEBUG Starts Here ----------------//
//----------------------------------------------------------------//
#ifdef ALFFDebug
	int nEvent = LINE_READ;
	int lError = 0;
	WPARAM wParam = 0;
	LPARAM lParam = MAKELONG(nEvent,lError);

	/* Test for Close After and IDLE TIME  Events */
	if ((connData->actOption != NO_TIMER)&&(connData->intvTime))
		  {
			timerType = connData->actOption;
			timerOn = true;
			ResetTimer(true);  //Force Timer To Be Set
		  }
//--------------- Tec3270 3270 DEBUG Starts Here -----------------//
#ifdef DEBUG_TN3270

#ifdef TEST_TN3270E
	/* IAC DO TN3270E */
	unsigned char wBuf1[] = {IAC, DO, TN3270E};
	pLineInBuf->ring_supply_data((char*)wBuf1, 3);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

	/* IAC, SB, TN3270E, SEND, DEVICE-TYPE, IAC, SE */
	unsigned char wBuf2[] = { IAC, SB, TN3270E, SEND_E, DEVICE_TYPE, IAC, SE};
	pLineInBuf->ring_supply_data((char*)wBuf2, 7);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);


   /* IAC SB TN3270E DEVICE-TYPE IS IBM-3287-1 CONNECT GWI00130 IAC SE */
	unsigned char wBuf3[] = {IAC, SB, TN3270E, DEVICE_TYPE, IS_E,
                            'I','B','M','-','3','2','7','8','-','5','E',
                            CONNECT,
                            'G','W','V','0','0','1','3','0',
                            IAC, SE};
   pLineInBuf->ring_supply_data((char*)wBuf3, 27);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);


	/* IAC SB TN3270E FUNCTIONS IS_E DATA_STREAM_CTL RESPONSES IAC SE */
	unsigned char wBuf4[] = {IAC, SB, TN3270E, FUNCTIONS, IS_E, RESPONSES,
                                                               IAC, SE };
	pLineInBuf->ring_supply_data((char*)wBuf4, 8);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

   /* T3270 Data-Type Header */
   unsigned char wBuf4A [] = {T3270_DATA, ERR_COND_CLEARED, ALWAYS_RESPONSE, 0x00,0x00};
	pLineInBuf->ring_supply_data((char*)wBuf4A, 5);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

#else
	//
	// Telnet Session Initialization - Valid For 3270 Terminal Types
	//
	/* IAC DO TN_TERMINAL_TYPE */
	unsigned char wBuf1[] = {IAC, DO, TN_TERMINAL_TYPE};
	pLineInBuf->ring_supply_data((char*)wBuf1, 3);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

	/* IAC, SB, TN_TERMINAL_TYPE, SEND, IAC, SE */
	unsigned char wBuf2[] = { IAC, SB, TN_TERMINAL_TYPE, SEND, IAC, SE};
	pLineInBuf->ring_supply_data((char*)wBuf2, 6);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

	/* IAC, DO, TN_EOR, IAC, WILL, TN_EOR */
	unsigned char wBuf3[] = {IAC, DO, TN_EOR, IAC, WILL, TN_EOR};
	pLineInBuf->ring_supply_data((char*)wBuf3, 6);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

	/* IAC, DO, TN_TRANSMIT_BINARY,IAC, WILL, TN_TRANSMIT_BINARY */
	unsigned char wBuf4[] = {IAC, DO, TN_TRANSMIT_BINARY,IAC, WILL,
											 TN_TRANSMIT_BINARY};
	pLineInBuf->ring_supply_data((char*)wBuf4, 6);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);
#endif


	/* Full Screen Received and ended with IAC,EOR  */
	/*
	unsigned char wBuf5[1600] =
	 {0x01,0x40,IAC,EOR,
	  0x05,0xC3,0x11,0xD2,0x7B,0x13,0x11,0x40,0xC1,0x1D,0x60,0xE3,
	  0xC5,0xD3,0xC1,0x40,0xf0,0xf0,0xF1,0x11,0xC1,0x60,0x1D,0xE8,0xD9,0x40,0xC5,0x40,
	  0xC4,0x40,0xC5,0x40,0x60,0x40,0xE2,0x40,0xC5,0x40,0xD9,0x40,0xD7,0x40,0xD9,0x40,
	  0xD6,0x1D,0x60,0x11,0xC2,0xC2,0x1D,0x60,0x4F,0x4F,0x4F,0x11,0xC2,0x4A,0x1D,0x60,
	  0x4F,0x4F,0x11,0xC3,0x4D,0x1D,0x60,0x4F,0x4F,0x4F,0x4F,0x4F,0x4F,0x40,0x4F,0x4F,
	  0x4F,0x4F,0x4F,0x4F,0x40,0x40,0x4F,0x11,0xC4,0xC1,0x1D,0xE8,0xC1,0x40,0xE2,0xC5,
	  0xD9,0xE5,0xC9,0xC3,0xD6,0x40,0xC4,0xD6,0x40,0xC2,0xD9,0xC1,0xE2,0xC9,0xD3,0x1D,
	  0x60,IAC,EOR};
	*/

	//
	unsigned char wBuf5[1920];
	memset ((char*)wBuf5,0xC1,1520);
	memset ((char*)wBuf5,ERASEWRITEREM,1);
	memset ((char*)wBuf5+1,0xC7,1);
   pLineInBuf->ring_supply_data((char*)wBuf5, 2);  //*

	/*--------- Field on Line 1, Col 5 ----------------*
	//(Protegido,Reverso,Cor Vermelho)
	unsigned char wBuf6[48] =
	 {0x11,0x40,0xC4,0x29,0x03,0xc0,0xe8,0x41,0xf2,0x42,0xf2,
	  0xc3,0xc1,0xd4,0xd7,0xd6,0x40,0xd7,0xd9,0xd6,0xe3,0xc5,
	  0xc7,0xc9,0xc4,0xd6,0x6b,0xd9,0xc5,0xe5,0xc5,0xd9,0xe2,
	  0xd6,0x6b,0xe5,0xc5,0xd9,0xd4,0xc5,0xd3,0xc8,0xd6,0x1d,
	  0x60,0x19,0xf1,0xc7};
	memcpy ((char*)wBuf5+2,wBuf6,sizeof wBuf6);

	/*--------- Field on Line  2, Col 1 ----------------*
	// (Protegido,Sublinhado,Cor Pink)
	unsigned char wBuf7[45] =
	 {0x11,0xC1,0x50,0x29,0x03,0xc0,0xe8,0x41,0xf4,0x42,0xf3,
	  0xc3,0xc1,0xd4,0xd7,0xd6,0x40,0xd7,0xd9,0xd6,0xe3,0xc5,
	  0xc7,0xc9,0xc4,0xd6,0x6b,0xd7,0xc9,0xd5,0xd2,0x6b,0xe2,
	  0xe4,0xc2,0xd3,0xc9,0xd5,0xc8,0xc1,0xc4,0xd6,0x4b,0x1d,
	  0x40};
	/*--------------------------------------------------*
	memcpy ((char*)wBuf5+2+sizeof wBuf6,(char*)wBuf7,sizeof wBuf7);

	/* Test For SFE embebbed on data stream with non-displayable field *
	unsigned char wBuf9[34] =
	 {0x1d,0xe8,0xd7,0x81,0xa2,0xa2,0xa6,0x96,0x99,0x84,0x40,0x4b,0x40,
	  0x4b,0x29,0x03,0x41,0xF4,0x42,0xf5,0xc0,0x4c,0x11,0xC5,
	  0xF0,0x29,0x02,0xc0,0x50,0x42,0xF2,0x28,0x42,0xF1};
	memcpy ((char*)wBuf5+95,(char*)wBuf9,sizeof wBuf9);

	/* Test For SA embebbed on data stream after other SA *
	unsigned char wBuf8[6] =
	 {0x28,0x42,0xF4,0x28,0x41,0xF4};
	memcpy ((char*)wBuf5+1200,(char*)wBuf8,sizeof wBuf8);

	memset ((char*)wBuf5+1518,IAC,1);
	memset ((char*)wBuf5+1519,EOR,1);
	pLineInBuf->ring_supply_data((char*)wBuf5, 1520);

//
// Standard Screen For 3270 Attributes Testing  */
//*
	unsigned char wBuf6[1349] =
	{0x7e,0xc6,0x11,0x40,0x4b,0x1d,0xe8,0x28,0x42,0xf4,0xc4,0x40,
	 0x81,0x40,0xa3,0x40,0x81,0x40,0x40,0xc9,0x40,0x95,0x40,0xa3,
	 0x40,0x85,0x40,0x99,0x40,0x86,0x40,0x81,0x40,0x83,0x40,0x85,
	 0x40,0x40,0x28,0x42,0xf5,0xe3,0x40,0xd5,0x40,0xf3,0x40,0xf2,
	 0x40,0xf7,0x40,0xf0,0x40,0xc5,0x28,0x42,0xf4,0x40,0x40,0xe2,
	 0x40,0x85,0x40,0x99,0x40,0xa5,0x40,0x85,0x40,0x99,0x28,0x42,
	 0x00,0x11,0xc1,0xe3,0x1d,0xe0,0xe4,0x95,0x97,0x99,0x96,0xa3,
	 0x85,0x83,0xa3,0x85,0x84,0x40,0x86,0x89,0x85,0x93,0x84,0xa2,
	 0x7a,0x1d,0xc0,0xd9,0x85,0x87,0xa4,0x93,0x81,0x99,0x40,0x40,
	 0x1d,0xc8,0xc9,0x95,0xa3,0x85,0x95,0xa2,0x85,0x11,0xc2,0xf5,
	 0x1d,0xe0,0xd7,0x99,0x96,0xa3,0x85,0x83,0xa3,0x85,0x84,0x40,
	 0x86,0x89,0x85,0x93,0x84,0xa2,0x7a,0x1d,0xe0,0xd9,0x85,0x87,
	 0xa4,0x93,0x81,0x99,0x40,0x40,0x1d,0xe8,0xc9,0x95,0xa3,0x85,
	 0x95,0xa2,0x85,0x11,0x5d,0x4a,0x1d,0xe8,0x28,0x42,0xf4,0xc8,
	 0x89,0xa3,0x40,0x28,0x42,0xf5,0xc5,0xd5,0xe3,0xc5,0xd9,0x28,
	 0x42,0xf4,0x40,0xa3,0x96,0x40,0x99,0x85,0xa3,0xa4,0x99,0x95,
	 0x40,0xa3,0x96,0x40,0x94,0x85,0x95,0xa4,0x11,0xc5,0xc9,0x1d,
	 0xe8,0x28,0x41,0x00,0x40,0xc4,0xc5,0xc6,0xc1,0xe4,0xd3,0xe3,
	 0x40,0x11,0xc5,0x5f,0x28,0x41,0xf1,0x40,0x40,0xc2,0xd3,0xc9,
	 0xd5,0xd2,0x40,0x40,0x11,0xc5,0xf1,0x28,0x41,0xf2,0x40,0xd9,
	 0xc5,0xe5,0xc5,0xd9,0xe2,0xc5,0x40,0x11,0xc6,0xc5,0x28,0x41,
	 0xf4,0xe4,0xd5,0xc4,0xc5,0xd9,0xd3,0xc9,0xd5,0xc5,0x11,0xc6,
	 0x5a,0x28,0x41,0x00,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,
	 0x60,0x11,0xc6,0x6f,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,
	 0x60,0x11,0xc7,0xc1,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,
	 0x60,0x11,0xc7,0xd5,0x60,0x60,0x60,0x60,0x60,0x60,0x60,0x60,
	 0x60,0x11,0xc7,0x60,0x1d,0xe0,0x28,0x42,0x00,0xd5,0xd6,0xd9,
	 0xd4,0xc1,0xd3,0x11,0xc7,0x6a,0x28,0x41,0x00,0x40,0xc4,0x85,
	 0x86,0x81,0xa4,0x93,0xa3,0x40,0x11,0xc7,0x7f,0x28,0x41,0xf1,
	 0x40,0xc4,0x85,0x86,0x81,0xa4,0x93,0xa3,0x40,0x11,0xc8,0xd1,
	 0x28,0x41,0xf2,0x40,0xc4,0x85,0x86,0x81,0xa4,0x93,0xa3,0x40,
	 0x11,0xc8,0xe5,0x28,0x41,0xf4,0x40,0xc4,0x85,0x86,0x81,0xa4,
	 0x93,0xa3,0x40,0x11,0xc8,0x7a,0x28,0x42,0xf1,0x28,0x41,0x00,
	 0x40,0x40,0xc2,0x93,0xa4,0x85,0x40,0x40,0x40,0x11,0xc9,0x4f,
	 0x28,0x41,0xf1,0x40,0x40,0xc2,0x93,0xa4,0x85,0x40,0x40,0x40,
	 0x11,0xc9,0x61,0x28,0x41,0xf2,0x40,0x40,0xc2,0x93,0xa4,0x85,
	 0x40,0x40,0x40,0x11,0xc9,0xf5,0x28,0x41,0xf4,0x40,0x40,0xc2,
	 0x93,0xa4,0x85,0x40,0x40,0x40,0x11,0x4a,0x4a,0x28,0x42,0xf2,
	 0x28,0x41,0x00,0x40,0x40,0x40,0xd9,0x85,0x84,0x40,0x40,0x40,
	 0x11,0x4a,0x5f,0x28,0x41,0xf1,0x40,0x40,0x40,0xd9,0x85,0x84,
	 0x40,0x40,0x40,0x11,0x4a,0xf1,0x28,0x41,0xf2,0x40,0x40,0x40,
	 0xd9,0x85,0x84,0x40,0x40,0x40,0x11,0x4b,0xc5,0x28,0x41,0xf4,
	 0x40,0x40,0x40,0xd9,0x85,0x84,0x40,0x40,0x40,0x11,0x4b,0x5a,
	 0x28,0x42,0xf3,0x28,0x41,0x00,0x40,0x40,0xd7,0x89,0x95,0x92,
	 0x40,0x40,0x40,0x11,0x4b,0x6f,0x28,0x41,0xf1,0x40,0x40,0xd7,
	 0x89,0x95,0x92,0x40,0x40,0x40,0x11,0x4c,0xc1,0x28,0x41,0xf2,
	 0x40,0x40,0xd7,0x89,0x95,0x92,0x40,0x40,0x40,0x11,0x4c,0xd5,
	 0x28,0x41,0xf4,0x40,0x40,0xd7,0x89,0x95,0x92,0x40,0x40,0x40,
	 0x11,0x4c,0x6a,0x28,0x42,0xf4,0x28,0x41,0x00,0x40,0x40,0xc7,
	 0x99,0x85,0x85,0x95,0x40,0x40,0x11,0x4c,0x7f,0x28,0x41,0xf1,
	 0x40,0x40,0xc7,0x99,0x85,0x85,0x95,0x40,0x40,0x11,0x4d,0xd1,
	 0x28,0x41,0xf2,0x40,0x40,0xc7,0x99,0x85,0x85,0x95,0x40,0x40,
	 0x11,0x4d,0xe5,0x28,0x41,0xf4,0x40,0x40,0xc7,0x99,0x85,0x85,
	 0x95,0x40,0x40,0x11,0x4d,0x7a,0x28,0x42,0xf5,0x28,0x41,0x00,
	 0xe3,0xa4,0x99,0x98,0xa4,0x96,0x89,0xa2,0x85,0x11,0x4e,0x4f,
	 0x28,0x41,0xf1,0xe3,0xa4,0x99,0x98,0xa4,0x96,0x89,0xa2,0x85,
	 0x11,0x4e,0x61,0x28,0x41,0xf2,0xe3,0xa4,0x99,0x98,0xa4,0x96,
	 0x89,0xa2,0x85,0x11,0x4e,0xf5,0x28,0x41,0xf4,0xe3,0xa4,0x99,
	 0x98,0xa4,0x96,0x89,0xa2,0x85,0x11,0x4f,0x4a,0x28,0x42,0xf6,
	 0x28,0x41,0x00,0x40,0xe8,0x85,0x93,0x93,0x96,0xa6,0x40,0x40,
	 0x11,0x4f,0x5f,0x28,0x41,0xf1,0x40,0xe8,0x85,0x93,0x93,0x96,
	 0xa6,0x40,0x40,0x11,0x4f,0xf1,0x28,0x41,0xf2,0x40,0xe8,0x85,
	 0x93,0x93,0x96,0xa6,0x40,0x40,0x11,0x50,0xc5,0x28,0x41,0xf4,
	 0x40,0xe8,0x85,0x93,0x93,0x96,0xa6,0x40,0x40,0x11,0x50,0x5a,
	 0x28,0x42,0xf7,0x28,0x41,0x00,0x40,0x40,0xe6,0x88,0x89,0xa3,
	 0x85,0x40,0x40,0x11,0x50,0x6f,0x28,0x41,0xf1,0x40,0x40,0xe6,
	 0x88,0x89,0xa3,0x85,0x40,0x40,0x11,0xd1,0xc1,0x28,0x41,0xf2,
	 0x40,0x40,0xe6,0x88,0x89,0xa3,0x85,0x40,0x40,0x11,0xd1,0xd5,
	 0x28,0x41,0xf4,0x40,0x40,0xe6,0x88,0x89,0xa3,0x85,0x40,0x40,
	 //                  0x40
	 0x11,0xd1,0x60,0x1d,0xe8,0x28,0x42,0x00,0x28,0x41,0x00,0xc9,
	 0xd5,0xe3,0xc5,0xd5,0xe2,0xc5,0x11,0xd1,0x6a,0x28,0x41,0x00,
	 0x40,0xc4,0x85,0x86,0x81,0xa4,0x93,0xa3,0x40,0x11,0xd1,0x7f,
	 0x28,0x41,0xf1,0x40,0xc4,0x85,0x86,0x81,0xa4,0x93,0xa3,0x40,
	 0x11,0xd2,0xd1,0x28,0x41,0xf2,0x40,0xc4,0x85,0x86,0x81,0xa4,
	 0x93,0xa3,0x40,0x11,0xd2,0xe5,0x28,0x41,0xf4,0x40,0xc4,0x85,
	 0x86,0x81,0xa4,0x93,0xa3,0x40,0x11,0xd2,0x7a,0x28,0x42,0xf1,
	 0x28,0x41,0x00,0x40,0x40,0xc2,0x93,0xa4,0x85,0x40,0x40,0x40,
	 0x11,0xd3,0x4f,0x28,0x41,0xf1,0x40,0x40,0xc2,0x93,0xa4,0x85,
	 0x40,0x40,0x40,0x11,0xd3,0x61,0x28,0x41,0xf2,0x40,0x40,0xc2,
	 0x93,0xa4,0x85,0x40,0x40,0x40,0x11,0xd3,0xf5,0x28,0x41,0xf4,
	 0x40,0x40,0xc2,0x93,0xa4,0x85,0x40,0x40,0x40,0x11,0xd4,
	 0x4a,0x28,0x42,0xf2,0x28,0x41,0x00,0x40,0x40,0x40,0xd9,0x85,
	 0x84,0x40,0x40,0x40,0x11,0xd4,0x5f,0x28,0x41,0xf1,0x40,0x40,
	 0x40,0xd9,0x85,0x84,0x40,0x40,0x40,0x11,0xd4,0xf1,0x28,0x41,
	 0xf2,0x40,0x40,0x40,0xd9,0x85,0x84,0x40,0x40,0x40,0x11,0xd5,
	 0xc5,0x28,0x41,0xf4,0x40,0x40,0x40,0xd9,0x85,0x84,0x40,0x40,
	 0x40,0x11,0xd5,0x5a,0x28,0x42,0xf3,0x28,0x41,0x00,0x40,0x40,
	 0xd7,0x89,0x95,0x92,0x40,0x40,0x40,0x11,0xd5,0x6f,0x28,0x41,
	 0xf1,0x40,0x40,0xd7,0x89,0x95,0x92,0x40,0x40,0x40,0x11,0xd6,
	 0xc1,0x28,0x41,0xf2,0x40,0x40,0xd7,0x89,0x95,0x92,0x40,0x40,
	 0x40,0x11,0xd6,0xd5,0x28,0x41,0xf4,0x40,0x40,0xd7,0x89,0x95,
	 0x92,0x40,0x40,0x40,0x11,0xd6,0x6a,0x28,0x42,0xf4,0x28,0x41,
	 0x00,0x40,0x40,0xc7,0x99,0x85,0x85,0x95,0x40,0x40,0x11,0xd6,
	 0x7f,0x28,0x41,0xf1,0x40,0x40,0xc7,0x99,0x85,0x85,0x95,0x40,
	 0x40,0x11,0xd7,0xd1,0x28,0x41,0xf2,0x40,0x40,0xc7,0x99,0x85,
	 0x85,0x95,0x40,0x40,0x11,0xd7,0xe5,0x28,0x41,0xf4,0x40,0x40,
	 0xc7,0x99,0x85,0x85,0x95,0x40,0x40,0x11,0xd7,0x7a,0x28,0x42,
	 0xf5,0x28,0x41,0x00,0xe3,0xa4,0x99,0x98,0xa4,0x96,0x89,0xa2,
	 0x85,0x11,0xd8,0x4f,0x28,0x41,0xf1,0xe3,0xa4,0x99,0x98,0xa4,
	 0x96,0x89,0xa2,0x85,0x11,0xd8,0x61,0x28,0x41,0xf2,0xe3,0xa4,
	 0x99,0x98,0xa4,0x96,0x89,0xa2,0x85,0x11,0xd8,0xf5,0x28,0x41,
	 0xf4,0xe3,0xa4,0x99,0x98,0xa4,0x96,0x89,0xa2,0x85,0x11,0xd9,
	 0x4a,0x28,0x42,0xf6,0x28,0x41,0x00,0x40,0xe8,0x85,0x93,0x93,
	 0x96,0xa6,0x40,0x40,0x11,0xd9,0x5f,0x28,0x41,0xf1,0x40,0xe8,
	 0x85,0x93,0x93,0x96,0xa6,0x40,0x40,0x11,0xd9,0xf1,0x28,0x41,
	 0xf2,0x40,0xe8,0x85,0x93,0x93,0x96,0xa6,0x40,0x40,0x11,0x5a,
	 0xc5,0x28,0x41,0xf4,0x40,0xe8,0x85,0x93,0x93,0x96,0xa6,0x40,
	 0x40,0x11,0x5a,0x5a,0x28,0x42,0xf7,0x28,0x41,0x00,0x40,0x40,
	 0xe6,0x88,0x89,0xa3,0x85,0x40,0x40,0x11,0x5a,0x6f,0x28,0x41,
	 0xf1,0x40,0x40,0xe6,0x88,0x89,0xa3,0x85,0x40,0x40,0x11,0x5b,
	 0xc1,0x28,0x41,0xf2,0x40,0x40,0xe6,0x88,0x89,0xa3,0x85,0x40,
	 0x40,0x11,0x5b,0xd5,0x28,0x41,0xf4,0x40,0x40,0xe6,0x88,0x89,
	 0xa3,0x85,0x40,0x40,0xff,0xef};
	pLineInBuf->ring_supply_data((char*)wBuf6, 1349);  //*
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);
#ifdef TEST_TN3270E

   /* NVT Data-Type Header */
   unsigned char wBuf6A [] = {NVT_DATA, ERR_COND_CLEARED, ALWAYS_RESPONSE, 0x00,0x01,
                              'N','V','T','-','D','A','T','A',' ','T','E','S','T',IAC,EOR};
	pLineInBuf->ring_supply_data((char*)wBuf6A, 20);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

   /* T3270_Data-Type Header */
   unsigned char wBuf6b [] = {T3270_DATA, ERR_COND_CLEARED, ALWAYS_RESPONSE, 0x00,0x02,
                              ERASEWRITEREM,0xC7,0x11,0x40,0x40,0x40,0x28,0x41,0xf2,
                              0xd9,0xc5,0xe5,0xc5,0xd9,0xe2,0xc5,0x40,
                              0xf3,0xf2,0xf7,0xf0,0x40,0x28,0x41,0x00,0x40,
                              0x1d,0xe8,IAC,EOR};
	pLineInBuf->ring_supply_data((char*)wBuf6b, 35);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

#endif

//--------------- Tec3270 3270 DEBUG Ends Here -----------------//

//--------------- Tec3270 NVT DEBUG Starts Here ----------------//
#elif defined(DEBUG_NVT)
	//
	// Telnet Session Initialization - Valid For NVT Terminal Type
	//
	/* IAC WILL TN_ECHO */
	unsigned char wBuf1[] = {IAC, WILL, TN_ECHO};
	pLineInBuf->ring_supply_data((char*)wBuf1, 3);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

	/* IAC WILL TN_SUPRESS_GA */
	unsigned char wBuf2[] = {IAC, WILL, TN_SUPPRESS_GA};
	pLineInBuf->ring_supply_data((char*)wBuf2, 3);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

	/* IAC, DO, TN_TERMINAL_TYPE */
	unsigned char wBuf3[] = { IAC, DO, TN_TERMINAL_TYPE};
	pLineInBuf->ring_supply_data((char*)wBuf3, 3);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

	/* IAC, DO, TN_NEG_ABOUT_WIN_SIZ */
	unsigned char wBuf4[] = { IAC, DO, TN_NEG_ABOUT_WIN_SIZ};
	pLineInBuf->ring_supply_data((char*)wBuf4, 3);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

//
// Standard Screen For NVT Testing  */
//
	unsigned char wBuf5[370] =
	{0x43,0x43,0x0d,0x0a,
	 0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,
	 0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,
	 0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,
	 0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,
	 0x23,0x23,0x23,0x0d,0x0a,
	 0x23,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
	 0x20,0x20,0x20,0x20,0x20,0x53,0x20,0x45,0x20,0x52,0x20,0x50,
	 0x20,0x52,0x20,0x20,0x4f,0x20,0x2d,0x20,0x53,0x20,0x50,0x20,
	 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
	 0x20,0x20,0x23,0x0d,0x0a,
	 0x23,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x45,0x71,0x75,
	 0x69,0x70,0x61,0x6d,0x65,0x6e,0x74,0x6f,0x3a,0x20,0x43,0x69,
	 0x73,0x63,0x6f,0x20,0x37,0x35,0x31,0x33,0x20,0x23,0x20,0x32,
	 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
	 0x20,0x20,0x23,0x0d,0x0a,
	 0x23,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x4c,0x6f,0x63,
	 0x61,0x6c,0x69,0x7a,0x61,0x63,0x61,0x6f,0x3a,0x20,0x52,0x45,
	 0x47,0x49,0x4f,0x4e,0x41,0x4c,0x20,0x53,0x41,0x4f,0x20,0x50,
	 0x41,0x55,0x4c,0x4f,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
	 0x20,0x20,0x23,0x0d,0x0a,
	 0x23,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x43,0x6f,0x6e,
	 0x74,0x61,0x74,0x6f,0x3a,0x20,0x28,0x30,0x31,0x31,0x29,0x20,
	 0x35,0x32,0x35,0x2d,0x31,0x35,0x32,0x36,0x20,0x2d,0x20,0x43,
	 0x47,0x52,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
	 0x20,0x20,0x23,0x0d,0x0a,
	 0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,
	 0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,
	 0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,
	 0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,0x23,
	 0x23,0x23,0x23,0x0d,0x0a,
	 0x60,0x0d,0x0a,0x0d,0x0a,
	 0x55,0x73,0x65,0x72,0x20,0x41,0x63,0x63,0x65,0x73,0x73,0x20,
	 0x56,0x65,0x72,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6f,0x6e,
	 0x0d,0x0a,0x0d,0x0a,
	 0x28,0x74,0x61,0x63,0x29,0x55,0x73,0x65,0x72,0x6e,0x61,0x6d,
	 0x65,0x3a,0x20};
	pLineInBuf->ring_supply_data((char*)wBuf5, 370);
	SendMessage(MSG_LINE_NOTIFY,wParam,lParam);

#endif  //ifdef DEBUG_NVT
//--------------- Tec3270 NVT DEBUG Ends Here -----------------//

	nEvent = LINE_CONNECT;
	lParam = MAKELONG(nEvent,lError);
	DoLineNotification(wParam,lParam);

#endif  //ifdef ALFFDebug
//----------------------Tec3270 DEBUG Ends Here -----------------//
}

void
ALFFMDIChild::CmDisconnectEnable(TCommandEnabler &ce)
{
 if (pTerminal->IsConnected() || IsConnecting()
   || IsSSLConnecting()
	|| MDIParent->IsMonitoring())
	ce.Enable(true);
  else
	ce.Enable(false);
}

void
ALFFMDIChild::CmDisconnect()
{
 SessionMessage(IDS_LINECLOSEDBYUSER);
 Disconnect(true);  //true = Check Exit on Closing
}

bool
ALFFMDIChild::Disconnect(bool checkExitOnClose)
{
 int pError;
 char stringError[LINE_STRING_ERROR_LENGTH];

 if (IsConnecting())
  {
   // Nothing to do: just reset the connection
   // and put it on Idle State()
   // See procedures that follow "if" structure
  }
 else if (IsConnected())
  {
	pError = pLineComm->LineDisconnect();
   if (pError != CONNECTION_CLOSED)
    {
 			strncpy(stringError,
			 		ALFFLineError(pError).ReportError(),
			 		LINE_STRING_ERROR_LENGTH);
         if (!IsWHLLSession())
	 	  	   pMsgs->StrMessage(stringError,0,IDS_ALFFSESSTITLE);
	      /* Log Error on Screen and Log File if is active*/
	      SessionMessage(stringError);
	 }
  }
 else if ( IsSSLConnected() || IsSSLConnecting()
        || IsSSLDisconnecting() )
   {

   // If the session was disconnect by host, so do the session cleanup
   if (disconnectedByHost)
    {
     DisconnectedByHost();
     return true;
    }

    /* Set Disconnecting SSL State */
    SetSSLDisconnectingState();
    disconnectPendingForReadWrite = false;

    // try to disconnect
	 pError = pLineComm->LineDisconnect();
    if (pError != SSL_CONNECTION_CLOSED)  // Something wrong has happened !!
     {
      string sslErrMsg;
      switch (pError)
       {
        case SSL_WANT_READ:
        case SSL_WANT_WRITE:
			     {
        		  	// Need to do nothing: further we will receive FD_READ
        			//  or FD_WRITE from socket
      			disconnectPendingForReadWrite = true;
       		   return false;
              }
        case SSL_DISCONNECT_ERROR:
       		  {
        			bool hasError = false;
        			sslErrMsg = pLineComm->GetSSLErrors(hasError);
        			if (hasError)
                {
                  if (!IsWHLLSession())
          			    pMsgs->StrMessage(sslErrMsg.c_str(),0,IDS_ALFFSESSTITLE);
          			/* Log Error on Screen and Log File if is active*/
          			SessionMessage(sslErrMsg.c_str());
         		 }
               break;
       		  }
        case INVALID_CONNECTION_STATE:
              {
               if (!IsWHLLSession())
                   pMsgs->StrMessage("SSLComm-Disconnect",IDS_ALFFINVSESSSTATE ,IDS_ALFFSESSTITLE);
               SessionMessage("SSLComm-Disconnect");
               SessionMessage(IDS_ALFFINVSESSSTATE);
               break;
              }
        default:
              {
               if (!IsWHLLSession())
               	pMsgs->StrMessage("SSLComm-Disconnect", IDS_ALFFSSLERROR, IDS_ALFFSESSTITLE);
               SessionMessage("SSLComm-Disconnect");
               SessionMessage(IDS_ALFFSSLERROR);
               break;
              }
       }

     }
    //final cleanup else's is ahead ....

   }
 else if (IsIdle()) // Already disconected, need no actions
    return true;

 else
  {
   if (!IsWHLLSession())
        pMsgs->StrMessage("Disconnect", IDS_ALFFINVSESSSTATE, IDS_ALFFSESSTITLE);
   SessionMessage("Disconnect");
   SessionMessage(IDS_ALFFINVSESSSTATE);
  }
 /* Register Date/Time of event */
 TimeMessage();

 /* Reset All conditions to initial state */
 CloseTerminal();

 /* If there is an remote printer we must close it */
 if (pRemotePrt)
  {
   pRemotePrt->Disconnect();
   delete pRemotePrt;
   pRemotePrt = NULL;
  }

 /* Update Connection window title */
 connStatusTitle = connInitialTitle;
 connData->connName[0] = NULL;
 connData->sessTitle[0] = NULL;
 connSSLStatus = " ";
 SetWindowTitle();

 SetIdleState();

 /* Update Base Terminal Screen */
 pTerminal->PaintScreen();

 if (checkExitOnClose && connData->connExit)
	Parent->PostMessage(MSG_CLOSE_IMMED,0,0);

 /* Reset Tries Count to None */
 numReconnTries = 0;

 return true;
}

bool
ALFFMDIChild::InitTerminalBuffer(bool nvt)
{
 short defScrLineSize, defScrNumLines,
	    altScrLineSize, altScrNumLines;
 bool colorTerminal, extendedAttribute;

 if (!nvt)
  {
	char *pType, *pModel;
	pType  = pTelnet->GetTerminalType();
	pModel = pTelnet->GetTerminalModel();

	/*
	 * STRCMP returns 0 (false) when strings to
	 * compare are equal
	 */
	if (!(strcmp(pType,IBM3278))
	  || !(strcmp(pType,IBM3279)) )
	 {
	  /* Set Terminal Color  Characteristics */
	  if (!strcmp(pType,IBM3279) )
		 colorTerminal = true;
	  else colorTerminal = false;

	  /* Set Terminal Highlighting Characteristics */
	  if (!(strcmp(pModel,MODEL2E))
		 || !(strcmp(pModel,MODEL3E))
		 || !(strcmp(pModel,MODEL4E))
		 || !(strcmp(pModel,MODEL5E)) )
		 extendedAttribute = true;
	  else extendedAttribute = false;

	  /* Set Terminal Default and Alternate Screen Format */
	  if  ( !(strcmp(pModel,MODEL2))
		 || !(strcmp(pModel,MODEL2E)) )
			{
			 defScrLineSize = 80;
			 defScrNumLines = 24;
			 altScrLineSize = 80;
			 altScrNumLines = 24;
			}
	  else if (!(strcmp(pModel,MODEL3))
				 || !(strcmp(pModel,MODEL3E)))
					{
					 defScrLineSize = 80;
					 defScrNumLines = 24;
					 altScrLineSize = 80;
					 altScrNumLines = 32;
					}
	  else if (!(strcmp(pModel,MODEL4))
				 || !(strcmp(pModel,MODEL4E)))
					{
					 defScrLineSize = 80;
					 defScrNumLines = 24;
					 altScrLineSize = 80;
					 altScrNumLines = 43;
					}

	  else if (!(strcmp(pModel,MODEL5))
				 || !(strcmp(pModel,MODEL5E)))
					{
					 defScrLineSize = 80;
					 defScrNumLines = 24;
					 altScrLineSize = 132;
					 altScrNumLines = 27;
					}

	  else      {
					 defScrLineSize = 80;
					 defScrNumLines = 24;
					 altScrLineSize = 80;
					 altScrNumLines = 24;
					}

	  /* Initialize 3270 Buffer with Default and Alternate Screens Parms */
	  p3270Buf->InitBuf(defScrNumLines,defScrLineSize,
							  altScrNumLines,altScrLineSize,
							  colorTerminal, extendedAttribute);
	  pTerminal->Connect(true); //3270 Mode
	 }
	 else
	 {
	  /* Included for preparing to other terminal
		* types on future versions....
		*/
	  if (!(strcmp(pType,TELNETNVT)))
		{
		 /* Returning To NVT Terminal Mode */
		 defScrLineSize = 80;
		 defScrNumLines = 24;
		 altScrLineSize = 80;
		 altScrNumLines = 24;
		 pTerminal->Connect(false,(!pTerminal->IsMode3270()));  //NVT Mode
		 pTerminal->SetEchoMode(pTelnet->GetEchoMode());
		 }
	  else
		 {
		  /* Unknow Terminal Type */
		  if (pTerminal->IsMode3270())
			 pTerminal->Connect(false); //NVT Mode
		  return false;
		 }
	 }
  }
 else
  {
	/* This is an NVT Session Initialization*/
	defScrLineSize = 80;
	defScrNumLines = 24;
	altScrLineSize = 80;
	altScrNumLines = 24;
	colorTerminal = false;
	extendedAttribute = false;

	/* Initialize NVT Buffer with Default and Alternate Screens Parms */
	pNVTBuf->InitBuf(defScrNumLines,defScrLineSize,
						  altScrNumLines,altScrLineSize,
						  colorTerminal, extendedAttribute);
  }
 /* Set Terminal Screen Characteristics */
 pTerminal->SetScrLineSize(defScrLineSize,altScrLineSize);
 pTerminal->SetScrNumLines(defScrNumLines,altScrNumLines);
 pTerminal->SetScreen(DEFAULTSCREEN);

 // Updating Terminal Characteristics on Application Class
 Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
 int retCode = 0;

 if ((theApp->GetTermLineSize() != altScrLineSize)     // era <
	|| (theApp->GetTermNumLines() != altScrNumLines+1))  // era <
  {
	theApp->SetTermLineSize(altScrLineSize);
	theApp->SetTermNumLines(altScrNumLines+1);

	/* Set Background Color To All Screen Size */
	pTerminal->ResetScrColor();
  }

 // Set Horizontal Scroller if we need it
 if ((retCode & SETHSCROLL)
  ||(retCode & SETVSCROLL))
	pTerminal->SetScroll();

 /* Update Tec3270 Status Bar */
 theApp->UpdateTN3270();    // TN3270/TN3270E indicator
 theApp->UpdateTermGadget();
 theApp->UpdateTermNetname();
 theApp->UpdatePrtGadget();
 theApp->UpdatePrtNetname();

 return true;
}

bool
ALFFMDIChild::CloseTerminal()
{
 if (timerOn)
  {
	timerOn = false;
	KillTimer(connNumber);
  }
 pTelnet->CloseAll();
 if (pTerminal->IsMode3270())
  {
	p3270Buf->ClearBuf();
	p3270Buf->ResetAll();
  }
 else	pNVTBuf->Reset();

 pTerminal->Disconnect();
 termBufferInitialized = false;

 /* Reset Communications Line */
 pLineComm->LineDisconnect();

 /* Reset All Connection Buffers */
 pLineInBuf->ring_reset();
 pLineOutBuf->ring_reset();
 pNetInBuf->ring_reset();
 pNetOutBuf->ring_reset();
 pOOBData->ring_reset();

 return true;
}

LRESULT
ALFFMDIChild::UpdateFont(WPARAM, LPARAM)
{
 TRect winRect;
 Tec3270MainWindow *theAppWindow =
	  TYPESAFE_DOWNCAST(GetApplication()->GetMainWindow(),
									Tec3270MainWindow);
 winRect = theAppWindow->GetClientRect();
 if (!IsZoomed())
  {
	MoveWindow(winRect.left, winRect.top,
				  (winRect.Width()/6)*5,
				  (winRect.Height()/8)*5,
				  true);
  }
 pTerminal->SetScreenFont(true);  //Should redraw the child window
 pTerminal->SetScroll();
 return 1L;
}

LRESULT
ALFFMDIChild::UpdateSecurityOptions(WPARAM, LPARAM)
{
 if (IsSSLConnected() || IsSSLConnecting())
  {
   // Accessing Application Class
   Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
   ALFFIniFile* iniFile = theApp->GetIniFile();
   char iniSection[24] = "SECURITY OPTIONS";
   bool verifyCert = iniFile->GetInt(iniSection,"VERIFYSERVERCERT",false);
   bool verifyRevoked =  iniFile->GetInt(iniSection,"VERIFYREVOKED",false);

   pLineComm->UpdateCertVerifyOptions(verifyCert ,verifyRevoked);

   if (pRemotePrt != NULL)
     pRemotePrt->UpdateSecurityOptions(verifyCert ,verifyRevoked);

  }
 return 1L;
}

LRESULT
ALFFMDIChild::UpdateColors(WPARAM, LPARAM)
{
 //pTerminal->SetColors();
 return 1L;
}

LRESULT
ALFFMDIChild::UpdateKeyboard(WPARAM keybId, LPARAM)
{
 if (!pTerminal->ReLoadKeyboard(keybId))
	pMsgs->Message(IDS_KEYBNOTAVAIL,IDS_KEYBERROR);
 return 1L;
}

void
ALFFMDIChild::EvSize(uint sizeType, TSize& size)
{
 TMDIChild::EvSize(sizeType, size);
}

LRESULT
ALFFMDIChild::EvResetTimer(WPARAM, LPARAM)
{
  ResetTimer();
  return 1L;
}

void
ALFFMDIChild::ResetTimer(bool forceSet)
{
 if (timerOn)
  {
	if ((timerType != KEY_TIMER)||(forceSet))
	 {
	  /* Kill the current timer. If it not exists nothing will be done. */
	  KillTimer(connNumber);

	  /* if there is no activity in the time interval specified by
		  connData->closeAfter this session will be timed out */
	  if (connData->intvTime)
		 connTimeout = connData->intvTime * 1000;
	  else return;

	  /* Set the TIMER with correct value */
	  if (connTimeout > MAXTIMEOUT)
		  SetTimer(connNumber,MAXTIMEOUT);
	  else SetTimer(connNumber,(UINT)connTimeout);
	 }
  }
}

void
ALFFMDIChild::EvTimer(uint timerId)
{
 KillTimer(timerId);
 if (connTimeout > MAXTIMEOUT)
	connTimeout -= MAXTIMEOUT;
  else connTimeout = 0;

 /* connTimeout contains the remaining time to wait until some action is done */
 if (connTimeout)
  {
	/* Connection Timer Must Be Restarted */
	if (connTimeout > MAXTIMEOUT)
	  SetTimer(connNumber, MAXTIMEOUT);
	 else SetTimer(connNumber, (UINT)connTimeout);
  }
 else /* Timer is Over: Do the correct action ! */
  {
	if (timerType == CLOSE_TIMER)
	 {
	  /* Connection will timeout */
	  SessionMessage(IDS_LINECLOSEDBYTIMEOUT);
	  Disconnect(true);  //true = Check Exit on Closing
	 }
	else if ((timerType == IDLE_TIMER) || (timerType == KEY_TIMER))
	  {
		/* Connection will send idle Key.. */
		int command;
		switch (IDS_IDLEKEYBASE+connData->pressKey+1)
		 {
		  case IDS_IDLECLEAR:  command = IDS_CLEAR; break;
		  case IDS_IDLEENTER:  command = IDS_ENTERCOMMAND; break;
		  case IDS_IDLEPA1  :  command = IDS_PA1; break;
		  case IDS_IDLEPA2  :  command = IDS_PA2; break;
		  case IDS_IDLEPA3  :  command = IDS_PA3; break;
		  case IDS_IDLEPF1  :  command = IDS_PF1; break;
		  case IDS_IDLEPF2  :  command = IDS_PF2; break;
		  case IDS_IDLEPF3  :  command = IDS_PF3; break;
		  case IDS_IDLEPF4  :  command = IDS_PF4; break;
		  case IDS_IDLEPF5  :  command = IDS_PF5; break;
		  case IDS_IDLEPF6  :  command = IDS_PF6; break;
		  case IDS_IDLEPF7  :  command = IDS_PF7; break;
		  case IDS_IDLEPF8  :  command = IDS_PF8; break;
		  case IDS_IDLEPF9  :  command = IDS_PF9; break;
		  case IDS_IDLEPF10 :  command = IDS_PF10; break;
		  case IDS_IDLEPF11 :  command = IDS_PF11; break;
		  case IDS_IDLEPF12 :  command = IDS_PF12; break;
		  case IDS_IDLEPF13 :  command = IDS_PF13; break;
		  case IDS_IDLEPF14 :  command = IDS_PF14; break;
		  case IDS_IDLEPF15 :  command = IDS_PF15; break;
		  case IDS_IDLEPF16 :  command = IDS_PF16; break;
		  case IDS_IDLEPF17 :  command = IDS_PF17; break;
		  case IDS_IDLEPF18 :  command = IDS_PF18; break;
		  case IDS_IDLEPF19 :  command = IDS_PF19; break;
		  case IDS_IDLEPF20 :  command = IDS_PF20; break;
		  case IDS_IDLEPF21 :  command = IDS_PF21; break;
		  case IDS_IDLEPF22 :  command = IDS_PF22; break;
		  case IDS_IDLEPF23 :  command = IDS_PF23; break;
		  case IDS_IDLEPF24 :  command = IDS_PF24; break;
		  default           :  command = 0; break;
		 }
		if (command)
			/*
			 * Simulate Command Key Pressed. Further the Timer will be reset
			 *	in DoNetOutput Procedure that will be activated on Terminal
			 *	Buffer Manager Object.
			 */
			pTerminal->ProcessCommand(command,true);
		 else
        {
         if (!IsWHLLSession())
            pMsgs->Message(IDS_SESSINVIDLEKEY,IDS_ALFFSESSTITLE);
         SessionMessage(IDS_SESSINVIDLEKEY);
        }
	  }
  }
}

void
ALFFMDIChild::ReceiveData(bool urgent)
{
 int  readLength = 0,
#ifndef ALFFDebug
		maxReadLength,
#endif
		retOOBLen;
 char *lastRead   = 0;

 //--------------------------TRACE---------------------------------
#ifdef ALFFTrace
	MessageBox("Starting line read ...",
						 "Tec3270 Trace Info", MB_OK);
#endif
 //-------------------------DEBUG----------------------------------
#ifdef ALFFDebug
 int lError = 0;
 readLength = pLineInBuf->ring_full_consecutive();
 lastRead = pLineInBuf->consume;
#else
 //----------- Normal Processing - Read Line ----------------------

 int lError;
 char stringError[LINE_STRING_ERROR_LENGTH];

 maxReadLength = readLength = pLineInBuf->ring_empty_consecutive();
 lError = pLineComm->LineRecvData(pLineInBuf->supply, (int&)readLength, urgent);

 // Is there some bytes on ringbuffer to process ?
 if (!readLength)
   // Nothing to do !!
   return;

 if(lError != 0)
  {
   if (IsConnected())  // Not an SSL Connection
    {
	  stringError[0]=NULL;
	  strncpy(stringError,
			  ALFFLineError(lError).ReportError(),
			  LINE_STRING_ERROR_LENGTH);
     if (!IsWHLLSession())
	  		pMsgs->StrMessage(stringError,0,IDS_ALFFSESSTITLE);

     /* Log Error on Screen and Log File if is active*/
     SessionMessage(stringError);
    }
   else if (IsSSLConnected() )
    {
     if ((lError == SSL_WANT_READ) || (lError == SSL_WANT_WRITE) )
      {
       //Nothing to do: wait until next FD_READ or FD_WRITE (LINE_READ / LINE_WRITE)
       receiveDataPendingForReadWrite = true;
       return;
      }
     else if (lError == SSL_CONNECTION_CLOSED)
      {
       if (!IsWHLLSession())
	    	pMsgs->Message(IDS_ALFFSSLCONNCLOSED,IDS_ALFFSESSTITLE);
	    pTerminal->WriteNVTLine(IDS_ALFFSSLCONNCLOSED);
	    SessionMessage(IDS_LINECLOSEDBYERROR);
	    Disconnect(true);  //true = Check Exit on Closing
       return;
      }
     else  //SSL_CONNECTION_ERROR
      {
       bool hasError = false;
       string sslErrMsg = pLineComm->GetSSLErrors(hasError);
       if (hasError)
        {
         if (!IsWHLLSession())
             pMsgs->Message(IDS_ALFFSSLERROR,IDS_ALFFSESSTITLE);
         /* Log Error on Screen and Log File if is active*/
         SessionMessage(IDS_ALFFSSLERROR);
         SessionMessage(sslErrMsg.c_str());
         return;
        }
      }
    }
   else if (IsIdle()) // CONNECTION_CLOSED
        return;

   else
    {
     if (!IsWHLLSession())
       pMsgs->StrMessage("ReceiveData",IDS_ALFFINVSESSSTATE, IDS_ALFFSESSTITLE);
     SessionMessage("ReceiveData");
     SessionMessage(IDS_ALFFINVSESSSTATE);
    }

	#ifndef ALFFDebug
	return;
	#endif
  }
  else
  {
   receiveDataPendingForReadWrite = false;
	if (readLength > maxReadLength)
    {
     if (!IsWHLLSession())
	  			pMsgs->Message(IDS_ALFFSESSRECVERR,IDS_ALFFSESSTITLE);
     SessionMessage(IDS_ALFFSESSRECVERR);
    }
	else
	 {
     if (readLength)
      {
	    pLineInBuf->ring_supplied(readLength);
	    lastRead = pLineInBuf->consume;
      }
     else return;
    }
  }
#endif

 //--------------------------TRACE---------------------------------
#ifdef ALFFTrace
 char tBuf[128];
 char message[256];
 memcpy(tBuf,lastRead,(readLength > sizeof tBuf ?
				 sizeof tBuf : (size_t)readLength));
 tBuf[126] = NULL;
 wsprintf(message,"Read Data (Char) -> %s",tBuf);
 MessageBox(message,
			  "Tec3270 Trace Info", MB_OK | MB_ICONEXCLAMATION);
#endif

 //--------------------------DEBUG---------------------------------
 if (traceON)
  {
   if (pTerminal->IsMode3270())
	  /* Convert EBCDIC to ASCII */
	  pTrcFile->LogData('R',lastRead, readLength, urgent, true,
							  p3270Buf->GetTabEbcAsc());
   else
	  /* Need no Conversion */
	  pTrcFile->LogData('R',lastRead, readLength, urgent);
  }

 /*
  * Process TelNet Data:
  *
  *   Take message available for consuming in NetInBuf and parse it for
  *   separating Terminal Input Data (TermInBuf) from Protocol Options
  *   Negotiations data and give correct responses for them (OOBData).
  */

 /* Do Not Process OOB Data on separate mode in this version */
 int telnetError = 0;
 if (!urgent)
	telnetError = pTelnet->MessageRecv(pLineInBuf,pNetInBuf,pOOBData);
 else pLineInBuf->ring_consumed(readLength);

 //
 // Is There OOBDATA to send ??
 //
 lError = 0;
 retOOBLen = pOOBData->ring_full_consecutive();
 if (retOOBLen)
  {
	//--------------------------TRACE-----------------------------
	#ifdef ALFFTrace
	MessageBox("Sending OOB Data ...",
				  "Tec3270 Debug Info", MB_OK | MB_ICONEXCLAMATION);
	#endif
	//------------------------------------------------------------
	//
	if ((pLineOutBuf->ring_empty_consecutive()) > retOOBLen)
	 {
	  pTelnet->SetOOBData(true);
     //  true == no TN3270E Header
	  if (pTelnet->MessageSend(pLineOutBuf,pOOBData,true))
		{
		 SendData();
		 pTerminal->SetEchoMode(pTelnet->GetEchoMode());
		 if (pTelnet->TermTypeChanged())
			  //&& (!termBufferInitialized))
		  {
			if (InitTerminalBuffer())
			 termBufferInitialized = true;
			else lError = IDS_ALFFSESSTERMERR;
		  }
		}
		else lError = IDS_ALFFSESSPROTERR;
	  pTelnet->SetOOBData(false);
	 }
	 else lError = IDS_ALFFSESSOUTBUFERR;
  }
 else if (!telnetError)
  {
  	 if (pTelnet->TermTypeChanged())
	  //&& (!termBufferInitialized))
	  {
		if (InitTerminalBuffer())
		 termBufferInitialized = true;
		else lError = IDS_ALFFSESSTERMERR;
	  }
  }

 if (lError || telnetError)
  {
   if (telnetError)
      lError = telnetError;
   if (!IsWHLLSession())
   	pMsgs->Message(lError,IDS_ALFFSESSTITLE);
   pTerminal->WriteNVTLine(lError);
   SessionMessage(lError);
   SessionMessage(IDS_LINECLOSEDBYERROR);
   Disconnect(true);  //true = Check Exit on Closing
  }
}

void
ALFFMDIChild::SendData(bool urgent)
{
 int  lError;
 char *sendBuf;
 int nCharsToSend;
 char stringError[LINE_STRING_ERROR_LENGTH];
 /*
  * if it is sending data put the new request on a queue...
  */

 sendQueue++;
 if (!sending)
 {
  while (sendQueue)
	{
	 sending=true;
	 //--------------------------TRACE---------------------------------
	 #ifdef ALFFTrace
	 MessageBox("Sending Data ...",
					"Tec3270 Debug Info", MB_OK | MB_ICONEXCLAMATION);
	 #endif
	 //----------------------------------------------------------------
	 nCharsToSend = pLineOutBuf->ring_full_consecutive();
	 if (nCharsToSend)
	 {
	  sendBuf = pLineOutBuf->consume;
#ifndef DEBUG_TN3270
	  lError = pLineComm->LineSendData(sendBuf, nCharsToSend, urgent);
#else
     lError = 0;
#endif
     if(lError != 0)
      {
		 dataSent = false;
       if (IsConnected())  // Not an SSL Connection
        {
		   stringError[0]=NULL;
		   strncpy(stringError,
					ALFFLineError(lError).ReportError(),
					LINE_STRING_ERROR_LENGTH);
         if (!IsWHLLSession())
		   	pMsgs->StrMessage(stringError,0,IDS_ALFFSESSTITLE);

		   /* Log Error on Screen and Log File if is active*/
		   SessionMessage(stringError);
		   TimeMessage();
        }
       else if (IsSSLConnected() )
        {
         if ((lError == SSL_WANT_READ) || (lError == SSL_WANT_WRITE) )
          {
           //Nothing to do: wait until next FD_READ  (LINE_READ)
           sendDataPendingForReadWrite = true;
           return;
          }
         else if (lError == SSL_CONNECTION_CLOSED)
          {
           if (!IsWHLLSession())
	        		pMsgs->Message(IDS_ALFFSSLCONNCLOSED,IDS_ALFFSESSTITLE);
	        pTerminal->WriteNVTLine(IDS_ALFFSSLCONNCLOSED);
	        SessionMessage(IDS_LINECLOSEDBYERROR);
	        Disconnect(true);  //true = Check Exit on Closing
           return;
          }
         else  //SSL_CONNECTION_ERROR
          {
           bool hasError = false;
           string sslErrMsg = pLineComm->GetSSLErrors(hasError);
           if (hasError)
            {
             if (!IsWHLLSession())
             	pMsgs->StrMessage(sslErrMsg.c_str(),0,IDS_ALFFSESSTITLE);
             /* Log Error on Screen and Log File if is active*/
             SessionMessage(sslErrMsg.c_str());
            }
          }
        }
       else
        {
         if (!IsWHLLSession())
         		pMsgs->StrMessage("SendData",IDS_ALFFINVSESSSTATE, IDS_ALFFSESSTITLE);
         SessionMessage("SendData");
         SessionMessage(IDS_ALFFSCRIPTINVBEFCONN);
        } 
#ifndef ALFFDebug
		 return;
#else
		 pLineOutBuf->ring_consumed(nCharsToSend);
#endif
      }
	  else
      {
       sendDataPendingForReadWrite = false;
       pLineOutBuf->ring_consumed(nCharsToSend);
      }
    }
	if (pLineOutBuf->ring_full_count())
	  dataSent = false;
	 else dataSent = true;

	//
	// Trace Send Text to Trace File if Trace Option was selected
	//
	if (traceON)
	 if (pTerminal->IsMode3270())
		/* Convert EBCDIC to ASCII */
		pTrcFile->LogData('S',sendBuf, nCharsToSend, urgent, true,
								p3270Buf->GetTabEbcAsc());
	 else
		/* Need no Conversion */
		pTrcFile->LogData('S', sendBuf, nCharsToSend);
	 sendQueue-=1;

	} // end while
  sending=false;
 }
}

void
ALFFMDIChild::SetIdleState()
{
 // Line Closed by host or any line error before
 //  reset  dataSent & xxxxxxxPendingForReadWrite
 connectPendingForReadWrite = false;
 receiveDataPendingForReadWrite = false;
 sendDataPendingForReadWrite    = false;
 disconnectPendingForReadWrite = false;
 dataSent = true;
 nLineState = nIdle;

 /* Update the SSL PadLock */
 Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
 theApp->UpdateSSLLock();
 theApp->UpdateTN3270();
 theApp->UpdateTermGadget();
 theApp->UpdateTermNetname();
 theApp->UpdatePrtGadget();
 theApp->UpdatePrtNetname();

 /* Update the connection icon to reflect its status */
 SetIconSm(GetApplication(), IDI_ALFFCONNECTIONBRK);
 pTerminal->Invalidate();

 /* Update Tec3270 Menu Bar to recflect connection status */
 GetApplication()->GetMainWindow()->DrawMenuBar();
}

void
ALFFMDIChild::SetConnectedState()
{
	nLineState = nConnected;

   /* Update the connection icon to reflect its status */
   SetIconSm(GetApplication(), IDI_ALFFCONNECTION);
   pTerminal->Invalidate();

   /* Update Tec3270 Menu Bar to recflect connection status */
   GetApplication()->GetMainWindow()->DrawMenuBar();

   /* Update Tec3270 Status Bar */
   Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
   theApp->UpdateSSLLock();    // SSL Padlock
}

void
ALFFMDIChild::SetSSLConnectedState()
{
 nLineState = nSSLConnected;

 /* Update Tec3270 Status Bar */
 Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
 theApp->UpdateSSLLock();      // SSL Padlock

 /* Update the connection icon to reflect its status */
 SetIconSm(GetApplication(), IDI_ALFFCONNECTION);
 pTerminal->Invalidate();

 /* Update Tec3270 Menu Bar to recflect connection status */
 GetApplication()->GetMainWindow()->DrawMenuBar();
}

bool
ALFFMDIChild::CanClose()
{
 bool closeConn;
 char msgText[STRINGMSGLEN+1];
 Tec3270App *theApp = TYPESAFE_DOWNCAST(GetApplication(),Tec3270App);
 if (IsWHLLSession() && !IsWHLLClosing())
  return false;
 closeConn = theApp->IsAppEnded();
 if ( (!closeConn) && (!IsWHLLSession()) )
  {
	if (pMsgs->StrMessage(Title, IDS_SESSWILLCLOSE, IDS_ALFFSESSTITLE,true)
			 == IDOK )
		closeConn = true;
  }
 else closeConn = true;
 if (closeConn)
  {
	if (traceON)
	 {
     ::LoadString(theApp->GetInstance(),IDS_ALFFSESSTRACEEND,msgText,STRINGMSGLEN);
	  pTrcFile->LogText(msgText, strlen(msgText));
	  delete pTrcFile;
	  pTrcFile = 0;
	  traceON = false;
	 }
	if (!IsIdle())
	  Disconnect(false);  //false = Do Not Check Exit on Closing
   MDIParent->DecrementNumChild();
	return true;
  }
  else return false;
}

/* Find / Replace Methods-Procedures Adapted From TEditSearch OWL Object
 * Perform a search or replace operation based on information
 * in SearchData
 */

void
ALFFMDIChild::CannotFind()
{
 char stringError[STRINGMSGLEN+1];
 char msgError[STRINGMSGLEN+1];
 pMsgs->LoadString(IDS_FINDCANNOTFIND,stringError,STRINGMSGLEN);
 wsprintf(msgError,stringError,(const char far*)SearchData.FindWhat);
 TWindow* w = SearchDialog ?
							(TWindow*)SearchDialog : (TWindow*)this;
 ALFFMsgs Msg(w);
 Msg.StrMessage(msgError,0,IDS_ALFFFINDREPLTITLE);
}

bool
ALFFMDIChild::DoSearch()
{
  int retCode = 0, fdBegin;
  uint startSelBufPos = 0;
  uint endSelBufPos = 0;
  TPoint startSelScr;
  TPoint endSelScr;
  do
  {
#if defined(BI_PLAT_WIN32)
	 unsigned long version = ::GetVersion();
	 if (version & 0x80000000L)
	 {
		if (GetApplication())
		  GetApplication()->PumpWaitingMessages();
	 }
#endif
	 bool found;
	 if ((SearchData.Flags & (FR_REPLACE|FR_REPLACEALL)) && (strFound))
	  found = true;
	 else
	  {
		if (pTerminal->IsMode3270())
		 found = p3270Buf->Search(-1, SearchData.FindWhat,
										 bool(SearchData.Flags&FR_MATCHCASE),
										 bool(SearchData.Flags&FR_WHOLEWORD),
										 !(SearchData.Flags&FR_DOWN)) >= 0;
		else found = pNVTBuf->Search(-1, SearchData.FindWhat,
										 bool(SearchData.Flags&FR_MATCHCASE),
										 bool(SearchData.Flags&FR_WHOLEWORD),
										 !(SearchData.Flags&FR_DOWN)) >= 0;
	  }

	 if (found)
		{
		  if (SearchData.Flags & (FR_REPLACE|FR_REPLACEALL))
			{
			 if (pTerminal->IsMode3270())
				fdBegin = p3270Buf->Replace(SearchData.ReplaceWith);
			 else fdBegin = pNVTBuf->Replace(SearchData.ReplaceWith);
			 if( fdBegin >= 0)
			  {
				lastOper = FR_REPLACE;
				pTerminal->UpdateScreen(fdBegin,LASTUPDATED,TOENDOFFIELD);
				strReplaced = true;
				strFound = false;
				retCode = true;
			  }
			  else
				{
				 char err[12];
				 if (fdBegin == PROTECTEDFIELD)
					  strcpy(err,PROTECTEDFD);
				 else if (fdBegin == NUMERICFIELD)
							 strcpy(err,NUMERICFD);
				 else strcpy(err,XSYSTEM);
				 pTerminal->LockKeyboard(err);
				 if (pTerminal->IsMode3270())
				  {
					if ( p3270Buf->GetSelection(startSelBufPos,endSelBufPos)
					  && (lastOper != FR_FINDNEXT ) )
					  pTerminal->UpdateScrSel(startSelBufPos,endSelBufPos);
				  }
				 else
				  {
					if ( pNVTBuf->GetSelection(startSelBufPos,endSelBufPos)
					  && (lastOper != FR_FINDNEXT ) )
					  pTerminal->UpdateScrSel(startSelBufPos,endSelBufPos);
				  }
				 TWindow* w = SearchDialog ?
								  (TWindow*)SearchDialog : (TWindow*)this;
				 ALFFMsgs Msg(w);
				 Msg.Message(IDS_REPLPROTECTED,IDS_ALFFFINDREPLTITLE);
				 lastOper = FR_REPLACE;
				 strFound = true;
				 retCode = false;
				 break;
				}
			}
		  else
			{
			 lastOper = FR_FINDNEXT;
			 strFound = true;
			 retCode = true;
			}
		}
	 else
	  {
		strFound = false;
		if (SearchData.Flags & (FR_FINDNEXT|FR_REPLACE))
		 {
		  pTerminal->RemoveSelection(true, !(SearchData.Flags&FR_DOWN));
		  CannotFind();
		  retCode = false;
		 }
		else if (SearchData.Flags & FR_REPLACEALL)
				{
				 TWindow* w = SearchDialog ?
								  (TWindow*)SearchDialog : (TWindow*)this;
				 ALFFMsgs Msg(w);
				 if (strReplaced)
				  {
					Msg.Message(IDS_REPLALLCHANGED,IDS_ALFFFINDREPLTITLE);
					strReplaced=false;
				  }
				  else CannotFind();
				 retCode = false;
				 break;
				}
	  }
  }
  while (SearchData.Flags & FR_REPLACEALL);
 return retCode;
}

//
// Open the modeless Find commdlg
//
void
ALFFMDIChild::CmEditFind()
{
  ResetTimer();   // EvResetTimer();
  if (!SearchCmd)
	{
	 SearchCmd = CM_EDITFIND;
    if (SearchDialog)
	      delete SearchDialog;
	 SearchDialog = new TFindDialog(this, SearchData);
	 SearchDialog->Create();
	 strFound = false;
  }
}

//
// Open the modeless Replace commdlg
//
void
ALFFMDIChild::CmEditReplace()
{
  ResetTimer();   // EvResetTimer();
  if (!SearchCmd)
  {
	 SearchCmd = CM_EDITREPLACE;
    if (SearchDialog)
	    delete SearchDialog;
	 SearchDialog = new TReplaceDialog(this, SearchData);
	 SearchDialog->Create();
	 strReplaced = false;
	 strFound = false;
  }
}

//
// Enable the find or replace option only if no dialog is up
//
void
ALFFMDIChild::CeEditFindReplace(TCommandEnabler& ce)
{
  ce.Enable(!SearchCmd
			 &&  pTerminal->IsConnected()
          && !pTerminal->IsLogOn()
			 && !MDIParent->IsMonitoring());
}

//
// Respond to the possible separate menu command to repeat the search
//
void
ALFFMDIChild::CmEditFindNext()
{
 uint startSelBufPos = 0;
 uint endSelBufPos = 0;
 bool hasSelection;

 ResetTimer();   // EvResetTimer();

 if (SearchDialog)
	 SearchDialog->UpdateData();

 SearchData.Flags |= FR_FINDNEXT;

 if (DoSearch())
	{
	 pTerminal->RemoveSelection(false, !(SearchData.Flags&FR_DOWN));
	 if (pTerminal->IsMode3270())
		hasSelection = p3270Buf->GetSelection(startSelBufPos,endSelBufPos);
	 else hasSelection = pNVTBuf->GetSelection(startSelBufPos,endSelBufPos);
	 if (hasSelection)
		pTerminal->UpdateScrSel(startSelBufPos,endSelBufPos);
	}
 else pTerminal->RemoveSelection(true, !(SearchData.Flags&FR_DOWN));
}

//
// Only enable FindNext if we've got data to search for
//
void
ALFFMDIChild::CeEditFindNext(TCommandEnabler& ce)
{
  ce.Enable((SearchData.FindWhat
		  && *(SearchData.FindWhat)) ? true : false
		  && !MDIParent->IsMonitoring());
}

//
// Respond to the message sent by the modeless find/replace dialog by
// performing a search. Or, if the dialog has terminated, zero search command
//
LRESULT
ALFFMDIChild::EvFindMsg(WPARAM, LPARAM lParam)
{
  uint startSelBufPos = 0;
  uint endSelBufPos = 0;
  bool hasSelection;
  PRECONDITION(SearchDialog);
  SearchDialog->UpdateData(lParam);
  if (SearchData.Flags & FR_DIALOGTERM)
	{
	 SearchCmd = 0;
	 strReplaced = false;
	 strFound = false;
	 lastOper = 0;
	 pTerminal->RemoveSelection(true, !(SearchData.Flags&FR_DOWN) );
	}
  else
	{
	 bool found = DoSearch();
	 pTerminal->RemoveSelection(false, !(SearchData.Flags&FR_DOWN) );
	 if (found)
	  {
		if (SearchData.Flags & FR_FINDNEXT)
		 {
		  if (pTerminal->IsMode3270())
			 hasSelection = p3270Buf->GetSelection(startSelBufPos,endSelBufPos);
		  else hasSelection = pNVTBuf->GetSelection(startSelBufPos,endSelBufPos);
		  if (hasSelection)
			  pTerminal->UpdateScrSel(startSelBufPos,endSelBufPos);
		 }
		 else pTerminal->UpdateScreen(0,LASTUPDATED,TOENDOFFIELD);
	  }
	}
  return 0;
}

/********************************************************************
 * Cut, Copy, Paste, Clear, & Delete Selection Methods for 3270     *
 * Buffer Operations. They take care with special caracteres like   *
 * 3270 SF and SFE orders.                                          *
 ********************************************************************/

/*
 * This function is called for Cut/Copy/Delete menu items to determine
 * whether or not the item is enabled.
 */
void
ALFFMDIChild::CmSelectEnable(TCommandEnabler& commandHandler)
{
  commandHandler.Enable(pTerminal->IsTextSelected()
								&&  pTerminal->IsConnected()
								&& !pTerminal->IsKeyboardLocked()
								&& !MDIParent->IsMonitoring());
}

/*
 * This function is called for the Paste menu item to determine whether or
 * not the item is enabled.
 */
void
ALFFMDIChild::CmPasteEnable(TCommandEnabler& commandHandler)
{
  TClipboard& clipboard = OpenClipboard();
  commandHandler.Enable( clipboard.IsClipboardFormatAvailable(CF_TEXT)
							 && !pTerminal->IsKeyboardLocked()
							 &&  pTerminal->IsConnected()
							 && !MDIParent->IsMonitoring());
  clipboard.CloseClipboard();
}

/*
 * This function is called for the Clear menu item to determine whether or
 * not the item is enabled.
 */
void
ALFFMDIChild::CmCharsEnable(TCommandEnabler& commandHandler)
{
  commandHandler.Enable(!pTerminal->IsKeyboardLocked()
								&&  pTerminal->IsConnected()
								&& !MDIParent->IsMonitoring());
}

/*
 * This function is called for the Undo menu item to determine whether or
 * not the item is enabled.
 */
void
ALFFMDIChild::CmModEnable(TCommandEnabler& commandHandler)
{
  bool isModified;
  if (pTerminal->IsConnected())
	{
	 if (pTerminal->IsMode3270())
	  isModified = p3270Buf->IsModified();
	 else isModified = pNVTBuf->IsModified();
	}
  else isModified = false;
  commandHandler.Enable(isModified
								&& !pTerminal->IsKeyboardLocked()
								&& !MDIParent->IsMonitoring());
}

void
ALFFMDIChild::CmEditCut()
{
 HGLOBAL HMem;
 char* pMem;
 Field* fdSelect;

 ResetTimer();

 /* Cut is similar to Copy except that selected text is removed */

 /* Save the Selected Text Before Inserting deleting it from 3270 Buffer */
 int fromPos = 0;
 if (pTerminal->IsMode3270())
	 fdSelect = p3270Buf->DataToScreen(fromPos,SELECTION,JUSTTEXT);
 else fdSelect = pNVTBuf->DataToScreen(fromPos,SELECTION,JUSTTEXT);

 char* selText = new char[strlen(fdSelect->fdText)+1];
 strcpy(selText, fdSelect->fdText);

 /* Remove Selected Text */
 if (pTerminal->ProcessCommand(IDS_DEL))
  {
	/* Allocate Memory Block To Acomodate the Text To be Inserted */
	HMem = (char*)::GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
										 strlen(selText)+1);
	if (HMem == NULL)
		pMsgs->Message(IDS_ALFFSESSOUTOFMEM,IDS_ALFFEDITTITLE);

	/* Lock Allocated Memory and obtain a pointer to it */
	pMem = (char*)::GlobalLock(HMem);
	if (pMem == NULL)
	 {
	  ::GlobalFree(HMem);
	  delete [] selText;
	  pMsgs->Message(IDS_ALFFSESSOUTOFMEM,IDS_ALFFEDITTITLE);
	  return;
	 }

	/* Copy Selected Text from selection to Global Memory Allocated */
	::lstrcpy(pMem,selText);

	/* Unlock the Global Memory Allocated */
	::GlobalUnlock(HMem);

	/* Try to get control over ClipBoard. If it is obtained OpenClipboard returns true */
   TClipboard& clipboard = OpenClipboard();
	if (!clipboard)
	  {
		::GlobalFree(HMem);
		delete [] selText;
		pMsgs->Message(IDS_EDITNOCLIPBOARD,IDS_ALFFEDITTITLE);
		return;
	  }

	/* Remove Clipboard Contents */
	if (clipboard.EmptyClipboard())
    {
     /* Supply the Memory Handle to The clipboard (insert the text in it) */
	  clipboard.SetClipboardData(CF_TEXT, HMem);
    }
	  /* Finally, Close the Clipboard, freeing access to it */
	clipboard.CloseClipboard();
  }
  else pTerminal->LockKeyboard();

 delete [] selText;
}

void
ALFFMDIChild::CmEditCopy()
{
 HGLOBAL HMem;
 char* pMem;
 Field* fdSelect;

 ResetTimer();

 /* Get the Selected Text for Inserting it on ClipBoard */
 int fromPos = 0;
 if (pTerminal->IsMode3270())
	 fdSelect = p3270Buf->DataToScreen(fromPos,SELECTION,JUSTTEXT,ASCII,true);
 else fdSelect = pNVTBuf->DataToScreen(fromPos,SELECTION,JUSTTEXT,ASCII);


 /* Allocate Memory Block To Acomodate the Text To be Inserted */
 HMem = (char*)::GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
									  strlen(fdSelect->fdText)+1);
 if (HMem == NULL)
	 pMsgs->Message(IDS_ALFFSESSOUTOFMEM,IDS_ALFFEDITTITLE);

 /* Lock Allocated Memory and obtain a pointer to it */
 pMem = (char*)::GlobalLock(HMem);
 if (pMem == NULL)
  {
	::GlobalFree(HMem);
	pMsgs->Message(IDS_ALFFSESSOUTOFMEM,IDS_ALFFEDITTITLE);
	return;
  }

 /* Copy Selected Text from selection to Global Memory Allocated */
 ::lstrcpy(pMem,fdSelect->fdText);

 /* Unlock the Global Memory Allocated */
 ::GlobalUnlock(HMem);

 /* Try to get control over ClipBoard. If it is obtained OpenClipboard returns true */

 TClipboard& clipboard = OpenClipboard();
 if (!clipboard)
	{
	 ::GlobalFree(HMem);
	 pMsgs->Message(IDS_EDITNOCLIPBOARD,IDS_ALFFEDITTITLE);
	 return;
	}

 /* Remove Clipboard Contents */
 if (clipboard.EmptyClipboard())
  {
   /* Supply the Memory Handle to The clipboard (insert the text in it) */
   clipboard.SetClipboardData(CF_TEXT, HMem);
  }

 /* Finally, Close the Clipboard, freeing access to it */
 clipboard.CloseClipboard();
}

void
ALFFMDIChild::CmEditPaste()
{
  int fdBegin;
  HANDLE HClipText;
  char*  pClipText;
  char*  cbText;

  ResetTimer();

  /* Try to get control over ClipBoard. If it is obtained OpenClipboard returns true */
  TClipboard& clipboard = OpenClipboard();
  if (!clipboard)
	{
	 pMsgs->Message(IDS_EDITNOCLIPBOARD,IDS_ALFFEDITTITLE);
	 return;
	}

  /* Try to get a Handle to Clipboard memory with the text */
  HClipText = clipboard.GetClipboardData(CF_TEXT);
  if (!HClipText)
	{
	 clipboard.CloseClipboard();
	 pMsgs->Message(IDS_EDITNOCLIPBOARD,IDS_ALFFEDITTITLE);
	 return;
	}

  /* Try to Get Memory Buffer enough to acomodate Clipboard Text */
  cbText = new char[(int)::GlobalSize(HClipText)];
  if (!cbText)
	{
	 clipboard.CloseClipboard();
	 pMsgs->Message(IDS_ALFFSESSOUTOFMEM,IDS_ALFFEDITTITLE);
	 return;
	}

  /* Get char pointer to ClipBoard Text */
  pClipText = (char*)::GlobalLock(HClipText);
  if (!pClipText)
	{
	 clipboard.CloseClipboard();
	 delete [] cbText;
	 pMsgs->Message(IDS_EDITNOCLIPBOARD,IDS_ALFFEDITTITLE);
	 return;
	}

  /* Copy Clipboard Text to Temporary Buffer for freeing Clipboard as fast as possible */
  ::lstrcpy(cbText,pClipText);

  /* Freeing Clipboard  */
  ::GlobalUnlock(HClipText);
  clipboard.CloseClipboard();

  /* Now we should remove from the ClipBoard Text, the control chars....*/
  char* textPaste = cbText;
  int pos = 0;
  int cbTextLen = strlen(cbText);
  for (int i = 0; i <= cbTextLen; i++)
	{
	 if (cbText[i] >= 0x20)   //ClipBoard is ASCII Text//
		textPaste[pos++] = cbText[i];
	}
  textPaste[pos] = NULL;

  /* As the clipboard text is available we should paste it into 3270 buffer */
  cbTextLen = strlen(textPaste);

  /* If there is any selection it must be replaced ... */
  if (pTerminal->IsTextSelected())
	{
	 /* This is an Replace Operation Like in FindReplace Method...*/
	 if (pTerminal->IsMode3270())
		 fdBegin = p3270Buf->Replace(textPaste);
	 else fdBegin = pNVTBuf->Replace(textPaste);
	 if (fdBegin >= 0)
		pTerminal->UpdateScreen(fdBegin,LASTUPDATED,TOENDOFFIELD);
	  else
		 {
		  char err[12];
		  if (fdBegin == PROTECTEDFIELD)
				strcpy(err,PROTECTEDFD);
		  else if (fdBegin == NUMERICFIELD)
					  strcpy(err,NUMERICFD);
		  else strcpy(err,XSYSTEM);
		  pTerminal->LockKeyboard(err);
		  pMsgs->Message(IDS_REPLPROTECTED,IDS_ALFFFINDREPLTITLE);
		 }
	}
  else
	{
	 /* This is an Insert Text Operation That May Be in Insert Mode */
	 if (pTerminal->IsMode3270())
		 fdBegin = p3270Buf->DataFromKeyboard(textPaste,cbTextLen,pTerminal->GetInsertMode());
	 else fdBegin = pNVTBuf->DataFromKeyboard(textPaste,cbTextLen,pTerminal->GetInsertMode());
	 if (fdBegin < 0)
	  {
		char err[12];
		if (fdBegin == PROTECTEDFIELD)
			 strcpy(err,PROTECTEDFD);
		else if (fdBegin == NUMERICFIELD)
					strcpy(err,NUMERICFD);
		else strcpy(err,XSYSTEM);
		pTerminal->LockKeyboard(err);
      pTerminal->PaintScreen();
	  }
	 /* Update screen with position changed */
	 else pTerminal->UpdateScreen(fdBegin+MUSTREPAINT,LASTUPDATED,TOENDOFFIELD);
	}
  delete [] cbText;
}

void
ALFFMDIChild::CmEditDelete()
{
 ResetTimer();
 if (pTerminal->IsTextSelected())
	pTerminal->ProcessCommand(IDS_DEL);
 else pMsgs->Message(IDS_EDITNOTEXTSEL,IDS_ALFFEDITTITLE);
}

void
ALFFMDIChild::CmEditClear()
{
 ResetTimer();
 pTerminal->ProcessCommand(IDS_CLEAR);
}

void
ALFFMDIChild::CmEditUndo()
{
 int fdBegin;
 ResetTimer();
 if (pTerminal->IsMode3270())
  {
    /* First of All, Selection Must Be Removed */
    pTerminal->RemoveSelection(true,false,false);
	 fdBegin = p3270Buf->ExecuteUndo();
  }
 else fdBegin = pNVTBuf->ExecuteUndo();
 if (fdBegin)
	pTerminal->UpdateScreen(fdBegin,LASTUPDATED,TOENDOFFIELD);
}

