File: gnu_io_RXTXPort.cpp

package info (click to toggle)
rxtx 2.2.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 6,868 kB
  • sloc: ansic: 14,337; sh: 10,247; java: 7,418; cpp: 2,687; makefile: 142
file content (1649 lines) | stat: -rw-r--r-- 49,749 bytes parent folder | download | duplicates (6)
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
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
/*-------------------------------------------------------------------------
|   RXTX License v 2.1 - LGPL v 2.1 + Linking Over Controlled Interface.
|   RXTX is a native interface to serial ports in java.
|   Copyright 2002-2004 Michal Hobot MichalHobot@netscape.net
|   Copyright 1997-2007 by Trent Jarvi tjarvi@qbang.org and others who
|   actually wrote it.  See individual source files for more information.
|
|   A copy of the LGPL v 2.1 may be found at
|   http://www.gnu.org/licenses/lgpl.txt on March 4th 2007.  A copy is
|   here for your convenience.
|
|   This library is free software; you can redistribute it and/or
|   modify it under the terms of the GNU Lesser General Public
|   License as published by the Free Software Foundation; either
|   version 2.1 of the License, or (at your option) any later version.
|
|   This library 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
|   Lesser General Public License for more details.
|
|   An executable that contains no derivative of any portion of RXTX, but
|   is designed to work with RXTX by being dynamically linked with it,
|   is considered a "work that uses the Library" subject to the terms and
|   conditions of the GNU Lesser General Public License.
|
|   The following has been added to the RXTX License to remove
|   any confusion about linking to RXTX.   We want to allow in part what
|   section 5, paragraph 2 of the LGPL does not permit in the special
|   case of linking over a controlled interface.  The intent is to add a
|   Java Specification Request or standards body defined interface in the 
|   future as another exception but one is not currently available.
|
|   http://www.fsf.org/licenses/gpl-faq.html#LinkingOverControlledInterface
|
|   As a special exception, the copyright holders of RXTX give you
|   permission to link RXTX with independent modules that communicate with
|   RXTX solely through the Sun Microsytems CommAPI interface version 2,
|   regardless of the license terms of these independent modules, and to copy
|   and distribute the resulting combined work under terms of your choice,
|   provided that every copy of the combined work is accompanied by a complete
|   copy of the source code of RXTX (the version of RXTX used to produce the
|   combined work), being distributed under the terms of the GNU Lesser General
|   Public License plus this exception.  An independent module is a
|   module which is not derived from or based on RXTX.
|
|   Note that people who make modified versions of RXTX are not obligated
|   to grant this special exception for their modified versions; it is
|   their choice whether to do so.  The GNU Lesser General Public License
|   gives permission to release a modified version without this exception; this
|   exception also makes it possible to release a modified version which
|   carries forward this exception.
|
|   You should have received a copy of the GNU Lesser General Public
|   License along with this library; if not, write to the Free
|   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
|   All trademarks belong to their respective owners.
--------------------------------------------------------------------------*/
#include "StdAfx.h"
#include "rxtxHelpers.h"

/*
Initialize

   accept:      none
   perform:     Initialize the native library
   return:      none
   exceptions:  none
   comments:
 * Class:     gnu_io_RXTXPort
 * Method:    Initialize
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_Initialize(JNIEnv *env, jclass cls)
{
}

/*
open

   accept:      The device to open. ie "COM1:"
   perform:     open the device
   return:      handle
   exceptions:  IOExcepiton
   comments:    Very often people complain about not being able to get past
                this function and it turns out to be permissions on the
                device file or bios has the device disabled.
 * Class:     gnu_io_RXTXPort
 * Method:    open
 * Signature: (Ljava/lang/String{ })I
 */
JNIEXPORT jint JNICALL Java_gnu_io_RXTXPort_open(JNIEnv *env, jobject jobj, jstring name)
{
  DCB PortDCB;
  COMMTIMEOUTS CommTimeouts;
  LPCWSTR lpMsgBuf;
  EventInfoStruct *EventInfo;
  DWORD dwErr;

  LPCWSTR wszName = env->GetStringChars(name, NULL);
  HANDLE hPort = CreateFileW(wszName,      // Pointer to the name of the port
                             GENERIC_READ | GENERIC_WRITE,// Access (read-write) mode
                             0,            // Share mode
                             NULL,         // Pointer to the security attribute
                             OPEN_EXISTING,// How to open the serial port
                             0,            // Port attributes
                             NULL);        // Handle to port with attribute to copy
  // If it fails to open the port, return FALSE.
  if ( hPort == INVALID_HANDLE_VALUE )
  { // Could not open the port.
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, PORT_IN_USE_EXCEPTION, L"open - CreateFile", lpMsgBuf );
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    env->ReleaseStringChars(name, wszName);
    return (jint)INVALID_HANDLE_VALUE;
  }


  PortDCB.DCBlength = sizeof (DCB);

  // Get the default port setting information.
  GetCommState(hPort, &PortDCB);

  // Change the DCB structure settings.
  PortDCB.fBinary = TRUE;               // Binary mode; no EOF check
  PortDCB.fParity = TRUE;               // Enable parity checking
  PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control
  PortDCB.fDtrControl = DTR_CONTROL_HANDSHAKE;// DTR flow control type
  PortDCB.fDsrSensitivity = FALSE;      // DSR sensitivity
  PortDCB.fTXContinueOnXoff = TRUE;     // XOFF continues Tx
  PortDCB.fErrorChar = FALSE;           // Disable error replacement
  PortDCB.fNull = FALSE;                // Disable null stripping
  PortDCB.fRtsControl = RTS_CONTROL_ENABLE;// RTS flow control
  PortDCB.fAbortOnError = FALSE;        // Do not abort reads/writes on error

  // Configure the port according to the specifications of the DCB structure.
  if (!SetCommState(hPort, &PortDCB))
  { // Could not set comm port state
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, PORT_IN_USE_EXCEPTION, L"open - SetCommState", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    env->ReleaseStringChars(name, wszName);
    return (jint)INVALID_HANDLE_VALUE;
  }

  // Retrieve the time-out parameters for all read and write operations
  // on the port.
  GetCommTimeouts(hPort, &CommTimeouts);

  // Change the COMMTIMEOUTS structure settings.
  CommTimeouts.ReadIntervalTimeout = 0;
  CommTimeouts.ReadTotalTimeoutMultiplier = 0;
  CommTimeouts.ReadTotalTimeoutConstant = MAXDWORD;
  CommTimeouts.WriteTotalTimeoutMultiplier = 10;
  CommTimeouts.WriteTotalTimeoutConstant = 1000;

  // Set the time-out parameters for all read and write operations
  // on the port.
  if (!SetCommTimeouts(hPort, &CommTimeouts))
  { // Unable to set the time-out parameters
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, PORT_IN_USE_EXCEPTION, L"open - SetCommTimeouts", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    env->ReleaseStringChars(name, wszName);
    return (jint)INVALID_HANDLE_VALUE;
  }

  // SETRTS: Sends the RTS (request-to-send) signal.
  EscapeCommFunction(hPort, SETRTS);


  if(dwErr = InitialiseEventInfoStruct(hPort, &EventInfo))
  { // Unable to set up EventInfo structure for event processing
    CreateErrorMsg(dwErr, lpMsgBuf);
    throw_java_exceptionW(env, IO_EXCEPTION, L"open - InitialiseEventInfoStruct", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    env->ReleaseStringChars(name, wszName);
    return (jint)INVALID_HANDLE_VALUE;
  }

  jclass cls = env->GetObjectClass(jobj);
  jfieldID jfEis = env->GetFieldID(cls, "eis", "I");
	if( !jfEis ) {
    IF_DEBUG
    (
		  env->ExceptionDescribe();
    )
		env->ExceptionClear();
    // Free the buffers.
    env->ReleaseStringChars(name, wszName);
		return (jint)INVALID_HANDLE_VALUE;
	}
	env->SetIntField(jobj, jfEis, (jint)EventInfo);

  env->ReleaseStringChars(name, wszName);
  // Returning HANDLE (which is a pointer) as file descriptor... Anyway, 32 bits are 32 bits
  return (jint)hPort;
}


