summaryrefslogtreecommitdiff
path: root/AEAPactor.c
blob: 56686ee9154118c6938c9a703be891752e5f4718 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
/*
Copyright 2001-2022 John Wiseman G8BPQ

This file is part of LinBPQ/BPQ32.

LinBPQ/BPQ32 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

LinBPQ/BPQ32 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with LinBPQ/BPQ32.  If not, see http://www.gnu.org/licenses
*/	

//
//	DLL to inteface AEA/Timewave TNC in Pactor Mode to BPQ32 switch 
//
//	Uses BPQ EXTERNAL interface
//

// Version 1.1.1.2 Sept 2010

// Fix CTEXT
// Turn round link when all acked (not all sent)

// Version 1.1.1.3 Sept 2010

// Turn round link if too long in receive

// Version 1.1.1.4 September 2010

// Fix Freq Display after Node reconfig
// Only use AutoConnect APPL for Pactor Connects

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE

#include "time.h"

//#include <process.h>
//#include <time.h>

#include "CHeaders.h"
#include "tncinfo.h"

#include "bpq32.h"


static char ClassName[]="AEAPACTORSTATUS";

static char WindowTitle[] = "AEA Pactor";
static int RigControlRow = 165;

#define	SOH	0x01	// CONTROL CODES 
#define	ETB	0x17
#define	DLE	0x10

#define MaxStreams 26

#define PTOVER 0x1a					// Pactor Turnround Char

char OverMsg[3] = " \x1a";

static RECT Rect;

static char status[8][8] = {"STANDBY",  "PHASING", "CHGOVER", "IDLE", "TRAFFIC", "ERROR", "RQ", "XXXX"};

struct TNCINFO * CreateTTYInfo(int port, int speed);
BOOL SetupConnection(int);
BOOL CloseConnection(struct TNCINFO * conn);
static BOOL WriteCommBlock(struct TNCINFO * TNC);
BOOL DestroyTTYInfo(int port);
static void CheckRX(struct TNCINFO * TNC);
VOID AEAPoll(int Port);
static VOID ProcessDEDFrame(struct TNCINFO * TNC, UCHAR * rxbuff, int len);
static VOID ProcessTermModeResponse(struct TNCINFO * TNC);
static VOID DoTNCReinit(struct TNCINFO * TNC);
static VOID DoTermModeTimeout(struct TNCINFO * TNC);

VOID ProcessPacket(struct TNCINFO * TNC, UCHAR * rxbuffer, int Len);
VOID ProcessKPacket(struct TNCINFO * TNC, UCHAR * rxbuffer, int Len);
static VOID ProcessAEAPacket(struct TNCINFO * TNC, UCHAR * rxbuffer, size_t Len);
VOID ProcessKNormCommand(struct TNCINFO * TNC, UCHAR * rxbuffer);
static VOID ProcessHostFrame(struct TNCINFO * TNC, UCHAR * rxbuffer, size_t Len);

//	Note that AEA host Mode uses SOH/ETB delimiters, with DLE stuffing

static VOID EncodeAndSend(struct TNCINFO * TNC, UCHAR * txbuffer, int Len);
static int	DLEEncode(UCHAR * inbuff, UCHAR * outbuff, size_t len);
static int	DLEDecode(UCHAR * inbuff, UCHAR * outbuff, size_t len);

int ProcessLine(char * buf, int Port)
{
	UCHAR * ptr,* p_cmd;
	char * p_ipad = 0;
	char * p_port = 0;
	unsigned short WINMORport = 0;
	int BPQport;
	int len=510;
	struct TNCINFO * TNC;
	char errbuf[256];

	strcpy(errbuf, buf);

	ptr = strtok(buf, " \t\n\r");

	if(ptr == NULL) return (TRUE);

	if(*ptr =='#') return (TRUE);			// comment

	if(*ptr ==';') return (TRUE);			// comment

	ptr = strtok(NULL, " \t\n\r");

	if (_stricmp(buf, "ADDR") == 0)			// Winmor Using BPQ32 COnfig
	{
		BPQport = Port;
		p_ipad = ptr;
	}
	else
	if (_stricmp(buf, "APPL") == 0)			// Using BPQ32 COnfig
	{
		BPQport = Port;
		p_cmd = ptr;
	}
	else
	if (_stricmp(buf, "PORT") != 0)			// Using Old Config
	{
		// New config without a PORT or APPL  - this is a Config Command

		strcpy(buf, errbuf);
		strcat(buf, "\r");

		BPQport = Port;

		TNC = TNCInfo[BPQport] = malloc(sizeof(struct TNCINFO));
		memset(TNC, 0, sizeof(struct TNCINFO));

		TNC->InitScript = malloc(1000);
		TNC->InitScript[0] = 0;

		goto ConfigLine;
	}
	else

	{

		// Old Config from file

	BPQport=0;
	BPQport = atoi(ptr);
	
	p_cmd = strtok(NULL, " \t\n\r");

	if (Port && Port != BPQport)
	{
		// Want a particular port, and this isn't it

		while(TRUE)
		{
			if (GetLine(buf) == 0)
				return TRUE;

			if (memcmp(buf, "****", 4) == 0)
				return TRUE;

		}
	}
	}
	if(BPQport > 0 && BPQport < 33)
	{
		TNC = TNCInfo[BPQport] = malloc(sizeof(struct TNCINFO));
		memset(TNC, 0, sizeof(struct TNCINFO));

		TNC->InitScript = malloc(1000);
		TNC->InitScript[0] = 0;

		if (p_cmd != NULL)
		{
			if (p_cmd[0] != ';' && p_cmd[0] != '#')
				TNC->ApplCmd=_strdup(p_cmd);
		}

		// Read Initialisation lines

		while(TRUE)
		{
			if (GetLine(buf) == 0)
				return TRUE;
ConfigLine:
			strcpy(errbuf, buf);

			if (memcmp(buf, "****", 4) == 0)
				return TRUE;

			ptr = strchr(buf, ';');
			if (ptr)
			{
				*ptr++ = 13;
				*ptr = 0;
			}
			
			if (_memicmp(buf, "WL2KREPORT", 10) == 0)
				TNC->WL2K = DecodeWL2KReportLine(buf);
			else
				strcat (TNC->InitScript, buf);
		}
	}

	return (TRUE);
}



static size_t ExtProc(int fn, int port, PDATAMESSAGE buff) 
{
	int txlen = 0;
	PMSGWITHLEN buffptr;
	struct TNCINFO * TNC = TNCInfo[port];
	struct STREAMINFO * STREAM;
	int Stream;

	if (TNC == NULL || TNC->hDevice == 0)
		return 0;							// Port not open

	switch (fn)
	{
	case 1:				// poll

		while (TNC->PortRecord->UI_Q)			// Release anything accidentally put on UI_Q
		{
			buffptr = Q_REM(&TNC->PortRecord->UI_Q);
			ReleaseBuffer(buffptr);
		}

		for (Stream = 0; Stream <= MaxStreams; Stream++)
		{
			if (TNC->Streams[Stream].ReportDISC)
			{
				TNC->Streams[Stream].ReportDISC = FALSE;
				buff->PORT = Stream;

				return -1;
			}
		}

		CheckRX(TNC);
		AEAPoll(port);

		for (Stream = 0; Stream <= MaxStreams; Stream++)
		{
			if (TNC->Streams[Stream].PACTORtoBPQ_Q !=0)
			{
				size_t datalen;
			
				buffptr=Q_REM(&TNC->Streams[Stream].PACTORtoBPQ_Q);

				datalen = buffptr->Len;

				buff->PORT = Stream;						// Compatibility with Kam Driver
				buff->PID = 0xf0;
				memcpy(&buff->L2DATA, &buffptr->Data[0], datalen);		// Data goes to + 7, but we have an extra byte
				datalen += sizeof(void *) + 4;

				PutLengthinBuffer(buff, (int)datalen);

		
				ReleaseBuffer(buffptr);
	
				return (1);
			}
		}
			
		return 0;

	case 2:				// send

		buffptr = GetBuff();

		if (buffptr == 0) return (0);			// No buffers, so ignore

		// Find TNC Record

		Stream = buff->PORT;
		
		if (!TNC->TNCOK)
		{
			// Send Error Response

			buffptr->Len = 36;
			memcpy(buffptr->Data, "No Connection to PACTOR TNC\r", 36);

			C_Q_ADD(&TNC->Streams[Stream].PACTORtoBPQ_Q, buffptr);
			
			return 0;
		}

		txlen = GetLengthfromBuffer((PDATAMESSAGE)buff) - 8;

		buffptr->Len = txlen;
		memcpy(buffptr->Data, buff->L2DATA, txlen);
		
		C_Q_ADD(&TNC->Streams[Stream].BPQtoPACTOR_Q, buffptr);

		if(TNC->Streams[Stream].Connected)
		{
			TNC->Streams[Stream].FramesQueued++;
		}
		return (0);


	case 3:				// CHECK IF OK TO SEND. Also used to check if TNC is responding
		
		Stream = (int)(size_t)buff;
		STREAM = &TNC->Streams[Stream];

		if (STREAM->FramesQueued  > 4)
			return 1 | TNC->HostMode << 8 | STREAM->Disconnecting << 15;	// Busy
	
		return TNC->HostMode << 8 | STREAM->Disconnecting << 15;		// OK, but lock attach if disconnecting;		// OK

	case 4:				// reinit

		return (0);

	case 5:				// Close

		EncodeAndSend(TNC, "OHON", 4);		// HOST N
		Sleep(50);

		SaveWindowPos(port);

		CloseCOMPort(TNC->hDevice);

		return (0);

	case 6:				// Scan Control

		return 0;		// None Yet

	}
	return 0;

}