/*
 nativeSetSerialPortParams

   accept:     speed, data bits, stop bits, parity
   perform:    set the serial port parameters
   return:     void
   exceptions: UnsupportedCommOperationException
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetSerialPortParams
 * Signature: (IIII)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_nativeSetSerialPortParams(JNIEnv *env, jobject jobj, jint speed, jint dataBits, jint stopBits, jint parity)
{
  DCB PortDCB;
  LPCWSTR lpMsgBuf;

  HANDLE hPort = get_fd(env, jobj);
  PortDCB.DCBlength = sizeof(DCB);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.nativeSetSerialPortParams(%ld, %ld, %ld, %ld) called\n", speed, dataBits, stopBits, parity);
  )

  // Get the default port setting information.
  if(!GetCommState(hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetSerialPortParams - GetCommState", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return;
  }

  // Change the DCB structure settings.
  PortDCB.BaudRate = speed;             // Current baud
  PortDCB.ByteSize = (BYTE)dataBits;    // Number of bits/byte, 4-8
  PortDCB.Parity = (BYTE)parity;        // 0-4=no,odd,even,mark,space
  switch(stopBits)
  {
    case gnu_io_RXTXPort_STOPBITS_1:
      PortDCB.StopBits = ONESTOPBIT;
      break;

    case gnu_io_RXTXPort_STOPBITS_2:
      PortDCB.StopBits = TWOSTOPBITS;
      break;

    case gnu_io_RXTXPort_STOPBITS_1_5:
      PortDCB.StopBits = ONE5STOPBITS;
      break;

    default:
      throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetSerialPortParams", L"Incorrect stopBits");

  }

  // Configure the port according to the specifications of the DCB structure.
  if (!SetCommState (hPort, &PortDCB))
  { //Unable to configure the serial port
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetSerialPortParams - SetCommState", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return;
  }

}

/*
setflowcontrol

   accept:      flowmode
	FLOWCONTROL_NONE        none
	FLOWCONTROL_RTSCTS_IN   hardware flow control
	FLOWCONTROL_RTSCTS_OUT         ""
	FLOWCONTROL_XONXOFF_IN  input software flow control
	FLOWCONTROL_XONXOFF_OUT output software flow control
   perform:     set flow control to flowmode
   return:      none
   exceptions:  UnsupportedCommOperationException
   comments:  there is no differentiation between input and output hardware
              flow control
 * Class:     gnu_io_RXTXPort
 * Method:    setflowcontrol
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_setflowcontrol(JNIEnv *env, jobject jobj, jint flowcontrol)
{
  DCB PortDCB;
  LPCWSTR lpMsgBuf;

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.setflowcontrol(%ld) called\n", flowcontrol);
  )

  HANDLE hPort = get_fd(env, jobj);

  PortDCB.DCBlength = sizeof(DCB);
  if(!GetCommState (hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"setflowcontrol - GetCommState", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return;
  }

  if(flowcontrol & (gnu_io_RXTXPort_FLOWCONTROL_RTSCTS_IN | gnu_io_RXTXPort_FLOWCONTROL_RTSCTS_OUT))
    PortDCB.fRtsControl = RTS_CONTROL_HANDSHAKE;
  else
    PortDCB.fRtsControl = RTS_CONTROL_ENABLE;

  if(flowcontrol & gnu_io_RXTXPort_FLOWCONTROL_RTSCTS_OUT)
    PortDCB.fOutxCtsFlow = TRUE;
  else
    PortDCB.fOutxCtsFlow = FALSE;

  if(flowcontrol & gnu_io_RXTXPort_FLOWCONTROL_XONXOFF_IN)
    PortDCB.fInX = TRUE;
  else
    PortDCB.fInX = FALSE;

  if(flowcontrol & gnu_io_RXTXPort_FLOWCONTROL_XONXOFF_OUT)
    PortDCB.fOutX = TRUE;
  else
    PortDCB.fOutX = FALSE;

  // Configure the port according to the specifications of the DCB structure.
  if (!SetCommState (hPort, &PortDCB))
  { // Could not set params
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"setflowcontrol - SetCommState", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return;
  }
}

/*
NativegetReceiveTimeout

   accept:     none
   perform:    get termios.c_cc[VTIME]
   return:     VTIME
   comments:   see  NativeEnableReceiveTimeoutThreshold
 * Class:     gnu_io_RXTXPort
 * Method:    NativegetReceiveTimeout
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_gnu_io_RXTXPort_NativegetReceiveTimeout(JNIEnv *env, jobject jobj)
{
  COMMTIMEOUTS CommTimeouts;
  LPCWSTR lpMsgBuf;
  HANDLE hPort = get_fd(env, jobj);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.NativegetReceiveTimeout() called\n");
  )

  // Retrieve the time-out parameters for all read and write operations on the port.
  if (!GetCommTimeouts(hPort, &CommTimeouts))
  { // Unable to get the time-out parameters
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, IO_EXCEPTION, L"NativegetReceiveTimeout - GetCommTimeouts", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return -1;
  }

  // As far as I know c_cc is byte table
  return CommTimeouts.ReadIntervalTimeout/100 <= 255 ? CommTimeouts.ReadIntervalTimeout / 100 : 255;
}

/*
NativeisReceiveTimeoutEnabled

   accept:     none
   perform:    determine if VTIME is none 0
   return:     JNI_TRUE if VTIME > 0 else JNI_FALSE
   comments:   see  NativeEnableReceiveTimeoutThreshold
 * Class:     gnu_io_RXTXPort
 * Method:    NativeisReceiveTimeoutEnabled
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_NativeisReceiveTimeoutEnabled(JNIEnv *env, jobject jobj)
{
  COMMTIMEOUTS CommTimeouts;
  LPCWSTR lpMsgBuf;
  HANDLE hPort = get_fd(env, jobj);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.NativeisReceiveTimeoutEnabled() called\n");
  )

  // Retrieve the time-out parameters for all read and write operations
  // on the port.
  if (!GetCommTimeouts(hPort, &CommTimeouts))
  { // Unable to get the time-out parameters
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, IO_EXCEPTION, L"NativeisReceiveTimeoutEnabled - GetCommTimeouts", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return -1;
  }

  return CommTimeouts.ReadIntervalTimeout || CommTimeouts.ReadTotalTimeoutConstant || CommTimeouts.ReadTotalTimeoutMultiplier ? JNI_TRUE : JNI_FALSE;
}

/*
NativeEnableReceiveTimeoutThreshold
   accept:      int  threshold, int vtime,int buffer
   perform:     Set c_cc->VMIN to threshold and c_cc=>VTIME to vtime
   return:      void
   exceptions:  IOException
   comments:    This is actually all handled in read with select in
                canonical input mode.
 * Class:     gnu_io_RXTXPort
 * Method:    NativeEnableReceiveTimeoutThreshold
 * Signature: (III)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_NativeEnableReceiveTimeoutThreshold(JNIEnv *env, jobject jobj, jint time, jint threshold, jint InputBuffer)
{
  COMMTIMEOUTS CommTimeouts;
  LPCWSTR lpMsgBuf;
  HANDLE hPort = get_fd(env, jobj);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.NativeEnableReceiveTimeoutThreshold(%ld, %ld) called\n", time, threshold);
  )

  // Retrieve the time-out parameters for all read and write operations
  // on the port.
  if (!GetCommTimeouts(hPort, &CommTimeouts))
  { // Unable to get the time-out parameters
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, IO_EXCEPTION, L"NativeEnableReceiveTimeoutThreshold - GetCommTimeouts", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return;
  }

  /* ------ from javax.comm.CommPort javadoc -------------------------------------------------------------
  |    Threshold   |    Timeout   |Read Buffer Size | Read Behaviour
  |State   |Value  |State   |Value|                 |
  |disabled|  -    |disabled| -   |    n bytes      | block until any data is available
  |enabled |m bytes|disabled| -   |    n bytes      | block until min(m,n) bytes are available
  |disabled|  -    |enabled |x ms |    n bytes      | block for x ms or until any data is available
  |enabled |m bytes|enabled |x ms |    n bytes      | block for x ms or until min(m,n) bytes are available
  --------------------------------------------------------------------------------------------------------

  Enabling the Timeout OR Threshold with a value a zero is a special case.
  This causes the underlying driver to poll for incoming data instead being event driven.
  Otherwise, the behaviour is identical to having both the Timeout and Threshold disabled.
  */

  // Following is based on my understanding of timeout parameters meaning.
  // Not completely precise (threshold?!)

  if(time == 0)
  { // polling mode - return if no data
    CommTimeouts.ReadIntervalTimeout = MAXDWORD;
    CommTimeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
    CommTimeouts.ReadTotalTimeoutConstant = 1;
  }
  else if(time == -1)
  { // disable timeout
    CommTimeouts.ReadIntervalTimeout = 0;
    CommTimeouts.ReadTotalTimeoutMultiplier = 0;
    CommTimeouts.ReadTotalTimeoutConstant = 0;
  }
  else
  { // set timeout
    CommTimeouts.ReadIntervalTimeout = 0;
    CommTimeouts.ReadTotalTimeoutMultiplier = 0;
    CommTimeouts.ReadTotalTimeoutConstant = time;
  }

  // Set the time-out parameters for all read and write operations
  // on the port.
  if (!SetCommTimeouts (hPort, &CommTimeouts))
  { // Unable to set the time-out parameters
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, IO_EXCEPTION, L"NativeEnableReceiveTimeoutThreshold - SetCommTimeouts", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return;
  }
}