VOID * AEAExtInit(EXTPORTDATA *  PortEntry)
{
	char msg[500];
	struct TNCINFO * TNC;
	int port;
	char * TempScript;
	char * ptr;

	//
	//	Will be called once for each Pactor Port
	//	The COM port number is in IOBASE
	//

	sprintf(msg,"AEA Pactor %s", PortEntry->PORTCONTROL.SerialPortName);
	WritetoConsole(msg);

	port=PortEntry->PORTCONTROL.PORTNUMBER;

	ReadConfigFile(port, ProcessLine);

	TNC = TNCInfo[port];

	if (TNC == NULL)
	{
		// Not defined in Config file

		sprintf(msg," ** Error - no info in BPQ32.cfg for this port\n");
		WritetoConsole(msg);

		return ExtProc;
	}

	TNC->Port = port;

	TNC->Hardware = H_AEA;

	TNC->TEXTMODE = FALSE;

	PortEntry->MAXHOSTMODESESSIONS = 11;		// Default

	TNC->InitScript = _strupr(TNC->InitScript);

	TNC->PortRecord = PortEntry;

	if (PortEntry->PORTCONTROL.PORTCALL[0] == 0)
	{
		memcpy(TNC->NodeCall, MYNODECALL, 10);
	}
	else
	{
		ConvFromAX25(&PortEntry->PORTCONTROL.PORTCALL[0], TNC->NodeCall);
	}

	if (PortEntry->PORTCONTROL.PORTINTERLOCK && TNC->RXRadio == 0 && TNC->TXRadio == 0)
		TNC->RXRadio = TNC->TXRadio = PortEntry->PORTCONTROL.PORTINTERLOCK;

	PortEntry->PORTCONTROL.PROTOCOL = 10;
	PortEntry->PORTCONTROL.PORTQUALITY = 0;
	PortEntry->SCANCAPABILITIES = NONE;		// No Scan Interlock 

	if (PortEntry->PORTCONTROL.PORTPACLEN == 0)
		PortEntry->PORTCONTROL.PORTPACLEN = 100;

	ptr=strchr(TNC->NodeCall, ' ');
	if (ptr) *(ptr) = 0;					// Null Terminate

	// Set Essential Params and MYCALL

	TempScript = malloc(4000);

	strcpy(TempScript, "RESTART\r");
	strcat(TempScript, "EXPERT ON\r");
	strcat(TempScript, "PTHUFF 0\r");
	strcat(TempScript, "PT200 ON\r");
	strcat(TempScript, "WIDESHFT OFF\r");
	strcat(TempScript, "ARQT 30\r");

	strcat(TempScript, TNC->InitScript);

	free(TNC->InitScript);
	TNC->InitScript = TempScript;

	// Others go on end so they can't be overriden

	strcat(TNC->InitScript, "XMITOK ON\r");
	strcat(TNC->InitScript, "XFLOW OFF\r");
	strcat(TNC->InitScript, "RXREV OFF\r");
	strcat(TNC->InitScript, "FLOW OFF\r");
	strcat(TNC->InitScript, "AWLEN 8\r");
	strcat(TNC->InitScript, "AUTOBAUD OFF\r");
	strcat(TNC->InitScript, "8BITCONV ON\r");
	strcat(TNC->InitScript, "ALFPAC OFF\r");
	strcat(TNC->InitScript, "ALFDISP OFF\r");
	strcat(TNC->InitScript, "ACRRTTY 0\r");
	strcat(TNC->InitScript, "HPOLL ON\r");
	strcat(TNC->InitScript, "EAS ON\r\r");
	strcat(TNC->InitScript, "CONMODE TRANS\r");
	strcat(TNC->InitScript, "PTOVER $1A\r\r");

	// Set the ax.25 MYCALL

	sprintf(msg, "MYCALL %s\r", TNC->NodeCall);
	strcat(TNC->InitScript, msg);

#ifndef LINBPQ

	CreatePactorWindow(TNC, ClassName, WindowTitle, RigControlRow, PacWndProc, 0, 0, ForcedClose);

	CreateWindowEx(0, "STATIC", "Comms State", WS_CHILD | WS_VISIBLE, 10,6,120,20, TNC->hDlg, NULL, hInstance, NULL);
	TNC->xIDC_COMMSSTATE = CreateWindowEx(0, "STATIC", "", WS_CHILD | WS_VISIBLE, 116,6,386,20, TNC->hDlg, NULL, hInstance, NULL);
	
	CreateWindowEx(0, "STATIC", "TNC State", WS_CHILD | WS_VISIBLE, 10,28,106,20, TNC->hDlg, NULL, hInstance, NULL);
	TNC->xIDC_TNCSTATE = CreateWindowEx(0, "STATIC", "", WS_CHILD | WS_VISIBLE, 116,28,520,20, TNC->hDlg, NULL, hInstance, NULL);

	CreateWindowEx(0, "STATIC", "Mode", WS_CHILD | WS_VISIBLE, 10,50,80,20, TNC->hDlg, NULL, hInstance, NULL);
	TNC->xIDC_MODE = CreateWindowEx(0, "STATIC", "", WS_CHILD | WS_VISIBLE, 116,50,200,20, TNC->hDlg, NULL, hInstance, NULL);
 
	CreateWindowEx(0, "STATIC", "Status", WS_CHILD | WS_VISIBLE, 10,72,110,20, TNC->hDlg, NULL, hInstance, NULL);
	TNC->xIDC_STATE = CreateWindowEx(0, "STATIC", "", WS_CHILD | WS_VISIBLE, 116,72,144,20, TNC->hDlg, NULL, hInstance, NULL);

 	CreateWindowEx(0, "STATIC", "TX/RX State", WS_CHILD | WS_VISIBLE,10,94,80,20, TNC->hDlg, NULL, hInstance, NULL);
	TNC->xIDC_TXRX = CreateWindowEx(0, "STATIC", "", WS_CHILD | WS_VISIBLE,116,94,374,20 , TNC->hDlg, NULL, hInstance, NULL);
 
	CreateWindowEx(0, "STATIC", "Buffers", WS_CHILD | WS_VISIBLE,10,116,80,20, TNC->hDlg, NULL, hInstance, NULL);
	TNC->xIDC_BUFFERS = CreateWindowEx(0, "STATIC", "", WS_CHILD | WS_VISIBLE,116,116,374,20 , TNC->hDlg, NULL, hInstance, NULL);
	
	CreateWindowEx(0, "STATIC", "Traffic", WS_CHILD | WS_VISIBLE,10,138,80,20, TNC->hDlg, NULL, hInstance, NULL);
	TNC->xIDC_TRAFFIC = CreateWindowEx(0, "STATIC", "RX 0 TX 0", WS_CHILD | WS_VISIBLE,116,138,374,20 , TNC->hDlg, NULL, hInstance, NULL);

	TNC->ClientHeight = 213;
	TNC->ClientWidth = 500;

	TNC->hMenu = CreateMenu();
	TNC->hWndMenu = CreatePopupMenu();
	
	MoveWindows(TNC);
#endif

	OpenCOMMPort(TNC, PortEntry->PORTCONTROL.SerialPortName, PortEntry->PORTCONTROL.BAUDRATE, FALSE);

	WritetoConsole("\n");

	return ExtProc;
}

static void CheckRX(struct TNCINFO * TNC)
{
	int Length, Len;

	// only try to read number of bytes in queue 

	if (TNC->RXLen == 500)
		TNC->RXLen = 0;

	Len = ReadCOMBlock(TNC->hDevice, &TNC->RXBuffer[TNC->RXLen], 500 - TNC->RXLen);

	if (Len == 0)
		return;
	
	TNC->RXLen += Len;

	Length = TNC->RXLen;

	// AEA uses SOH ETX Framing

	if (TNC->RXBuffer[0] != SOH)
	{
		// Char Mode Frame I think we need to see cmd: on end

		// If we think we are in host mode, then to could be noise - just discard.

		if (TNC->HostMode)
		{
			if (TNC->ReinitState == 2)
			{
				// Just entered host mode, so could be text command on front

				unsigned char * ptr = strchr(TNC->RXBuffer, SOH);
				
				if (ptr)
				{
					int textlen = ptr - TNC->RXBuffer;

					TNC->RXLen -= textlen;
					Length = TNC->RXLen;

					Debugprintf("%s", TNC->RXBuffer);
					Debugprintf("AEA Entered Host Mode");
					TNC->ReinitState =0; 

					memmove(TNC->RXBuffer, ptr, Length);
					goto hostFrame;
				}
			}

			Debugprintf("AEA Bad Host Frame");
			TNC->RXLen = 0;		// Ready for next frame
			return;
		}

		TNC->RXBuffer[TNC->RXLen] = 0;

//		if (TNC->RXBuffer[TNC->RXLen-2] != ':')
		if (strstr(TNC->RXBuffer, "cmd:") == 0)
		{
			if (strlen(TNC->RXBuffer) < TNC->RXLen)
				TNC->RXLen = 0;							// NULL in text mode message

			return;				// Wait for rest of frame
		}

		// Complete Char Mode Frame

		TNC->RXLen = 0;		// Ready for next frame
					
		ProcessTermModeResponse(TNC);
		return;
	}

	// Receiving a Host Mode frame

	if (TNC->HostMode == 0)	// If we are in Term Mode, discard it. Probably in recovery
	{
		TNC->RXLen = 0;		// Ready for next frame
		return;
	}

hostFrame:

	if (Length < 3)				// Minimum Frame Sise
		return;

	if (TNC->RXBuffer[Length-1] != ETB)
		return;					// Wait till we have a full frame

	if (TNC->RXBuffer[Length-2] == DLE && TNC->RXBuffer[Length-3] != DLE)
		return;					// ??? DLE ETB isn't end of frame, but DLE DLE ETB is

	ProcessHostFrame(TNC, TNC->RXBuffer, Length);	// Could have multiple packets in buffer

	TNC->RXLen = 0;		// Ready for next frame

		
	return;

}

static VOID ProcessHostFrame(struct TNCINFO * TNC, UCHAR * rxbuffer, size_t Len)
{
	UCHAR * FendPtr;
	size_t NewLen;

	//	Split into Packets. By far the most likely is a single packet, so treat as special case
	//  Beware of DLE ETB and DLE DLE ETB!

	FendPtr = memchr(&rxbuffer[1], ETB, Len-1);

FENDLoop:

	if (*(FendPtr - 1) == DLE && *(FendPtr - 2) != DLE)
	{
		FendPtr++;
		FendPtr = memchr(FendPtr, ETB, Len-1);
		goto FENDLoop;
	}
	
	if (FendPtr == &rxbuffer[Len-1])
	{
		ProcessAEAPacket(TNC, &rxbuffer[1], Len - 2);
		return;
	}
		
	// Process the first Packet in the buffer

	NewLen =  FendPtr - rxbuffer -1;

	ProcessAEAPacket(TNC, &rxbuffer[1], NewLen);
	
	// Loop Back

	ProcessHostFrame(TNC, FendPtr+1, Len - NewLen - 2);
	return;

}

static BOOL WriteCommBlock(struct TNCINFO * TNC)
{
	WriteCOMBlock(TNC->hDevice, TNC->TXBuffer, TNC->TXLen);
	TNC->Timeout = 50;
	return TRUE;
}