/*
isDTR

   accept:      none
   perform:     check status of DTR
   return:      true if TIOCM_DTR is set
                false if TIOCM_DTR is not set
   exceptions:  none
   comments:    DTR stands for Data Terminal Ready
 * Class:     gnu_io_RXTXPort
 * Method:    isDTR
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_isDTR(JNIEnv *env, jobject jobj)
{
  DCB PortDCB;
  HANDLE hPort = get_fd(env, jobj);

  PortDCB.DCBlength = sizeof(DCB);

  // Get the default port setting information.
  if(!GetCommState(hPort, &PortDCB))
  {
    GetLastError();
    return JNI_FALSE;
  }

  // This is not completely correct: I assume that nobody's playing with
  // manually setting/resetting DTR. Instead, DTR is in handshake mode (ON unless
  // port closed) or disable mode (OFF).
  // So, don't use EscapeCommFunction(SETDTR/CLRDTR) in this library!
  return PortDCB.fDtrControl != DTR_CONTROL_DISABLE ? JNI_TRUE : JNI_FALSE;
}

/*
setDTR

   accept:      new DTR state
   perform:     if state is true, TIOCM_DTR is set
                if state is false, TIOCM_DTR is unset
   return:      none
   exceptions:  none
   comments:    DTR stands for Data Terminal Ready
 * Class:     gnu_io_RXTXPort
 * Method:    setDTR
 * Signature: (Z)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_setDTR(JNIEnv *env, jobject jobj, jboolean state)
{
  DCB PortDCB;

  HANDLE hPort = get_fd(env, jobj);
  PortDCB.DCBlength = sizeof(DCB);

  // Don't use EscapeCommFunction(SETDTR/CLRDTR) in this library!

  // Get the default port setting information.
  if(!GetCommState (hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    GetLastError();
    return;
  }

  if(state == JNI_TRUE)
    PortDCB.fDtrControl = DTR_CONTROL_HANDSHAKE;
  else
    PortDCB.fDtrControl = DTR_CONTROL_DISABLE;


  // Configure the port according to the specifications of the DCB structure.
  if (!SetCommState (hPort, &PortDCB))
  { //Unable to configure the serial port
    GetLastError();
    return;
  }
}

/*
setRTS

   accept:      state  flag to set/unset.
   perform:     depends on the state flag
                if true TIOCM_RTS is set
                if false TIOCM_RTS is unset
   return:      none
   exceptions:  none
   comments:    tcsetattr with c_cflag CRTS_IFLOW
 * Class:     gnu_io_RXTXPort
 * Method:    setRTS
 * Signature: (Z)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_setRTS(JNIEnv *env, jobject jobj, jboolean state)
{
  HANDLE hPort = get_fd(env, jobj);

  // EscapeCommFunction will fail if there's RTS/CTS flowcontrol. If it is incorrect,
  // we could turn flowcontrol off when getting to this function
  if(state == JNI_TRUE)
    EscapeCommFunction(hPort, SETRTS);
  else
    EscapeCommFunction(hPort, CLRRTS);
}

/*
setDSR

   accept:      state  flag to set/unset.
   perform:     depends on the state flag
                if true TIOCM_DSR is set
                if false TIOCM_DSR is unset
   return:      none
   exceptions:  none
   comments:    tcsetattr with c_cflag CRTS_IFLOW
 * Class:     gnu_io_RXTXPort
 * Method:    setDSR
 * Signature: (Z)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_setDSR(JNIEnv *env, jobject jobj, jboolean state)
{
  DCB PortDCB;

  HANDLE hPort = get_fd(env, jobj);
  PortDCB.DCBlength = sizeof(DCB);

  // Get the default port setting information.
  if(!GetCommState (hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    GetLastError();
    return;
  }

  // Change the DCB structure settings.
  if(state != JNI_FALSE)
    PortDCB.fOutxDsrFlow = TRUE;
  else
    PortDCB.fOutxDsrFlow = FALSE;

  // Configure the port according to the specifications of the DCB
  // structure.
  if (!SetCommState (hPort, &PortDCB))
  { //Unable to configure the serial port
    GetLastError();
    return;
  }
}

/*
isCTS

   accept:      none
   perform:     check status of CTS
   return:      true if TIOCM_CTS is set
                false if TIOCM_CTS is not set
   exceptions:  none
   comments:    CTS stands for Clear To Send.
 * Class:     gnu_io_RXTXPort
 * Method:    isCTS
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_isCTS(JNIEnv *env, jobject jobj)
{
  DWORD ModemStat;
  HANDLE hPort = get_fd(env, jobj);

  if(!GetCommModemStatus(hPort, &ModemStat))
    return JNI_FALSE;

  return ModemStat|MS_CTS_ON ? JNI_TRUE : JNI_FALSE;
}

/*
isDSR

   accept:      none
   perform:     check status of DSR
   return:      true if TIOCM_DSR is set
                false if TIOCM_DSR is not set
   exceptions:  none
   comments:    DSR stands for Data Set Ready
 * Class:     gnu_io_RXTXPort
 * Method:    isDSR
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_isDSR(JNIEnv *env, jobject jobj)
{
  DWORD ModemStat;
  HANDLE hPort = get_fd(env, jobj);

  if(!GetCommModemStatus(hPort, &ModemStat))
    return JNI_FALSE;

  return ModemStat|MS_DSR_ON ? JNI_TRUE : JNI_FALSE;
}

/*
isCD

   accept:      none
   perform:     check status of CD
   return:      true if TIOCM_CD is set
                false if TIOCM_CD is not set
   exceptions:  none
   comments:    CD stands for Carrier Detect
                The following comment has been made...
                "well, it works, there might ofcourse be a bug, but making DCD
                permanently on fixed it for me so I don't care"
 * Class:     gnu_io_RXTXPort
 * Method:    isCD
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_isCD(JNIEnv *env, jobject jobj)
{
  DWORD ModemStat;
  HANDLE hPort = get_fd(env, jobj);

  if(!GetCommModemStatus(hPort, &ModemStat))
    return JNI_FALSE;

  return ModemStat|MS_RLSD_ON ? JNI_TRUE : JNI_FALSE;
}

/*
isRI

   accept:      none
   perform:     check status of RI
   return:      true if TIOCM_RI is set
                false if TIOCM_RI is not set
   exceptions:  none
   comments:    RI stands for Ring Indicator
 * Class:     gnu_io_RXTXPort
 * Method:    isRI
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_isRI(JNIEnv *env, jobject jobj)
{
  DWORD ModemStat;
  HANDLE hPort = get_fd(env, jobj);

  if(!GetCommModemStatus(hPort, &ModemStat))
    return JNI_FALSE;

  return ModemStat|MS_RING_ON ? JNI_TRUE : JNI_FALSE;
}

/*
isRTS

   accept:      none
   perform:     check status of RTS
   return:      true if TIOCM_RTS is set
                false if TIOCM_RTS is not set
   exceptions:  none
   comments:    tcgetattr with c_cflag CRTS_IFLOW
 * Class:     gnu_io_RXTXPort
 * Method:    isRTS
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_isRTS(JNIEnv *env, jobject jobj)
{
  DCB PortDCB;
  HANDLE hPort = get_fd(env, jobj);

  PortDCB.DCBlength = sizeof(DCB);
  if(!GetCommState (hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    GetLastError();
    return JNI_FALSE;
  }

  if(PortDCB.fRtsControl == RTS_CONTROL_DISABLE)
    return JNI_FALSE;

  if(PortDCB.fRtsControl == RTS_CONTROL_ENABLE)
    return JNI_TRUE;

  if(PortDCB.fRtsControl == RTS_CONTROL_HANDSHAKE)
  {
    //MessageBox(NULL, L"Undefined condition: isRTS() but control is RTS_CONTROL_HANDSHAKE\r\nReturning FALSE", L"Warning", MB_OK | MB_ICONWARNING | MB_SETFOREGROUND);
    printj(env, L"Undefined condition: isRTS() but control is RTS_CONTROL_HANDSHAKE. Returning FALSE\n");
    return JNI_FALSE;
  }

  return JNI_FALSE;
}

/*
sendBreak

   accept:     duration in milliseconds.
   perform:    send break for actual time.  not less than 0.25 seconds.
   exceptions: none
   comments:   not very precise
 * Class:     gnu_io_RXTXPort
 * Method:    sendBreak
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_sendBreak(JNIEnv *env, jobject jobj, jint duration)
{
  HANDLE hPort = get_fd(env, jobj);

  SetCommBreak(hPort);
  Sleep(duration);
  ClearCommBreak(hPort);
}

/*
writeByte

   accept:      byte to write (passed as int)
   perform:     write a single byte to the port
   return:      none
   exceptions:  IOException
 * Class:     gnu_io_RXTXPort
 * Method:    writeByte
 * Signature: (IZ)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_writeByte(JNIEnv *env, jobject jobj, jint b, jboolean i)
{
  DWORD dwNumBytesWritten;
  LPCWSTR lpMsgBuf;
  HANDLE hPort = get_fd(env, jobj);
  BYTE bb = (BYTE)b;

  do {
    if (!WriteFile(hPort,              // Port handle
                   &bb,                // Pointer to the data to write
                   1,                  // Number of bytes to write
                   &dwNumBytesWritten, // Pointer to the number of bytes written
                   NULL))              // Must be NULL for Windows CE
    { // WriteFile failed. Report error.
      CreateErrorMsg(GetLastError(), lpMsgBuf);
      throw_java_exceptionW(env, IO_EXCEPTION, L"writeByte - WriteFile", lpMsgBuf );
      // Free the buffers.
      ReleaseErrorMsg(lpMsgBuf);
      return;
    }
  } while(dwNumBytesWritten == 0);
}

/*
writeArray

   accept:      jbarray: bytes used for writing
                off: offset in array to start writing
                len: Number of bytes to write
   perform:     write length bytes of jbarray
   return:      none
   exceptions:  IOException
 * Class:     gnu_io_RXTXPort
 * Method:    writeArray
 * Signature: ([BIIZ)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_writeArray(JNIEnv *env, jobject jobj, jbyteArray b, jint off, jint len, jboolean i)
{
  LPCWSTR lpMsgBuf;
	DWORD dwNumBytesWritten;
  jint total=0;
  HANDLE hPort = get_fd(env, jobj);

  jbyte *body = env->GetByteArrayElements(b, NULL);

	do {
    IF_DEBUG
    (
      printj(env, L"--- writeArray - %d bytes to write\n", len-total);
    )
    if (!WriteFile(hPort,              // Port handle
                   body+total+off,     // Pointer to the data to write
                   len-total,          // Number of bytes to write
                   &dwNumBytesWritten, // Pointer to the number of bytes written
                   NULL))              // Must be NULL for Windows CE
    { // WriteFile failed. Report error.
      CreateErrorMsg(GetLastError(), lpMsgBuf);
      throw_java_exceptionW(env, IO_EXCEPTION, L"writeArray - WriteFile", lpMsgBuf );
      // Free the buffers.
      ReleaseErrorMsg(lpMsgBuf);
      env->ReleaseByteArrayElements(b, body, JNI_ABORT);
      return;
    }
    total += dwNumBytesWritten;
	} while( total < len );

  env->ReleaseByteArrayElements(b, body, JNI_ABORT);
}

/*
nativeDrain

   accept:      none
   perform:     wait until all data is transmitted
   return:      none
   exceptions:  IOException
   comments:    java.io.OutputStream.flush() is equivalent to tcdrain,
                not tcflush, which throws away unsent bytes

                count logic added to avoid infinite loops when EINTR is
                true...  Thread.yeild() was suggested.
 * Class:     gnu_io_RXTXPort
 * Method:    nativeDrain
 * Signature: ()V
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeDrain(JNIEnv *env, jobject jobj, jboolean i)
{
  //COMSTAT Stat;
  //DWORD dwErrors;
  HANDLE hPort = get_fd(env, jobj);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.nativeDrain() called\n");
  )
  /*
  if(!FlushFileBuffers(hPort))
  {
    IF_DEBUG
    (
      printj(env, L"!!! FlushFileBuffers() error %ld\n", GetLastError());
    )
    return JNI_FALSE;
  }
   */
  // Alternative implementation:
  /*
  do
  {
    if(!ClearCommError(hPort, &dwErrors, &Stat))
    {
      GetLastError();
      return;
    }
    Sleep(10);
  } while(Stat.cbOutQue > 0);*/

  return JNI_FALSE;
}

/*
nativeavailable

   accept:      none
   perform:     find out the number of bytes available for reading
   return:      available bytes
                -1 on error
   exceptions:  none /// should be IOException
 * Class:     gnu_io_RXTXPort
 * Method:    nativeavailable
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_gnu_io_RXTXPort_nativeavailable(JNIEnv *env, jobject jobj)
{
  DWORD dwErrors;
  COMSTAT Stat;
  LPCWSTR lpMsgBuf;
  HANDLE hPort = get_fd(env, jobj);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.nativeavailable() called");
  )

  if(!ClearCommError(hPort, &dwErrors, &Stat))
  {
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, IO_EXCEPTION, L"nativeavailable - ClearCommError", lpMsgBuf );
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return -1;
  }

  IF_DEBUG
  (
    printj(env, L" - returning %ld\n", Stat.cbInQue);
  )

  return Stat.cbInQue;
}

/*
readByte

   accept:      none
   perform:     Read a single byte from the port
   return:      The byte read
   exceptions:  IOException
 * Class:     gnu_io_RXTXPort
 * Method:    readByte
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_gnu_io_RXTXPort_readByte(JNIEnv *env, jobject jobj)
{
  BYTE bb;
  DWORD dwNumBytesRead;
  LPCWSTR lpMsgBuf;
  HANDLE hPort = get_fd(env, jobj);

  if (!ReadFile(hPort, &bb, 1, &dwNumBytesRead, NULL))
  { // ReadFile failed. Report error.
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    throw_java_exceptionW(env, IO_EXCEPTION, L"readByte - ReadFile", lpMsgBuf);
    // Free the buffers.
    ReleaseErrorMsg(lpMsgBuf);
    return -1;
  }

  return dwNumBytesRead > 0 ? bb : -1;
}

/*
readArray

   accept:       offset (offset to start storing data in the jbarray) and
                 Length (bytes to read)
   perform:      read bytes from the port into a byte array
   return:       bytes read on success
                 0 on read timeout
   exceptions:   IOException
   comments:     throws ArrayIndexOutOfBoundsException if asked to
                 read more than SSIZE_MAX bytes
 * Class:     gnu_io_RXTXPort
 * Method:    readArray
 * Signature: ([BII)I
 */