VOID AEAPoll(int Port)
{
	struct TNCINFO * TNC = TNCInfo[Port];
	struct STREAMINFO * STREAM;
	UCHAR * Poll = TNC->TXBuffer;
	char Status[80];
	int Stream;

	if (TNC->Timeout)
	{
		TNC->Timeout--;
		
		if (TNC->Timeout)			// Still waiting
			return;

		// Timed Out

		if (TNC->HostMode == 0)
		{
			DoTermModeTimeout(TNC);
			return;
		}

		// Timed out in host mode - Clear any connection and reinit the TNC

		TNC->TNCOK = FALSE;
		TNC->HostMode = 0;
		TNC->ReinitState = 0;
				
		sprintf(Status,"%s Open but TNC not responding", TNC->PortRecord->PORTCONTROL.SerialPortName);
		SetWindowText(TNC->xIDC_COMMSSTATE, Status);

		for (Stream = 0; Stream <= MaxStreams; Stream++)
		{
			if (TNC->PortRecord->ATTACHEDSESSIONS[Stream])		// Connected
			{
				TNC->Streams[Stream].Connected = FALSE;		// Back to Command Mode
				TNC->Streams[Stream].ReportDISC = TRUE;		// Tell Nod
			}
		}
	}

	// if we have just restarted or TNC appears to be in terminal mode, run Initialisation Sequence

	if (!TNC->HostMode)
	{
		DoTNCReinit(TNC);
		return;
	}	

	if (TNC->CommandBusy)
		goto Poll;

	// We don't check for a new attach unless Timeout and CommandBusy are both zero, as we need to send a command.

	// If Pactor Session has just been attached, set Pactor Call to the connecting user's callsign


	if (TNC->PortRecord->ATTACHEDSESSIONS[0] && TNC->Streams[0].Attached == 0)
	{
		// New Attach

		int calllen;
		UCHAR TXMsg[1000];
		int datalen;
		char Msg[80];

		TNC->Streams[0].Attached = TRUE;
		TNC->Streams[0].TimeInRX = 0;

		calllen = ConvFromAX25(TNC->PortRecord->ATTACHEDSESSIONS[0]->L4USER, TNC->Streams[0].MyCall);
		TNC->Streams[0].MyCall[calllen] = 0;
		
		datalen = sprintf(TXMsg, "OMf%s", TNC->Streams[0].MyCall);
		EncodeAndSend(TNC, TXMsg, datalen);
		TNC->InternalCmd = 'M';
		TNC->CommandBusy = TRUE;

		sprintf(Status, "In Use by %s", TNC->Streams[0].MyCall);
		SetWindowText(TNC->xIDC_TNCSTATE, Status);

		// Stop Scanning

		sprintf(Msg, "%d SCANSTOP", TNC->Port);
		
		Rig_Command( (TRANSPORTENTRY *) -1, Msg);

		// Shouldn't we also take out of standby mode?? PN is Pactor Listen, for monitoring

		return;

	}
	
	//If sending internal command list, send next element

	if (TNC->CmdSet)
	{
		char * start, * end;
		size_t len;

		start = TNC->CmdSet;
		
		if (*(start) == 0)			// End of Script
		{
			free(TNC->CmdSave);
			TNC->CmdSet = NULL;
		}
		else
		{
			end = strchr(start, 13);
			len = ++end - start -1;	// exclude cr
			TNC->CmdSet = end;
		
			EncodeAndSend(TNC, start, (int)len);
			TNC->InternalCmd = 'X';
			TNC->CommandBusy = TRUE;

			return;
		}
	}

	for (Stream = 0; Stream <= MaxStreams; Stream++)
	{
		STREAM = &TNC->Streams[Stream];

		if (STREAM->Attached)
			CheckForDetach(TNC, Stream, STREAM, TidyClose, ForcedClose, CloseComplete);
	}

	if (TNC->NeedPACTOR)
	{
		TNC->NeedPACTOR--;

		if (TNC->NeedPACTOR == 0)
		{
			EncodeAndSend(TNC, "OPA", 3);	// ??Return to packet mode??
			TNC->CommandBusy = TRUE;

			TNC->CmdSet = TNC->CmdSave = malloc(100);

			sprintf(TNC->CmdSet, "OMf%s\rOPt\rOCETRANS\r", TNC->NodeCall);  // Queue Back to Pactor Standby
			TNC->InternalCmd = 'T';
			TNC->TEXTMODE = FALSE;
			TNC->IntCmdDelay--;

			// Restart Scanning

			sprintf(Status, "%d SCANSTART 15", TNC->Port);
		
			Rig_Command( (TRANSPORTENTRY *) -1, Status);

			return;
		}
	}

	for (Stream = 0; Stream <= MaxStreams; Stream++)
	{
		if (TNC->TNCOK && TNC->Streams[Stream].BPQtoPACTOR_Q && TNC->DataBusy == FALSE)
		{
			int datalen;
			UCHAR TXMsg[1000];
			PMSGWITHLEN buffptr;
			UCHAR * MsgPtr;
			char Status[80];
			
			if (TNC->Streams[Stream].Connected)
			{
				if (Stream == 0)
				{
					// Limit amount in TX

					if (TNC->Streams[0].BytesTXed - TNC->Streams[0].BytesAcked > 200)
						continue;

					// If in IRS state for too long, force turnround

					if (TNC->TXRXState == 'R')
					{
						if (TNC->Streams[0].TimeInRX++ > 15)
						{
							EncodeAndSend(TNC, "OAG", 3);
							TNC->InternalCmd = 'A';
							TNC->CommandBusy = TRUE;
						}
						else
							goto GetStatus;
					}
					TNC->Streams[0].TimeInRX = 0;
				}

				buffptr=Q_REM(&TNC->Streams[Stream].BPQtoPACTOR_Q);
				TNC->Streams[Stream].FramesQueued--;
				datalen=buffptr->Len;
				MsgPtr = buffptr->Data;

				if (TNC->SwallowSignon)
				{
					TNC->SwallowSignon = FALSE;	
					if (strstr(MsgPtr, "Connected"))	// Discard *** connected
					{
						ReleaseBuffer(buffptr);
						return;
					}
				}

				// If in CONV, and data looks binary, switch to TRAN

				TNC->NeedTurnRound = TRUE;		// Sending data, so need turnround at end

				if (TNC->TEXTMODE)
				{
					int i;
					UCHAR j;

					for (i = 0; i < datalen; i++)
					{
						j = MsgPtr[i];

						if (j > 127 ||  j == 26 || j < 10)
						{
							TNC->TEXTMODE = FALSE;
							EncodeAndSend(TNC, "OCETRANS", 8);
							Debugprintf("Switching to TRANS");
							TNC->CommandBusy = TRUE;
							TNC->InternalCmd = 'A';	
							break;
						}
					}
				}

				sprintf(TXMsg, "%c", Stream + ' ');
					
				memcpy(&TXMsg[1], buffptr->Data, datalen);
				
				EncodeAndSend(TNC, TXMsg, datalen + 1);
				ReleaseBuffer(buffptr);
				TNC->Streams[Stream].BytesTXed += datalen; 
				Debugprintf("Stream %d Sending %d, BytesTXED now %d", Stream, datalen, TNC->Streams[Stream].BytesTXed);
				TNC->Timeout = 0;
				TNC->DataBusy = TRUE;

				if (Stream == 0)
					ShowTraffic(TNC);

				if (STREAM->Disconnecting && TNC->Streams[Stream].BPQtoPACTOR_Q == 0)
					TidyClose(TNC, 0);

				return;
			}
			else
			{
				buffptr=Q_REM(&TNC->Streams[Stream].BPQtoPACTOR_Q);
				datalen=buffptr->Len;
				MsgPtr = buffptr->Data;

				// Command. Do some sanity checking and look for things to process locally

				datalen--;				// Exclude CR
				MsgPtr[datalen] = 0;	// Null Terminate
				_strupr(MsgPtr);

				if ((Stream == 0) && memcmp(MsgPtr, "RADIO ", 6) == 0)
				{
					sprintf(&MsgPtr[40], "%d %s", TNC->Port, &MsgPtr[6]);
					if (Rig_Command(TNC->PortRecord->ATTACHEDSESSIONS[0]->L4CROSSLINK, &MsgPtr[40]))
					{
						ReleaseBuffer(buffptr);
					}
					else
					{
						buffptr->Len = sprintf(buffptr->Data, "%s", &MsgPtr[40]);
						C_Q_ADD(&TNC->Streams[Stream].PACTORtoBPQ_Q, buffptr);
					}
					return;
				}

				if (memcmp(MsgPtr, "MODE CONV", 9) == 0)
				{
					TNC->TEXTMODE = TRUE;
					buffptr->Len = sprintf((UCHAR *)buffptr->Data,"AEA} Ok\r");
					C_Q_ADD(&STREAM->PACTORtoBPQ_Q, buffptr);

					EncodeAndSend(TNC, "OCECONV", 7);
					TNC->CommandBusy = TRUE;

					return;
				}

				if (memcmp(MsgPtr, "MODE TRANS", 9) == 0)
				{
					TNC->TEXTMODE = FALSE;
					buffptr->Len = sprintf(buffptr->Data,"AEA} Ok\r");
					C_Q_ADD(&STREAM->PACTORtoBPQ_Q, buffptr);

					EncodeAndSend(TNC, "OCETRANS", 8);
					TNC->CommandBusy = TRUE;

					return;
				}

				if (MsgPtr[0] == 'C' && MsgPtr[1] == ' ' && datalen > 2)	// Connect
				{
					memcpy(TNC->Streams[Stream].RemoteCall, &MsgPtr[2], 9);
					TNC->Streams[Stream].Connecting = TRUE;

					// If Stream 0, Convert C CALL to PACTOR CALL

					if (Stream == 0)
					{
						datalen = sprintf(TXMsg, "%cPG%s", Stream + '@', TNC->Streams[0].RemoteCall);
						sprintf(Status, "%s Connecting to %s",
							TNC->Streams[0].MyCall, TNC->Streams[0].RemoteCall);
						SetWindowText(TNC->xIDC_TNCSTATE, Status);
					}
					else
						datalen = sprintf(TXMsg, "%cCO %s", Stream + '@', TNC->Streams[Stream].RemoteCall);

					EncodeAndSend(TNC, TXMsg, datalen);
					TNC->InternalCmd = 'C';			// So we dont send the reply to the user.
					ReleaseBuffer(buffptr);
					TNC->Streams[Stream].Connecting = TRUE;

					return;
				}

				if (memcmp(MsgPtr, "DISCONNECT", datalen) == 0)	// Disconnect
				{
					if (Stream == 0)
					{
						EncodeAndSend(TNC, "ODI", 3);			// ??Return to packet mode??
						TNC->NeedPACTOR = 50;
						TNC->CommandBusy = TRUE;
					}
					else
					{
						sprintf(TXMsg, "%cDI", Stream + '@');
						EncodeAndSend(TNC, TXMsg, 3);
						TNC->CmdStream = Stream;
					}

					TNC->Streams[Stream].Connecting = FALSE;
					TNC->Streams[Stream].ReportDISC = TRUE;
					ReleaseBuffer(buffptr);

					return;
				}
	
				// Other Command ??

				if (Stream > 0)
					datalen = sprintf(TXMsg, "C20%s", MsgPtr);
				else
					datalen = sprintf(TXMsg, "O%s", MsgPtr);

				EncodeAndSend(TNC, TXMsg, datalen);
				ReleaseBuffer(buffptr);
				TNC->InternalCmd = 0;
				TNC->CommandBusy = TRUE;
				TNC->CmdStream = Stream;
			}
		}
	}

GetStatus:

	// Need to poll data and control channel (for responses to commands)

	// Also check status if we have data buffered (for flow control)

	if (TNC->TNCOK)
	{
		if (TNC->IntCmdDelay <= 0)
		{
			EncodeAndSend(TNC, "OOP", 3);
			TNC->InternalCmd = 'S';
			TNC->CommandBusy = TRUE;
			TNC->IntCmdDelay = 9;	// Every second
			return;
		}
		else
			TNC->IntCmdDelay--;
	}

Poll:
	// Nothing doing - send Poll (but not too often)

	TNC->PollDelay++;

	if (TNC->PollDelay < 3)
		return;

	TNC->PollDelay = 0;

	EncodeAndSend(TNC, "OGG", 3);			// Poll

	return;
}