JNIEXPORT jint JNICALL Java_gnu_io_RXTXPort_readArray(JNIEnv *env, jobject jobj, jbyteArray b, jint off, jint len)
{
  LPCWSTR lpMsgBuf;
	DWORD dwNumBytesRead, dwTotalRead = 0;
  jint threshold;
  HANDLE hPort = get_fd(env, jobj);

  if(len < 0)
  {
    throw_java_exceptionW(env, ARRAY_INDEX_OUT_OF_BOUNDS, L"readArray", L"Negative number of character to read");
    return -1;
  }

  jbyte *body = env->GetByteArrayElements(b, NULL);
  threshold = get_java_int_var(env, jobj, "threshold");

  do
  {
    if (!ReadFile(hPort, (unsigned char *)(body+off), len, &dwNumBytesRead, NULL))
    { // ReadFile failed. Report error.
      CreateErrorMsg(GetLastError(), lpMsgBuf);
      throw_java_exceptionW(env, IO_EXCEPTION, L"readArray - WriteFile", lpMsgBuf );
      // Free the buffers.
      ReleaseErrorMsg(lpMsgBuf);
      env->ReleaseByteArrayElements(b, body, JNI_ABORT);
      return -1;
    }

    dwTotalRead += dwNumBytesRead;
  } while(dwNumBytesRead > 0 && threshold != 0 && dwTotalRead <= (DWORD)len && dwTotalRead < (DWORD)threshold);

  env->ReleaseByteArrayElements(b, body, 0);
  return dwTotalRead;
}

/*
eventLoop

   accept:      none
   perform:     periodically check for SerialPortEvents
   return:      none
   exceptions:  none
   comments:	please keep this function clean.
 * Class:     gnu_io_RXTXPort
 * Method:    eventLoop
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_eventLoop(JNIEnv *env, jobject jobj)
{
  jfieldID jfMonitorThreadCloseLock, jfMonitorThreadLock, jfMonThreadisInterrupted;
  jmethodID jmSendEvent;
  HANDLE hCommEventThread;
  DWORD dwThreadID, dwWaitResult, dwEvent;
  int RetVal;
  HANDLE hPort = get_fd(env, jobj);
  EventInfoStruct *EventInfo = get_eis(env, jobj);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.eventLoop() start\n");
  )

  jclass cls = env->GetObjectClass(jobj);

  // Get pointers to some Java variables and methods:
  if( !(jfMonitorThreadLock = env->GetFieldID(cls, "MonitorThreadLock", "Z")) ||
      !(jfMonThreadisInterrupted = env->GetFieldID(cls, "monThreadisInterrupted", "Z")) ||
      !(jfMonitorThreadCloseLock = env->GetFieldID(cls, "MonitorThreadCloseLock", "Z")) ||
      !(jmSendEvent = env->GetMethodID(cls, "sendEvent", "(IZ)Z"))
    )
  {
    IF_DEBUG
    (
		  env->ExceptionDescribe();
    )
	  env->ExceptionClear();
	  return;
  }

  hCommEventThread = CreateThread(NULL, 0, CommEventThread, (LPVOID)EventInfo, 0, &dwThreadID);
  if(hCommEventThread == NULL)
  {
    LPCWSTR lpMsgBuf;
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    printj(env, L"!!! eventLoop - CreateThread() error: %s\n", lpMsgBuf);
    ReleaseErrorMsg(lpMsgBuf);
    return;
  }

  CloseHandle(hCommEventThread);

  do
  {
    if(env->GetBooleanField(jobj, jfMonThreadisInterrupted) == JNI_TRUE)
    {
      IF_DEBUG
      (
        printj(env, L"--- RXTXPort.eventLoop() interrupted - exiting\n");
      )

      CloseHandle(EventInfo->eventHandle);

	    env->SetBooleanField(jobj, jfMonitorThreadCloseLock, JNI_FALSE);
      return;
    }

    if(EventInfo->eventThreadReady)
    { // Thread is ready to work - pass signal to Java
      IF_DEBUG
      (
        printj(env, L"--- RXTXPort.eventLoop() - EventThread is ready\n");
      )
      env->SetBooleanField(jobj, jfMonitorThreadLock, JNI_FALSE);
      EventInfo->eventThreadReady = false;
    }

    if((dwWaitResult = WaitForSingleObject(EventInfo->eventHandle, 250)) == WAIT_FAILED)
    {
      IF_DEBUG
      (
        LPCWSTR lpMsgBuf;
        CreateErrorMsg(GetLastError(), lpMsgBuf);
        printj(env, L"!!! eventLoop - WaitForSingleObject() error: %s\n", lpMsgBuf);
        ReleaseErrorMsg(lpMsgBuf);
      )
      CloseHandle(EventInfo->eventHandle);
	  env->SetBooleanField(jobj, jfMonitorThreadCloseLock, JNI_FALSE);
      return;
    }

    if(dwWaitResult == WAIT_OBJECT_0)
    {
      dwEvent = EventInfo->event;
      // Clearing event - event thread will continue
      EventInfo->event = 0;
      // Send events to Java
      if(RetVal = SendEvents(env, jobj, dwEvent, EventInfo, jmSendEvent))
      {
        IF_DEBUG
        (
          printj(env, L"!!! eventLoop - SendEvents() result: %d\n", RetVal);
        )
        CloseHandle(EventInfo->eventHandle);
  	    env->SetBooleanField(jobj, jfMonitorThreadCloseLock, JNI_FALSE);
        return;
      }
    }
    else
    {
      IF_DEBUG
      (
        //printj(env, L"--- eventLoop() looping\n");
        MessageBeep(MB_OK);
      )
    }
  } while(TRUE);
}


/*
interruptEventLoop

   accept:      nothing
   perform:     sets monThreadisInterrupted
   return:      nothing
   exceptions:  none
   comments:    real monitoring thread will stay until port is closed
 * Class:     gnu_io_RXTXPort
 * Method:    interruptEventLoop
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_interruptEventLoop(JNIEnv *env, jobject jobj)
{
  jfieldID jfid;
  HANDLE hPort = get_fd(env, jobj);

  jclass cls = env->GetObjectClass(jobj);
  jfid = env->GetFieldID(cls, "monThreadisInterrupted", "Z");
	env->SetBooleanField(jobj, jfid, JNI_TRUE);
}


/*
 nativeSetEventFlag

   accept:      fd for finding the struct, event to flag, flag.
   perform:     toggle the flag
   return:      none
   exceptions:  none
   comments:	all the logic used to be done in Java but its too noisy
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetEventFlag
 * Signature: (IIZ)V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_nativeSetEventFlag(JNIEnv *env, jobject jobj, jint fd, jint event, jboolean flag)
{
  DWORD dwErr, NewFlag;
  EventInfoStruct *EventInfo = get_eis(env, jobj);
  HANDLE hPort = (HANDLE)fd;

  IF_DEBUG
  (
    printj(env, L"--- nativeSetEventFlag(%ld, %d) called\n", event, (int)flag);
  )

  switch(event)
  {
    case SPE_DATA_AVAILABLE:
      NewFlag = EV_RXCHAR;
    break;

    case SPE_OUTPUT_BUFFER_EMPTY:
      NewFlag = EV_TXEMPTY;
    break;

    case SPE_CTS:
      NewFlag = EV_CTS;
    break;

    case SPE_DSR:
      NewFlag = EV_DSR;
    break;

    case SPE_RI:
      NewFlag = EV_RING;
    break;

    case SPE_CD:
      NewFlag = EV_RLSD;
    break;

    case SPE_OE:
    case SPE_PE:
    case SPE_FE:
      NewFlag = EV_ERR;
    break;

    case SPE_BI:
      NewFlag = EV_BREAK;
    break;

  }

  if(flag == JNI_TRUE)
    EventInfo->ef = EventInfo->ef | NewFlag;
  else
    EventInfo->ef = EventInfo->ef & ~NewFlag;

  if(!SetCommMask(hPort, EventInfo->ef))
  {
    dwErr = GetLastError();
    IF_DEBUG
    (
      LPCWSTR lpMsgBuf;
      CreateErrorMsg(dwErr, lpMsgBuf);
      printj(env, L"!!! nativeSetEventFlag - SetCommMask() error: %ld %s\n", dwErr, lpMsgBuf );
      ReleaseErrorMsg(lpMsgBuf);
    )
    return;
  }

}

/*
nativeClose

   accept:      none
   perform:     get the fd from the java end and close it
   return:      none
   exceptions:  none
 * Class:     gnu_io_RXTXPort
 * Method:    nativeClose
 * Signature: (Ljava/lang/String{ })V
 */