static VOID DoTNCReinit(struct TNCINFO * TNC)
{
	UCHAR * Poll = TNC->TXBuffer;

	if (TNC->ReinitState == 1)		// Forcing back to Term
		TNC->ReinitState = 0;		// Got Response, so must be back in term mode

	if (TNC->ReinitState == 0)
	{
		// Just Starting - Send a CR to see if in Terminal or Host Mode

		char Status[80];
		
		sprintf(Status,"%s Initialising TNC", TNC->PortRecord->PORTCONTROL.SerialPortName);
		SetWindowText(TNC->xIDC_COMMSSTATE, Status);

		Poll[0] = 13;
		TNC->TXLen = 1;
		TNC->RXLen = 0;

		WriteCommBlock(TNC);

		return;
	}

	if (TNC->ReinitState == 2)		// In Term State, Sending Initialisation Commands
	{
		char * start, * end;
		size_t len;

		start = TNC->InitPtr;
		
		if (*(start) == 0)			// End of Script
		{
			// Put into Host Mode


			Poll[0] = 0x11;		// XON
			Poll[1] = 0x18;		// CAN
			Poll[2] = 0x03;		// COM

			memcpy(&Poll[3], "HOST Y\r", 7);

			TNC->TXLen = 10;
			WriteCommBlock(TNC);
			TNC->Timeout = 0;
			TNC->CommandBusy = FALSE;
			TNC->DataBusy = FALSE;

			TNC->HostMode = TRUE;		// Should now be in Host Mode
			TNC->NeedPACTOR = 50;		// Need to Send PACTOR command after 5 secs

			return;
		}
		
		end = strchr(start, 13);
		len = ++end - start;
		TNC->InitPtr = end;
		memcpy(Poll, start, len);

		TNC->TXLen = (int)len;
		WriteCommBlock(TNC);


		return;

	}
}

static VOID DoTermModeTimeout(struct TNCINFO * TNC)
{
	UCHAR * Poll = TNC->TXBuffer;

	if (TNC->ReinitState == 0)
	{
		//Checking if in Terminal Mode - Try to set back to Term Mode

		TNC->ReinitState = 1;

		EncodeAndSend(TNC, "OHON", 4);		// HOST N
		TNC->Timeout = 20;
		return;
	}
	if (TNC->ReinitState == 1)
	{
		// Forcing back to Term Mode

		TNC->ReinitState = 0;
		DoTNCReinit(TNC);				// See if worked
		return;
	}
}

static VOID ProcessTermModeResponse(struct TNCINFO * TNC)
{
	UCHAR * Poll = TNC->TXBuffer;

	Debugprintf("AEA Initstate %d Response %s", TNC->ReinitState, TNC->RXBuffer);

	if (TNC->ReinitState == 0 || TNC->ReinitState == 1) 
	{
		// Testing if in Term Mode. It is, so can now send Init Commands

		TNC->InitPtr = TNC->InitScript;
		TNC->ReinitState = 2;
		DoTNCReinit(TNC);		// Send First Command
		return;
	}
	if (TNC->ReinitState == 2)
	{
		// Sending Init Commands

		DoTNCReinit(TNC);		// Send Next Command
		return;
	}
}