JNIEXPORT void JNICALL Java_gnu_io_RXTXPort_nativeClose(JNIEnv *env, jobject jobj, jstring name)
{
  HANDLE hPort = get_fd(env, jobj);

  IF_DEBUG
  (
    LPCWSTR wszName = env->GetStringChars(name, NULL);
    printj(env, L"--- RXTXPort.nativeClose(%s) called\n", wszName);
    env->ReleaseStringChars(name, wszName);
  )

  if (!CloseHandle(hPort))
  {
    GetLastError();
    return;
  }

}

/*
nativeGetParityErrorChar

   accept:      -
   perform:     check the ParityErrorChar
   return:      The ParityErrorChar as an jbyte.
   exceptions:  UnsupportedCommOperationException if not implemented
   comments:    It appears the Parity char is usually \0.  The windows
		API allows for this to be changed.  I cant find may
		examples of this being done.  Maybe for a reason.

		Use a direct call to the termios file until we find a
		solution.
 * Class:     gnu_io_RXTXPort
 * Method:    nativeGetParityErrorChar
 * Signature: ()I
 */
JNIEXPORT jbyte JNICALL Java_gnu_io_RXTXPort_nativeGetParityErrorChar(JNIEnv *env, jobject jobj)
{
  DCB PortDCB;
  LPCWSTR lpMsgBuf;

  HANDLE hPort = get_fd(env, jobj);
  PortDCB.DCBlength = sizeof(DCB);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.nativeGetParityErrorChar() called\n");
  )

  // Get port setting information.
  if(!GetCommState(hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    IF_DEBUG
    (
      printj(env, L"!!! nativeGetParityErrorChar - GetCommState() error: %s\n", lpMsgBuf);
    )
    ReleaseErrorMsg(lpMsgBuf);
    return -1;
  }

  return (jbyte)PortDCB.ErrorChar;
}