static VOID ProcessAEAPacket(struct TNCINFO * TNC, UCHAR * Msg, size_t Len)
{
	PMSGWITHLEN buffptr;
	char * Buffer = &Msg[1];			// Data portion of frame
	char * Call;
	char Status[80];
	int Stream = 0;
	int Opcode;
	struct STREAMINFO * STREAM;

	// Any valid frame is an ACK

	TNC->TNCOK = TRUE;
	TNC->Timeout = 0;

	Len = DLEDecode(Msg, Msg, Len);		// Remove KISS transparency

	Stream = Msg[0] & 15;
	Opcode = Msg[0] >> 4;

	STREAM = &TNC->Streams[Stream];

	if (Msg[0] == 'O' && Msg[1] == 'G' && Msg[2] == 'G')
	{
		if (Msg[3] == 0)
		{
			// OK Response

			sprintf(Status,"%s TNC link OK", TNC->PortRecord->PORTCONTROL.SerialPortName);
			SetWindowText(TNC->xIDC_COMMSSTATE, Status);

			return;
		}
	}

	if (Msg[0] == '/')			// 2F
	{
		char * Eptr;
		
		// Echoed Data

		Len--;

		Eptr = memchr(Buffer, 0x1c, Len);

		if (Eptr) 
			Debugprintf("Echoed 1c followed by %x", *(++Eptr));

		TNC->Streams[0].BytesAcked += (int)Len;

		Debugprintf("Ack for %d, BytesAcked now %d", Len, TNC->Streams[0].BytesAcked);
		ShowTraffic(TNC);

		// If nothing more to send, turn round link
						
		if ((TNC->Streams[0].BPQtoPACTOR_Q == 0) && TNC->NeedTurnRound &&
			(TNC->Streams[0].BytesAcked >= TNC->Streams[0].BytesTXed))		// Nothing following and all acked
			{
				Debugprintf("AEA Sent = Acked - sending Turnround");
						
				if (TNC->TEXTMODE == 0)
				{
					// In Trans - switch back

					TNC->TEXTMODE = TRUE;
					EncodeAndSend(TNC, "OCECONV", 7);
					Debugprintf("Switching to CONV");
					TNC->CommandBusy = TRUE;
					TNC->InternalCmd = 'A';	
					TNC->NeedTRANS = TRUE;
				}
					
				TNC->NeedTurnRound = FALSE;
				EncodeAndSend(TNC, OverMsg, 2);
				TNC->Timeout = 0;						//  No response to data
		}
		return;
	}

	if (Opcode == 3)
	{
		// Received Data

		// Pass to Appl

		buffptr = GetBuff();
		if (buffptr == NULL) return;	// No buffers, so ignore

		Len--;							// Remove Header

		buffptr->Len = Len;				// Length
		TNC->Streams[Stream].BytesRXed += (int)Len;
		memcpy(&buffptr->Data[0], Buffer, Len);
		C_Q_ADD(&TNC->Streams[Stream].PACTORtoBPQ_Q, buffptr);

		if (Stream == 0)
			ShowTraffic(TNC);

		return;
	}


	if (Opcode == 4)
	{
		// Link Status or Command Response

		TNC->CommandBusy = FALSE;

		if (TNC->InternalCmd)
		{
			// Process it

			if (TNC->InternalCmd == 'S')		// Status
			{
//				if (Msg[3] == 'P' && Msg[4] == 'G')
				{
					SetWindowText(TNC->xIDC_STATE, status[Msg[5] - 0x30]);
					
					TNC->TXRXState = Msg[6];

					if (Msg[6] == 'S')
						SetWindowText(TNC->xIDC_TXRX, "Sender");
					else
						SetWindowText(TNC->xIDC_TXRX, "Receiver");

					Msg[12] = 0;
					SetWindowText(TNC->xIDC_MODE, Msg);

					// Testing.. I think ZF returns buffers

					EncodeAndSend(TNC, "OZF", 3);
					TNC->InternalCmd = 'Z';
					TNC->CommandBusy = TRUE;
				}
			
				return;
			}

			if (TNC->InternalCmd == 'Z')		// Buffers?
			{
				Msg[Len] = 0;
				SetWindowText(TNC->xIDC_BUFFERS, &Msg[3]);
				return;
			}

			return;
		}

		// Reply to Manual command - Pass to Appl

		Stream = TNC->CmdStream;
		STREAM = &TNC->Streams[Stream];


		buffptr = GetBuff();

		if (buffptr == NULL) return;			// No buffers, so ignore

		Buffer[Len - 1] = 13;
		Buffer[Len] = 0;

		buffptr->Len = sprintf(&buffptr->Data[0],"AEA} %s", Buffer);

		C_Q_ADD(&TNC->Streams[Stream].PACTORtoBPQ_Q, buffptr);

		return;

	}

	if (Opcode == 5)
	{
		// Link Messages (Connect, etc)

		if (Stream == 15)
		{
			// SOH $5F X X $00 ETB data acknowledgement 

			if (Msg[1] == 'X' && Msg[2] == 'X' && Msg[3] == 0)
			{
				TNC->DataBusy = FALSE;

				if (TNC->NeedTRANS)		// Sent CTRL/Z in conv mode - switch back to trans
				{
					TNC->NeedTRANS = FALSE;
					TNC->TEXTMODE = FALSE;
					EncodeAndSend(TNC, "OCETRANS", 8);
					Debugprintf("Switching to TRANS");
					TNC->CommandBusy = TRUE;
					TNC->InternalCmd = 'A';	
				}
				else
					EncodeAndSend(TNC, "OGG", 3);			// Send another Poll
			}
			return;
		}

		if (strstr(Buffer, "DISCONNECTED") || strstr(Buffer, "Timeout"))
		{
			if ((TNC->Streams[Stream].Connecting | TNC->Streams[Stream].Connected) == 0)
			{
				// Not connected or Connecting. Probably response to going into Pactor Listen Mode

				return;
			}
	
			if (STREAM->Connecting && STREAM->Disconnecting == FALSE)
			{
				// Connect Failed
			
				buffptr = GetBuff();
				if (buffptr == 0) return;			// No buffers, so ignore

				buffptr->Len = sprintf(&buffptr->Data[0], "*** Failure with %s\r", TNC->Streams[Stream].RemoteCall);

				C_Q_ADD(&TNC->Streams[Stream].PACTORtoBPQ_Q, buffptr);
	
				TNC->Streams[Stream].Connecting = FALSE;
				TNC->Streams[Stream].Connected = FALSE;				// In case!
				TNC->Streams[Stream].FramesQueued = 0;

				return;
			}

			// Connected, or Disconnecting - Release Session

			TNC->Streams[Stream].Connecting = FALSE;
			TNC->Streams[Stream].Connected = FALSE;		// Back to Command Mode
			TNC->Streams[Stream].FramesQueued = 0;

			if (STREAM->Disconnecting == FALSE)
				STREAM->ReportDISC = TRUE;		// Tell Node

			STREAM->Disconnecting = FALSE;

			// Need to reset Pactor Call in case it was changed

			TNC->NeedPACTOR = 20;

			if (Stream == 0)
			{
				// Claar any data from buffers 

				EncodeAndSend(TNC, "OTC", 3);			// Clear buffers
				TNC->NeedPACTOR = 20;
				TNC->InternalCmd = 'T';
				TNC->CommandBusy = TRUE;
			}

			return;
		}

		Call = strstr(Buffer, "NNECTED to");

		if (Call)
		{	
			Call+=11;					// To Callsign
			
			if (Stream == 0)
			{
				Buffer[Len-2] = 0;
			}

			TNC->Streams[Stream].BytesRXed = TNC->Streams[Stream].BytesTXed = TNC->Streams[Stream].BytesAcked = 0;
			TNC->Streams[Stream].ConnectTime = time(NULL); 

			if (Stream == 0)
			{
				// Stop Scanner

				char Msg[80];
				
				sprintf(Msg, "%d SCANSTOP", TNC->Port);

				Rig_Command( (TRANSPORTENTRY *) -1, Msg);

				ShowTraffic(TNC);

			}

			if (TNC->PortRecord->ATTACHEDSESSIONS[Stream] == 0)
			{
				// Incoming Connect

				ProcessIncommingConnect(TNC, Call, Stream, TRUE);

				if (Stream == 0)
				{
					struct WL2KInfo * WL2K = TNC->WL2K;
					char FreqAppl[10] = "";				// Frequecy-specific application
	
					if (TNC->RIG && TNC->RIG != &TNC->DummyRig)
					{
						// If Scan Entry has a Appl, save it

						if (TNC->RIG->FreqPtr && TNC->RIG->FreqPtr[0]->APPL[0])
							strcpy(FreqAppl, &TNC->RIG->FreqPtr[0]->APPL[0]);
						}

					// We are going to Send something, so turn link round
				
					EncodeAndSend(TNC, "OAG", 3);
					TNC->InternalCmd = 'A';
					TNC->CommandBusy = TRUE;
				
					sprintf(Status, "%s Connected to %s Inbound", TNC->Streams[0].RemoteCall, TNC->NodeCall);
					SetWindowText(TNC->xIDC_TNCSTATE, Status);

					// If an autoconnect APPL is defined, send it

					if (FreqAppl[0])				// Frequency specific APPL overrides TNC APPL
					{
						buffptr = GetBuff();
						if (buffptr == 0) return;	// No buffers, so ignore

						buffptr->Len = sprintf(&buffptr->Data[0], "%s\r", FreqAppl);
						C_Q_ADD(&TNC->Streams[Stream].PACTORtoBPQ_Q, buffptr);
						TNC->SwallowSignon = TRUE;
						return;
					}

					if (TNC->ApplCmd)
					{
						buffptr = GetBuff();
						if (buffptr == 0) return;			// No buffers, so ignore

						buffptr->Len = sprintf(&buffptr->Data[0], "%s\r", TNC->ApplCmd);
						C_Q_ADD(&TNC->Streams[Stream].PACTORtoBPQ_Q, buffptr);
												
						TNC->SwallowSignon = TRUE;

						return;
					}
				}

				if (FULL_CTEXT && HFCTEXTLEN == 0)
				{
					char CTBuff[300];
					int Len = CTEXTLEN, CTPaclen = 50;
					int Next = 0;

					CTBuff[0] = Stream + ' ';

					while (Len > CTPaclen)		// CTEXT Paclen
					{
						memcpy(&CTBuff[1], &CTEXTMSG[Next], CTPaclen);
						EncodeAndSend(TNC, CTBuff, CTPaclen + 1);
						Next += CTPaclen;
						Len -= CTPaclen;
					}

					memcpy(&CTBuff[1], &CTEXTMSG[Next], Len);
					EncodeAndSend(TNC, CTBuff, Len + 1);
				}
				return;

			}
			else
			{
				// Connect Complete
			
				buffptr = GetBuff();
				if (buffptr == 0) return;			// No buffers, so ignore

				buffptr->Len  = sprintf(&buffptr->Data[0], "*** Connected to %s\r", Call);;

				C_Q_ADD(&TNC->Streams[Stream].PACTORtoBPQ_Q, buffptr);
	
				TNC->Streams[Stream].Connecting = FALSE;
				TNC->Streams[Stream].Connected = TRUE;			// Subsequent data to data channel
	
				if (Stream == 0)
				{
					sprintf(Status, "%s Connected to %s Outbound", TNC->NodeCall, TNC->Streams[0].RemoteCall);
					SetWindowText(TNC->xIDC_TNCSTATE, Status);
					UpdateMH(TNC, Call, '+', 'O');
				}

				return;
			}
		}
	}	
}


int	DLEDecode(UCHAR * inbuff, UCHAR * outbuff, size_t len)
{
	unsigned int i, txptr = 0;
	UCHAR c;

	for (i=0; i<len; i++)
	{
		c = inbuff[i];

		if (c == DLE)
			c = inbuff[++i];

		outbuff[txptr++] = c;
	}

	return txptr;

}

static VOID EncodeAndSend(struct TNCINFO * TNC, UCHAR * txbuffer, int Len)
{
	// Send A Packet With DLE Encoding Encoding

	TNC->TXLen = DLEEncode(txbuffer, TNC->TXBuffer, Len);

	WriteCommBlock(TNC);
}

static int DLEEncode(UCHAR * inbuff, UCHAR * outbuff, size_t len)
{
	unsigned int i, txptr = 0;
	UCHAR c;

	outbuff[0] = SOH;
	txptr=1;

	for (i=0; i<len; i++)
	{
		c = inbuff[i];
		
		switch (c)
		{
		case DLE:
		case SOH:
		case ETB:

			outbuff[txptr++] = DLE;
//			Debugprintf("Escaping %x", c);
		}
		
		outbuff[txptr++] = c;
	}

	outbuff[txptr++] = ETB;

	return txptr;

}


VOID TidyClose(struct TNCINFO * TNC, int Stream)
{
	if (Stream == 0)					// Pactor Stream
	{
		EncodeAndSend(TNC, "ODI", 3);	// Disconnect

		TNC->InternalCmd = 'P';
		TNC->CommandBusy = TRUE;
	}
	else
	{
		UCHAR TXMsg[10];

		sprintf(TXMsg, "%cDI", Stream + '@');
		EncodeAndSend(TNC, TXMsg, 4);		// Send twice - must force a disconnect
	}
}

VOID ForcedClose(struct TNCINFO * TNC, int Stream)
{
	TidyClose(TNC, Stream);			// Send DI again - can't do much else
}

VOID CloseComplete(struct TNCINFO * TNC, int Stream)
{
	TNC->NeedPACTOR = 50;	
}