/*
nativeSetParityErrorChar

   accept:      the ParityArrorCharacter as an int.
   perform:     Set the ParityErrorChar
   return:      JNI_TRUE on success
   exceptions:  UnsupportedCommOperationException if not implemented
   comments:    It appears the Parity char is usually \0.  The windows
		API allows for this to be changed.  I cant find may
		examples of this being done.  Maybe for a reason.

		Use a direct call to the termios file until we find a
		solution.
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetParityErrorChar
 * Signature: (B)Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeSetParityErrorChar(JNIEnv *env, jobject jobj, jbyte b)
{
  DCB PortDCB;
  LPCWSTR lpMsgBuf;

  HANDLE hPort = get_fd(env, jobj);
  PortDCB.DCBlength = sizeof(DCB);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.nativeSetParityErrorChar(%#x) called\n", (int)b);
  )

  // Get port setting information.
  if(!GetCommState(hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    IF_DEBUG
    (
      printj(env, L"!!! nativeSetParityErrorChar - GetCommState() error: %s\n", lpMsgBuf);
    )
    ReleaseErrorMsg(lpMsgBuf);
    return JNI_FALSE;
  }

  if(b != 0)
  {
    PortDCB.fErrorChar = TRUE;
    PortDCB.fParity = TRUE;
    PortDCB.ErrorChar = b;
  }
  else
  {
    PortDCB.fErrorChar = FALSE;
    PortDCB.fParity = FALSE;
    PortDCB.ErrorChar = 0;
  }

  if (!SetCommState(hPort, &PortDCB))
  {
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    IF_DEBUG
    (
      printj(env, L"!!! nativeSetParityErrorChar - SetCommState() error: %s\n", lpMsgBuf);
    )
    ReleaseErrorMsg(lpMsgBuf);
    return JNI_FALSE;
  }

  return JNI_TRUE;
}

/*
nativeGetEndOfInputChar

   accept:      -
   perform:     check the EndOf InputChar
   return:      the EndOfInputChar as an jbyte.  -1 on error
   exceptions:  UnsupportedCommOperationException if not implemented
   comments:
 * Class:     gnu_io_RXTXPort
 * Method:    nativeGetEndOfInputChar
 * Signature: ()I
 */
JNIEXPORT jbyte JNICALL Java_gnu_io_RXTXPort_nativeGetEndOfInputChar(JNIEnv *env, jobject jobj)
{
  DCB PortDCB;
  LPCWSTR lpMsgBuf;

  HANDLE hPort = get_fd(env, jobj);
  PortDCB.DCBlength = sizeof(DCB);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.nativeGetEndOfInputChar() called\n");
  )

  // Get port setting information.
  if(!GetCommState(hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    IF_DEBUG
    (
      printj(env, L"!!! nativeGetEndOfInputChar - GetCommState() error: %s\n", lpMsgBuf);
    )
    ReleaseErrorMsg(lpMsgBuf);
    return -1;
  }

  return (jbyte)PortDCB.EofChar;
}


/*
nativeSetEndOfInputChar

   accept:      The EndOfInputChar as an int
   perform:     set the EndOfInputChar
   return:      JNI_TRUE on success
   exceptions:  UnsupportedCommOperationException if not implemented
   comments:    This may cause troubles on Windows.
		Lets give it a shot and see what happens.

		See termios.c for the windows bits.

		EofChar = val;
		fBinary = false;  //winapi docs say always use true. ?
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetEndOfInputChar
 * Signature: (B)Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeSetEndOfInputChar(JNIEnv *env, jobject jobj, jbyte b)
{
  DCB PortDCB;
  LPCWSTR lpMsgBuf;

  HANDLE hPort = get_fd(env, jobj);
  PortDCB.DCBlength = sizeof(DCB);

  IF_DEBUG
  (
    printj(env, L"--- RXTXPort.nativeSetEndOfInputChar(%#x) called\n", (int)b);
  )

  // Get port setting information.
  if(!GetCommState(hPort, &PortDCB))
  { //Unable to get configuration of the serial port
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    IF_DEBUG
    (
      printj(env, L"!!! nativeSetEndOfInputChar - GetCommState() error: %s\n", lpMsgBuf);
    )
    ReleaseErrorMsg(lpMsgBuf);
    return JNI_FALSE;
  }

  if( b != 0)
  {
    PortDCB.fBinary = FALSE;
    PortDCB.EofChar = b;
  }
  else
  {
    PortDCB.fBinary = TRUE;
    PortDCB.EofChar = 0;
  }

  if (!SetCommState(hPort, &PortDCB))
  {
    CreateErrorMsg(GetLastError(), lpMsgBuf);
    IF_DEBUG
    (
      printj(env, L"!!! nativeSetEndOfInputChar - SetCommState() error: %s\n", lpMsgBuf);
    )
    throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetEndOfInputChar", lpMsgBuf);
    ReleaseErrorMsg(lpMsgBuf);
    return JNI_FALSE;
  }

  return JNI_TRUE;
}


/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetUartType
 * Signature: (Ljava/lang/String{ }Z)Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeSetUartType(JNIEnv *env, jobject jobj, jstring type, jboolean test)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetUartType", L"Operation not implemented");
  return JNI_FALSE;
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeGetUartType
 * Signature: ()Ljava/lang/String{ }
 */
JNIEXPORT jstring JNICALL Java_gnu_io_RXTXPort_nativeGetUartType(JNIEnv *env, jobject jobj)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetUartType", L"Operation not implemented");
  return env->NewStringUTF("Unknown");
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetBaudBase
 * Signature: (I)Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeSetBaudBase(JNIEnv *env, jobject jobj, jint baudBase)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetBaudBase", L"Operation not implemented");
  return JNI_FALSE;
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeGetBaudBase
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_gnu_io_RXTXPort_nativeGetBaudBase(JNIEnv *env, jobject jobj)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeGetBaudBase", L"Operation not implemented");
  return -1;
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetDivisor
 * Signature: (I)Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeSetDivisor(JNIEnv *env, jobject jobj, jint divisor)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetDivisor", L"Operation not implemented");
  return JNI_FALSE;
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeGetDivisor
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_gnu_io_RXTXPort_nativeGetDivisor(JNIEnv *env, jobject jobj)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeGetDivisor", L"Operation not implemented");
  return -1;
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetLowLatency
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeSetLowLatency(JNIEnv *env, jobject jobj)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetLowLatency", L"Operation not implemented");
  return JNI_FALSE;
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeGetLowLatency
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeGetLowLatency(JNIEnv *env, jobject jobj)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeGetLowLatency", L"Operation not implemented");
  return JNI_FALSE;
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeSetCallOutHangup
 * Signature: (Z)Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeSetCallOutHangup(JNIEnv *env, jobject jobj, jboolean noHup)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeSetCallOutHangup", L"Operation not implemented");
  return JNI_FALSE;
}

/*
 * Class:     gnu_io_RXTXPort
 * Method:    nativeGetCallOutHangup
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_gnu_io_RXTXPort_nativeGetCallOutHangup(JNIEnv *env, jobject jobj)
{
  throw_java_exceptionW(env, UNSUPPORTED_COMM_OPERATION, L"nativeGetCallOutHangup", L"Operation not implemented");
  return JNI_FALSE;
}