File: SIO.cpp

package info (click to toggle)
yudit 2.9.6-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 13,868 kB
  • ctags: 6,378
  • sloc: cpp: 70,516; perl: 4,299; ansic: 1,957; makefile: 846; sh: 331
file content (1889 lines) | stat: -rw-r--r-- 40,565 bytes parent folder | download | duplicates (3)
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
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
/** 
 *  Yudit Unicode Editor Source File
 *
 *  GNU Copyright (C) 1997-2006  Gaspar Sinai <gaspar@yudit.org>  
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License, version 2,
 *  dated June 1991. See file COPYYING for details.
 *
 *  This program 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 this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 For windows debuging #define UNICODE
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <stoolkit/SUtil.h>

#define STDIN 0
#define STDOUT 1

#ifndef USE_WINAPI
#include <unistd.h>
#include <sys/wait.h>
#else
#include <io.h>
#include <direct.h>
#endif

#include "SIO.h"
#include "SExcept.h"
#include "SEncoder.h"

#ifdef USE_WINAPI
#define S_MYOFLAGS O_BINARY
#else
#include <dirent.h>
#define S_MYOFLAGS 0
#endif

#ifdef  USE_WINAPI
# include <winsock.h>
# include <io.h>
# define ERRNO WSAGetLastError()
#else
# include <errno.h>
# include <netdb.h>
# include <sys/socket.h>
# include <sys/types.h>
# include <netinet/in.h>
# include <unistd.h>
# define ERRNO errno
#endif

#ifdef HAVE_MMAP
#include <fcntl.h>
#include <sys/mman.h>
#if !defined (__svr4__) && !defined (__SVR4) && defined (sun)
extern "C" {
extern int munmap(void *, size_t);
}
#endif
#if !defined (MAP_FAILED)
#define MAP_FAILED ((void *)-1)
#endif
#ifndef MAP_FAILED
#define MAP_FAILED ((void *)-1)
#endif
#endif

#ifdef USE_WINAPI
// Hacked for winapi This is in SEventBSD hacked to hide dependency !!!!
int gettimeofday (struct timeval* tv, void* tz);
int initsockets(bool init);
#define SBAD_SOCKET  0
#define EWOULDBLOCK TRY_AGAIN
#else
#define SBAD_SOCKET  -1
#endif

#ifdef MAX_PATH
# define SS_MAX_DIR_LENGTH          MAX_PATH
#else
# define SS_MAX_DIR_LENGTH          4096
#endif

#ifdef USE_WINAPI
typedef HANDLE SS_DIR;
#define SS_INVALID_DIR INVALID_HANDLE_VALUE
#define SS_S_ISDIR(_m) ((_m & _S_IFMT)==_S_IFDIR)
#define SS_S_ISREG(_m) ((_m & _S_IFMT)==_S_IFREG)
#else
#define SS_S_ISDIR(_m) (S_ISDIR(_m))
#define SS_S_ISREG(_m) (S_ISREG(_m))
#define SS_S_ISLNK(_m) (S_ISLNK(_m))
typedef DIR* SS_DIR;
#define SS_INVALID_DIR 0
#endif

#ifdef USE_WINAPI
static WCHAR   _currDirW [SS_MAX_DIR_LENGTH];
#else
static char    _currDir [SS_MAX_DIR_LENGTH];
#endif

class SFileImageBuffer
{
public:
  SFileImageBuffer(long fd, long size, bool writeflag);
  ~SFileImageBuffer();
#ifdef USE_WINAPI
  void* handle;
#endif  
  int   count;
  char* buffer;
  long  bufferSize;
  long  fd;
  bool  writeflag;
};

SFileImage::~SFileImage ()
{
  if (shared)
  {
    SFileImageBuffer* b = (SFileImageBuffer*) shared;
    b->count--;
    if (b->count==0) delete b;
  }
}

SFileImage&
SFileImage::operator = (const SFileImage& in)
{
  if (&in != this)
  {
    if (shared)
    {
      SFileImageBuffer* b = (SFileImageBuffer*) shared;
      b->count--;
      if (b->count==0) delete b;
      shared = 0;
    }
    if (in.shared)
    {
      SFileImageBuffer* b = (SFileImageBuffer*) in.shared;
      b->count++;
      shared = b;
    }
  }
  return *this;
}

SFileImage::SFileImage (void)
{
  shared = 0;
}

SFileImage::SFileImage (long fd, long size, bool writeflag)
{
  SFileImageBuffer* b = new SFileImageBuffer (fd, size, writeflag);
  if (b->bufferSize < 0)
  {
    delete b;
    shared = 0;
  }
  else
  {
    shared = b;
  }
}

long
SFileImage::size() const
{
  if (shared == 0) return -1;
  SFileImageBuffer* b = (SFileImageBuffer*) shared;
  return b->bufferSize;
}

char*
SFileImage::array()
{
  if (shared == 0) return 0;
  SFileImageBuffer* b = (SFileImageBuffer*) shared;
  return b->buffer;
}


SFileImage::SFileImage (const SFileImage& in)
{
  if (in.shared)
  {
    SFileImageBuffer* b = (SFileImageBuffer*) in.shared;
    b->count++;
    shared = b;
  }
  else
  {
    shared = 0;
  }
}

static int sharedCount=0;
SFileImageBuffer::SFileImageBuffer(long _fd, long size, bool _writeflag)
{
  fd = _fd;
  bufferSize = size;
  count = 1;
#ifdef USE_WINAPI
  writeflag = _writeflag;
  handle = CreateFileMapping ((void*)fd, 0, 
		(_writeflag) ? PAGE_READWRITE : PAGE_READONLY, 
		0, 0, 0);
  if (handle==0)
  {
    CloseHandle ((void*) fd);
    fd = -1;
    buffer = 0;
    bufferSize = -1;
  }
  else
  {
    buffer = (char*) MapViewOfFile (handle, 
		(_writeflag) ? FILE_MAP_ALL_ACCESS : FILE_MAP_READ, 
		0, 0, bufferSize);
    if (buffer ==0)
    {
      CloseHandle (handle);
      CloseHandle ((void*) fd);
      fd = -1;
      buffer = 0;
      bufferSize = -1;
    }
  }
#else
# ifdef HAVE_MMAP
  writeflag = _writeflag;
  buffer=(char*) mmap (0, bufferSize, 
	(_writeflag) ? (PROT_WRITE|PROT_READ) : PROT_READ, MAP_SHARED, fd, 0);
  if (buffer==0 || buffer==(char*)MAP_FAILED)
  {
    if (fd >=0) close (fd);
    fd = -1;
    buffer = 0;
    bufferSize = -1;
  }
# else
  writeflag = 0;
  buffer = new char[bufferSize];
  CHECK_NEW (buffer);
  if (read (fd, buffer, bufferSize)!= bufferSize)
  {
    if (fd >=0) close (fd);
    delete buffer;
    fd = -1;
    buffer = 0;
    bufferSize = -1;
  }
  if (fd >=0) close (fd);
  close (fd);
  fd = -1;
# endif
#endif
  sharedCount++;
}

SFileImageBuffer::~SFileImageBuffer()
{
  if (buffer !=0)
  {
    if (fd >= 0)
    {
#ifdef USE_WINAPI
      UnmapViewOfFile (buffer);
      CloseHandle (handle);
      CloseHandle ((void*) fd);
#else
# ifdef HAVE_MMAP
      munmap ((char*)buffer, bufferSize);
      ::close (fd);
# else
# endif
#endif
    }
    else
    {
      delete buffer;
    }
  }
  sharedCount--;
  if (sharedCount==0) 
  {
    //fprintf (stderr, "SFileImageBuffer::~SFileImageBuffer OK\n");
  }
}

/**
 * @author: Gaspar Sinai <gaspar@yudit.org>
 * @version: 2000-04-23
 * This library is not multi-threaded. Therefor we need event handlers.
 */

/**
 * This is the base class for all io classes
 */
SIO::SIO (SEventSource::Type t)  : in(t, -1),  out(t, -1)
{
}

/**
 * The descturctor.
 */
SIO::~SIO()
{
}

/**
 * Get an input stream
 */
const SInputStream&
SIO::getInputStream()
{
  return in;
}

/**
 * Get an output stream
 */
const SOutputStream&
SIO::getOutputStream()
{
  return out;
}

/**
 * Create an stdio object. This will have
 */
SStdIO::SStdIO () : SIO(SEventSource::FILE), err(SEventSource::FILE, -1)
{
}

SStdIO::~SStdIO ()
{
}

/**
 * Get an input stream that can be used an a standard input.
 */
const SInputStream&
SStdIO::getInputStream()
{
  if (in.getId()<0)
  {
    in = SInputStream (SEventSource::FILE, (long)0);
  }
  return in;
}

/**
 * Get an output stream that can be used an a standard output.
 */
const SOutputStream&
SStdIO::getOutputStream()
{
  if (out.getId()<0)
  {
    out = SOutputStream (SEventSource::FILE, (long)1);
  }
  return out;
}

/**
 * Get an output stream that can be used an a standard error output.
 */
const SOutputStream&
SStdIO::getErrorOutputStream()
{
  if (err.getId()<0)
  {
    err = SOutputStream (SEventSource::FILE, (long)2);
  }
  return err;
}

/**
 * Create an stdio object. This will have
 * @param c is the command to execute.
 */
SPipe::SPipe (const SString& c) : SIO(SEventSource::PIPE), command (c)
{
}

/**
 * Create an stdio object. This will have
 * @param c is the command to execute.
 */
SPipe::SPipe (void) : SIO(SEventSource::PIPE), command ("")
{
}

SPipe::~SPipe ()
{
#ifdef USE_WINAPI
/* FIMXE: You need to modify SYudit.cpp for this. 
*/
  for (unsigned int i=0; i< waitHandles.size(); i++)
  {
    PROCESS_INFORMATION* pinfo = (PROCESS_INFORMATION*) waitHandles[i];
    CloseHandle (pinfo->hThread);
    CloseHandle (pinfo->hProcess);
  }
#endif
}

/**
 * Get an input stream that can be used an a standard input.
 */
const SInputStream&
SPipe::getInputStream()
{
  if (in.getId()<0)
  {
    if (command.size()==0)
    {
      /* STDIO in */
//fprintf (stderr, "STDIO input.\n");
      in = SInputStream (SEventSource::FILE, (long)0);
      in.setOK(true);
    }
    else
    {
      long d = openPipe (false);
      in = SInputStream (SEventSource::PIPE, d);
#ifdef USE_WINAPI
      in.setOK(d>0);
#else
      in.setOK(d>=0);
#endif        
    }
  }
  return in;
}

/**
 * Get an output stream that can be used an a standard output.
 */
const SOutputStream&
SPipe::getOutputStream()
{
  if (out.getId()<0)
  {
    if (command.size()==0)
    {
      out = SOutputStream (SEventSource::FILE, (long)1);
//fprintf (stderr, "SOutputStream stdout\n");
      out.setOK(true);
    }
    else
    {
//fprintf (stderr, "SOutputStream command\n");
      long d = openPipe (true);
      out = SOutputStream (SEventSource::PIPE, d);
#ifdef USE_WINAPI
      out.setOK(d>0);
#else
      out.setOK(d>=0);
#endif        
    }
  }
  return out;
}

/**
 * Create a file from a fixed filename
 * @param f is the filename in unix format.
 */
SFile::SFile (const SString& f) : SIO(SEventSource::FILE)
{
  name = f;
}

/**
 * Create a file from a file. The file is reaaly just the name
 * @param f is the original file
 */
SFile::SFile (const SFile& f) : SIO(SEventSource::FILE)
{
  name = f.name;
  map = f.map;
}

/**
 * Assign a file.
 */
SFile&
SFile::operator = (const SFile& f)
{
  name = f.name;
  if (this != &f) map = f.map;
  return *this;
}

/**
 * Open the file for reading and return the input stream, that
 * can be sued by a SReader
 */
const SInputStream&
SFile::getInputStream()
{
  long fd = in.getId();
  if (fd<0)
  {
    SString filename=name;

#ifdef USE_WINAPI
    filename.replaceAll("/", "\\");
    filename.append ((char) 0);
    SEncoder u8("utf-8");
    SEncoder u16("utf-16-le");
    SString res = u16.encode (u8.decode (filename));
    WCHAR* filenameW = (WCHAR *) res.array();
#else
    filename.append ((char) 0);
    char * filenameU = (char*) filename.array();
#endif
    if (filename.size()==0)
    {
      fd = (long) STDIN;
    }
    else
    {
#ifdef USE_WINAPI

      fd = (long) _wopen (filenameW, O_RDONLY | S_MYOFLAGS);
      // Windows98SE does not implement _wopen
      if (fd < 0) {
         SString filenameA = utf8ToSystem (filename);
         filenameA.append ((char)0);
         fd = (long) open (filenameA.array(), O_RDONLY | S_MYOFLAGS);
      }
#else
      fd = (long) open (filenameU, O_RDONLY | S_MYOFLAGS );
#endif
    }
  }
  SInputStream ins(SEventSource::FILE, fd);
#ifdef USE_WINAPI
  ins.setOK(fd>0);
#else
  ins.setOK(fd>=0);
#endif        
  in = ins;
  return in;
}

/**
 * Open the file for writing and return the output stream, that
 * can be sued by a SWriter
 */
const SOutputStream&
SFile::getOutputStream()
{
  int fd;
  if (out.getId()< 0) 
  {
    SString filename=name;
#ifdef USE_WINAPI
    filename.replaceAll("/", "\\");
    filename.append ((char) 0);
    SEncoder u8("utf-8");
    SEncoder u16("utf-16-le");
    SString res = u16.encode (u8.decode (filename));
    WCHAR* filenameW = (WCHAR *) res.array();
#else
    filename.append ((char) 0);
    char * filenameU = (char*) filename.array();
#endif
    if (name.size()==0)
    {
      fd = STDOUT;
    }
    else
    {
#ifdef USE_WINAPI
      fd = _wopen (filenameW, O_WRONLY | O_CREAT | O_TRUNC | S_MYOFLAGS, 0666);
      // Windows98SE does not implement _wopen
      if (fd < 0) {
         SString filenameA = utf8ToSystem (filename);
         filenameA.append ((char)0);
         fd = open (filenameA.array(), O_WRONLY | O_CREAT | O_TRUNC | S_MYOFLAGS, 0666);
      }
#else
      fd = open (filenameU, O_WRONLY | O_CREAT | O_TRUNC | S_MYOFLAGS, 0666);
#endif
    }
    SOutputStream outs (SEventSource::FILE, (long)fd);
#ifdef USE_WINAPI
    outs.setOK(fd>0);
#else
    outs.setOK(fd>=0);
#endif        
    out = outs;
  }
  return out;
}

/**
 * Find the file by the path..
 * @parma filen is the base filename. 
 * @param pt is the list of paths it could be found.
 * @aram lookcwd is true if we also need to look into current working dir
 */
SFile::SFile (const SString& filen, const SStringVector& pt, bool lookcwd): SIO(SEventSource::FILE) 
{
  name = "";
  /* Serach for file */
  for (unsigned int i=0; i<pt.size() && size() < 0; i++)
  {
    SString newName = pt[i];
    newName.append ("/");
    newName.append (filen);
    newName.replaceAll("//", "/");
    if (!lookcwd && newName == filen)
    {
      name = "";
      continue;
    }
    name = newName;
  }
  if (size() < 0 && lookcwd)
  {
    name =  filen;
  }
}

/**
 * Try to mmap the file. If does not work, try to read it.
 * @return the buffer that is a representation of the file.
 * call the size() function after this call to determine the
 * real size in a multi-user environment.
 * write flag is present but only read is allowed. Write is not
 * implemented.
 */
const SFileImage&
SFile::getFileImage(bool writeflag)
{
  if (map.size()>=0) return map;
  long s = size();
  if (s <=0) return map;

  SString fn=name;
#ifdef USE_WINAPI
  fn.replaceAll("/", "\\");
#endif
  fn.append ((char) 0);

#ifdef USE_WINAPI
  //SString p = ("\\\\?\\");
  //p.append (utf8ToSystem (fn));
  SEncoder u8("utf-8");
  SEncoder u16("utf-16-le");
  SString res = u16.encode (u8.decode (fn));
  WCHAR* fileNameW = (WCHAR *) res.array();
#else
  const char* fileName = fn.array();
#endif


#ifdef USE_WINAPI
  //void* fd=CreateFileW (fileNameW, 0, OF_READ | OF_SHARE_DENY_NONE);
  void* fd=CreateFileW (fileNameW, 
	(writeflag) ? (GENERIC_READ| GENERIC_WRITE) : GENERIC_READ, 
	(writeflag) ? (FILE_SHARE_READ | FILE_SHARE_WRITE) : FILE_SHARE_READ,
	0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, 0);
  if (fd==0)
  {
    // Windows98SE does not implement CreateFileW
    SString fileNameA = utf8ToSystem (fn);
    fileNameA.append ((char)0);
    fd=CreateFileA (fileNameA.array(), 
 	(writeflag) ? (GENERIC_READ| GENERIC_WRITE) : GENERIC_READ, 
	(writeflag) ? (FILE_SHARE_READ | FILE_SHARE_WRITE) : FILE_SHARE_READ,
	0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, 0);
    if (fd == 0) return map;
  }
  if (fd==0)
#else
  int fd=open ((const char*) fileName, (writeflag) ? O_RDWR : O_RDONLY);
  if (fd<0)
#endif
  {
    return map;
  }
  SFileImage newMap((long) fd, s, writeflag);
  map = newMap;
  if (map.size() < 0)
  {
#ifndef USE_WINAPI
    fprintf (stderr, "SIO: Open succeeded but mmap failed for %s\n", fileName);
#endif
  }
  return map;
}

/**
 * Get the resolved filename in unix format.
 */
const SString&
SFile::getName() const
{
   return name;
}

/**
 * return the file size or negative if it does not exist
 */
long
SFile::size()
{
  struct stat     buf;
  SString newName = name;
  newName.append ((char)0);
#ifdef USE_WINAPI
  newName.replaceAll("/", "\\");
  SEncoder u8("utf-8");
  SEncoder u16("utf-16-le");
  SString u16str = u16.encode (u8.decode (newName));
  WCHAR* currentW = (WCHAR *) u16str.array();
 
  WIN32_FIND_DATAW entry;
  SS_DIR  dir=FindFirstFileW (currentW, &entry);
  if (dir == SS_INVALID_DIR)
  {
    WIN32_FIND_DATAA entryA;
    SString system = utf8ToSystem (newName);
    system.append ((char)0);
    // Fall back to system
    char* currentA = (char *) system.array();

    // Windows98SE does not implement FindFirstFileW
    dir=FindFirstFileA (currentA, &entryA);
    if (dir == SS_INVALID_DIR)
    {
      return -1;
    }
    FindClose (dir);
    return ((long)entryA.nFileSizeHigh * (MAXDWORD+1)) + (long)entryA.nFileSizeLow;
  }
  FindClose (dir);
  return ((long)entry.nFileSizeHigh * (MAXDWORD+1)) + (long)entry.nFileSizeLow;
#else
  if (stat ((char*)newName.array(), &buf) != 0)
  {
    return -1;
  }
  return (long) buf.st_size;
#endif
}

bool
SFile::truncate (long _size)
{
  SString newName = name;
#ifdef USE_WINAPI
  newName.replaceAll("/", "\\");
  newName.replaceAll("/", "\\");
  newName.append ((char) 0);
  SEncoder u8("utf-8");
  SEncoder u16("utf-16-le");
  SString res = u16.encode (u8.decode (newName));
  WCHAR* filenameW = (WCHAR *) res.array();
#endif
  SString newNameU = newName;
  newNameU.append ((char) 0);
  char * filenameU = (char*) newName.array();
#ifdef USE_WINAPI
  int d = _wopen (filenameW, O_WRONLY | O_CREAT | O_APPEND | S_MYOFLAGS, 0666);
  // Windows98SE does not implement _wopen
  if (d < 0) {
     SString filenameA = utf8ToSystem (newName);
     filenameA.append ((char)0);
      d = open (filenameA.array(), O_WRONLY | O_CREAT | O_APPEND | S_MYOFLAGS, 0666);
  }
#else
  int d = open (filenameU, O_WRONLY | O_CREAT | O_APPEND | S_MYOFLAGS, 0666);
#endif
  if (d <=0)
  {
    return false;
  }
#ifdef USE_WINAPI
  if (::_chsize (d, _size) != 0)
  {
    close (d);
    return false;
  }
#else
  if (::ftruncate (d, _size) != 0)
  {
    close (d);
    return false;
  }
#endif
  close (d);
  return true;
}

/**
 * Destruct the file.
 */
SFile::~SFile ()
{
}

/**
 * Make a new socket abstraction class.
 * @param h is the hostname or ip address.
 * @param p is the port.
 */
SSocket::SSocket (const SString h, int p): SIO(SEventSource::SOCKET)
{
  host = h;
  port = p;
}

/**
 * Make a new server socket abstraction class.
 * @param h is the hostname or ip address.
 */
SSocket::SSocket (const SSocket& s) : SIO(SEventSource::SOCKET)
{
  host = s.host;
  port = s.port;
}

/**
 * Assing a socket.
 * do not assign sterams
 */
SSocket&
SSocket::operator = (const SSocket& s)
{
  host = s.host;
  port = s.port;
  return *this;
}

/**
 * Destroy a socket.
 * The copied streams may survive the socket.
 */
SSocket::~SSocket ()
{
}

/**
 * Get an input stream that could be used by a SReader
 */
const SInputStream&
SSocket::getInputStream()
{
  if (port < 0) return out;
  if (out.isOK())
  {
     //SInputStream s (SEventSource::SOCKET, (long)dup((int)out.getId()));
     //if (s.getId() > 0) s.setOK(true);
     SOutputStream s(out);
     in = s;
     return in;
  }
  openSocket(&in);
  return in;
}

/**
 * Get an input stream that could be used by a SWriter
 */
const SOutputStream&
SSocket::getOutputStream()
{
  if (port < 0) return out;
  if (in.isOK())
  {
     //SOutputStream s (SEventSource::SOCKET, (long)dup((int)in.getId()));
     //if (s.getId() > 0) s.setOK(true);
     SOutputStream s(in);
     out = s;
     return out;
  }
  openSocket(&out);
  return out;
}
  
/**
 * Try to open a socket. Used internally.
 * For ip addressed, ipv6 is not yet supported.
 */
void
SSocket::openSocket(SOutputStream* o)
{
#ifdef USE_WINAPI 
  initsockets (true);
#endif
  int sd = socket (AF_INET, SOCK_STREAM, IPPROTO_IP);
  SOutputStream s (SEventSource::SOCKET, (long)sd);
  *o = s;
#ifdef USE_WINAPI
  if (sd == 0)
  {
#else 
  if (sd == -1)
  {
#endif
    port = -1;
    return;
  }
  char* hstring = host.cString();

  // We could use saddr.s_addr = inet_addr(address);
  // But we don't want at this stage
  if (sscanf (hstring, "%d.%d.%d.%d", 
     &address[0], &address[1], &address[2], &address[3])!=4)
  {
    struct hostent*  hostEntry = gethostbyname (hstring);
    if (hostEntry==0 || hostEntry->h_addr_list==0)
    {
      fprintf (stderr, "error: can not get ip address for \"%s\"\n", hstring);
      port = -1;
#ifdef USE_WINAPI
      closesocket(sd);
#else
      close (sd);
#endif
      delete hstring;
      return;
    }
    address[0] = hostEntry->h_addr_list[0][0];
    address[1] = hostEntry->h_addr_list[0][1];
    address[2] = hostEntry->h_addr_list[0][2];
    address[3] = hostEntry->h_addr_list[0][3];
  }
  delete hstring;
  address[0] &= 0xff;
  address[1] &= 0xff;
  address[2] &= 0xff;
  address[3] &= 0xff;

  struct sockaddr_in server;
  server.sin_addr.s_addr = htonl ((address[0]<<24) +
      (address[1] << 16) + (address[2] << 8) + address[3]);
  server.sin_port = htons (port);
  server.sin_family = AF_INET;
  
  if (connect (sd, (struct sockaddr*) &server, sizeof (server))!=0)
  {
    fprintf (stderr, "error: failed to connect to %d.%d.%d.%d:%d (%d)\n",
        address[0], address[1], address[2], address[3], port, ERRNO);
#ifdef USE_WINAPI
    closesocket(sd);
#else
    close (sd);
#endif
    return;
  }
  o->setOK(true);
}


/**
 * make a server socket. Not yet implemented.
 */
/* TODO: implement this */
SServer::SServer (int port): SIO(SEventSource::SERVER)
{
}

/**
 * Delete a server socket.
 */
SServer::~SServer ()
{
}


/**
 * Try to guess the current directory
 * GetTempFileName
 */
SDir::SDir(void) : name("/home/gsinai")
{
#ifdef USE_WINAPI
/*
  //char* buff=0;
  //if (GetFullPathNameQ ("Gazsi Bacsi", SS_MAX_DIR_LENGTH-1, _currDirW, &buff))
*/
  if (GetCurrentDirectoryW (SS_MAX_DIR_LENGTH-1, _currDirW))
  {
    
    SString u16fn ((const char*) _currDirW, (unsigned int) 2 * wcslen (_currDirW));
    SEncoder u8("utf-8");
    SEncoder u16("utf-16-le");

    name = u8.encode (u16.decode (u16fn));

  // Windows98 does not implement getCurrentDirectoryW
  } else if (GetCurrentDirectoryA (SS_MAX_DIR_LENGTH-1, (char*) _currDirW)) {
    SString ansi ((const char*) _currDirW);
    name = systemToUtf8 (ansi);
  }
  else 
  {
    name = (SString) "Z:/";
  }
  name.replaceAll("\\", "/");
  name.insert (0, "/");
#else
  if (getcwd(_currDir, SS_MAX_DIR_LENGTH-1)==0)
  {
    name = (SString) "/";
  }
  else
  {
    _currDir[SS_MAX_DIR_LENGTH-1] = 0;
    name = (SString) _currDir;
  }
#endif
}
/**
 * The directory abstraction layer
 */
SDir::SDir(const SString& _name) : name (_name)
{
  /* convert it to a real name */
  name.replaceAll ("\\", "/");
  name.replaceAll ("//", "/");
  if (name.size() == 0 || name[0] != '/')
  {
    name.insert (0, "/");
  }
#ifdef USE_WINAPI
  if (name.size() >= 2 && name[1] == ':' 
    && name[0] >= 'A' && name[0] <= 'Z')
  {
    /* C:WINDOWS */
    if (name.size() > 2 && name[2] != '/')
    {
      name.insert (2, "/");
    }
    name.insert (0, "/");
  }
  else if (name.size() >= 2 && name[1] == ':' 
    && name[0] >= 'a' && name[0] <= 'z')
  {
    char dletter = name[0] - 'a' + 'A';
    name.remove (0);
    name.insert (0, SString(&dletter, 1));
    /* d:yuko */
    if (name.size() > 2 && name[2] != '/')
    {
      name.insert (2, "/");
    }
    name.insert (0, "/");
    name.insert (0, "/");
  }
#endif
}

/**
 * Copy
 */
SDir::SDir(const SDir& dir)
{
  name = dir.name;
}

/**
 * Assign
 */
SDir&
SDir::operator = (const SDir& dir)
{
  name = dir.name;
  return *this;
}

/**
 * Delete
 */
SDir::~SDir ()
{
}

/**
 * Return the directory list.
 * @param e is SE_FILE or SE_DIR
 */
SStringVector
SDir::list (SEntry e)
{
  return list ("*", e);
}

/**
 * Return the directory list.
 * @param pattern is the pattern to look for. * is all.
 * @param e is SE_FILE or SE_DIR
 * It makes a smart list= checking checkTime 
 */
SStringVector
SDir::list (const SStringVector &patterns, SEntry e)
{
  if (name.size()==0) return SStringVector();

  SStringVector entries;

  SString _name = name;
#ifdef USE_WINAPI
  if (_name.size() > 0 && _name[0] == '/')
  {
    _name.remove (0); 
  }
  if (_name.size () == 0)
  {
    if (e!=SE_DIR)  return SStringVector();
    /* get drive letters */
    DWORD letter =GetLogicalDrives();
    SStringVector v;
    for (int i=(int)'A'; i<=(int)'Z' && letter; i++)
    {
      if (letter &1)
      {
        SString str;
        str.append ((char)i);
        str.append (':');
        v.append (str);
      }
      letter = letter >> 1;
    }
    return SStringVector (v);

  }
   _name.append("/*.*");
   _name.replaceAll("//", "/");
   _name.replaceAll("/", "\\");
   _name.append ((char)0);

   SEncoder u8("utf-8");
   SEncoder u16("utf-16-le");
   SString u16str = u16.encode (u8.decode (_name));
   WCHAR* currentW = (WCHAR *) u16str.array();

#else 
   _name.append ((char)0);
   char* currentU = (char*) _name.array();
#endif

   SS_DIR  dir;
 

#ifdef USE_WINAPI
  WIN32_FIND_DATAW entry;
  WIN32_FIND_DATAA entryA;
  dir=FindFirstFileW (currentW, &entry);
  boolean ansi = false;
  if (dir == SS_INVALID_DIR)
  {
    SString system = utf8ToSystem (_name);
    system.append ((char)0);
    // Fall back to system
    char* currentA = (char *) system.array();

    // Windows98SE does not implement FindFirstFileW
    dir=FindFirstFileA (currentA, &entryA);
    ansi = true;
  }
#else
  struct dirent*  entry;
  dir = opendir (currentU);
#endif
  if (dir == SS_INVALID_DIR)
  {
    //fprintf (stderr, "can not opendir: %s\n", currentU);
    return SStringVector(entries);
  }
  struct stat buf;
  while (true)
  {

#ifdef USE_WINAPI

    SString dnameStr;

    if (ansi) {
       dnameStr = systemToUtf8 (SString (entryA.cFileName));
       entry.dwFileAttributes = entryA.dwFileAttributes;
    } else {
       SString u16fn ((const char*) entry.cFileName, (unsigned int) 2 * wcslen (entry.cFileName));
       dnameStr = u8.encode (u16.decode (u16fn));
    }

    if (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
      if (e==SE_DIR && dnameStr != ".." && dnameStr != ".")
      {
        for(unsigned int i=0; i<patterns.size(); i++)
        {
          if (dnameStr.match(patterns[i]))
          {
            entries.append (dnameStr); break;
          }
        }
      }
    }
    else if (!(entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
    {
      if (e==SE_FILE)
      {
        for(unsigned int i=0; i<patterns.size(); i++)
        {
          if (dnameStr.match(patterns[i]))
          {
            entries.append (dnameStr); break;
          }
        }
      }
    }
    if (ansi) {
      if (!FindNextFileA (dir, &entryA))
      {
        if (GetLastError()==ERROR_NO_MORE_FILES) break;
        fprintf (stderr, "some errrors...%d\n", (int) GetLastError());
        break;
      }
    } else {
      if (!FindNextFileW (dir, &entry))
      {
        if (GetLastError()==ERROR_NO_MORE_FILES) break;
        fprintf (stderr, "some errrors...%d\n", (int) GetLastError());
        break;
      }
   }

#else

    if ((entry=readdir (dir))==0) break;

    SString fullName = name;
    fullName.append ('/');
    char* dname = entry->d_name;
    fullName.append (dname);
    fullName.replaceAll("//", "/");
    char* cFullName = fullName.cString();
    CHECK_NEW (cFullName);

    if (stat (cFullName, &buf) != 0 && lstat (cFullName, &buf) != 0)
    {
      fprintf (stderr, "can not stat: %s\n", cFullName);
      delete cFullName; 
      continue;
    }

    if (SS_S_ISDIR( buf.st_mode))
    {
      if (e==SE_DIR && strcmp (dname, ".")!=0 
        && strcmp (dname, "..")!=0)
      {
        SString n (dname);
        for(unsigned int i=0; i<patterns.size(); i++)
        {
          if (n.match(patterns[i]))
          {
            entries.append (n); break;
          }
        }
      }
    }
    else if ( SS_S_ISREG (buf.st_mode) || SS_S_ISLNK (buf.st_mode))
    {
      if (e==SE_FILE)
      {
        SString n (dname);
        for(unsigned int i=0; i<patterns.size(); i++)
        {
          if (n.match(patterns[i]))
          {
            entries.append (n); break;
          }
        }
      }
    }
    delete cFullName;
#endif

  }

#ifdef USE_WINAPI
  FindClose (dir);
#else
  closedir (dir);
#endif
  return SStringVector(entries);
}

/**
 * return the name of this directory
 */
SString
SDir::getUnixName() const
{
  return SString (name);
}
/**
 * return the name of this directory
 * Expos C: D: as they are.
 */
SString
SDir::getName() const
{
  SString str = name;
#ifdef USE_WINAPI
  if (str.size() > 0)
  {
    str.remove (0);
  }
#endif
  return SString (str);
}

/**
 * check if directory exists 
 */
bool
SDir::exists() const
{
  SString _name = name;
#ifdef USE_WINAPI
  if (_name == "/") return true;
  if (_name.size() > 0 && _name[0] == '/')
  {
    _name.remove (0); 
  }
  if (_name.size() == 2 && _name[1] == ':' 
      && _name[0] >= 'A' && _name[0] <= 'Z')
  {
    DWORD letter=GetLogicalDrives();
    return ((letter & (1 << (_name[0] - 'A'))) != 0);
  }
  if (_name.size() == 2 && _name[1] == ':' 
      && _name[0] >= 'a' && _name[0] <= 'z')
  {
    DWORD letter=GetLogicalDrives();
    return ((letter & (1 << (_name[0] - 'a'))) != 0);
  }
  // TODO Network 'Places'.
  if (_name.find ("/") < 0) 
  {
  }
  _name.replaceAll("/", "\\");
  _name.append ((char)0);
  SEncoder u8("utf-8");
  SEncoder u16("utf-16-le");
  SString u16str = u16.encode (u8.decode (_name));
  WCHAR* currentW = (WCHAR *) u16str.array();
 
  WIN32_FIND_DATAW entry;
  SS_DIR  dir=FindFirstFileW (currentW, &entry);
  if (dir == SS_INVALID_DIR)
  {
    WIN32_FIND_DATAA entryA;
    SString system = utf8ToSystem (_name);
    system.append ((char)0);
    // Fall back to system
    char* currentA = (char *) system.array();

    // Windows98SE does not implement FindFirstFileW
    dir=FindFirstFileA (currentA, &entryA);
    if (dir == SS_INVALID_DIR)
    {
      return false;
    }
    if (entryA.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) return true;
    return false;
  }
  if (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) return true;
  return false;
#else
  struct stat buf;
  char* current = _name.cString();
  CHECK_NEW (current);
  if (stat (current, &buf) != 0)
  {
    delete current;
    return false;
  }
  if (!SS_S_ISDIR( buf.st_mode))
  {
    delete current;
    return false;
  }
  delete current;
  return true;
#endif
}

/**
 * Try to create the directory. 
 * @return true on successs
 */
bool
SDir::create () const
{
  SString s = name;

#ifdef USE_WINAPI
  if (s.size() > 0 && s[0] == '/')
  {
    s.remove (0); 
  }
  s.replaceAll("/", "\\");
  s.append ((char) 0);
  SEncoder u8("utf-8");
  SEncoder u16("utf-16-le");
  SString u16str = u16.encode (u8.decode (s));

  WIN32_FIND_DATAW entry;
  int status= _wmkdir ((WCHAR*) u16str.array());
  if (status != 0) {
     // Windows98SE does not implement _wmkdir
     SString ansi = utf8ToSystem (s);
     ansi.append ((char)0);
     status= mkdir (ansi.array ());
     if (status != 0) {
       return false;
     }
  }
#else
  s.append ((char) 0);
  int status = mkdir (s.array(), 0755);
  if (status == -1 && errno != EEXIST) return false;
#endif
  return exists();
}

/**
 * check if directory readable 
 */
bool
SDir::readable() const
{
  SString _name = name;
#ifdef USE_WINAPI
  if (_name == "/") return true;
  if (_name.size() > 0 && _name[0] == '/')
  {
    _name.remove (0); 
  }
  if (_name.size() == 2 && _name[1] == ':' 
      && _name[0] >= 'A' && _name[0] <= 'Z')
  {
    DWORD letter=GetLogicalDrives();
    return ((letter & (1 << (_name[0] - 'A'))) != 0);
  }
  if (_name.size() == 2 && _name[1] == ':' 
      && _name[0] >= 'a' && _name[0] <= 'z')
  {
    DWORD letter=GetLogicalDrives();
    return ((letter & (1 << (_name[0] - 'a'))) != 0);
  }
  // TODO Network 'Places'.
  if (_name.find ("/") < 0) 
  {
  }
  _name.replaceAll("/", "\\");

#else

  char* current = _name.cString();
  CHECK_NEW (current);

#endif

  SS_DIR dir;

#ifdef USE_WINAPI

  WIN32_FIND_DATAW entry;
  SEncoder u8("utf-8");
  SEncoder u16("utf-16-le");
  _name.append ((char)0);
  SString u16str = u16.encode (u8.decode (_name));
  dir=FindFirstFileW ((WCHAR*) u16str.array(), &entry);
  if (dir==SS_INVALID_DIR)
  {
    WIN32_FIND_DATAA entryA;
    SString system = utf8ToSystem (_name);
    // Fall back to system
    char* currentA = (char *) system.array();

    // Windows98SE does not implement FindFirstFileW
    dir=FindFirstFileA (currentA, &entryA);
    if (dir==SS_INVALID_DIR) return false;
  }
#else
  dir = opendir (current);
  if (dir==SS_INVALID_DIR)
  {
    delete current;
    return false;
  }
#endif

#ifdef USE_WINAPI
  FindClose (dir);
#else
  closedir(dir);
  delete current;
#endif

  return true;
}

/**
 * Change directory 
 * ToDO DWORD GetLogicalDriveStrings (DWROD, char* lpBuffer);
 */
bool
SDir::cd (const SString& _newDir)
{
  SString newDir = _newDir;
  newDir.replaceAll("\\", "/");
  newDir.replaceAll("//", "/");
  
  if (newDir.size() == 0)
  {
    return false;
  }
  SStringVector cw = SStringVector(name, "/");
#ifdef USE_WINAPI
  if (newDir.size() >= 2 && newDir[1] == ':' 
    && newDir[0] >= 'A' && newDir[0] <= 'Z')
  {
    /* C:WINDOWS */
    if (newDir.size() > 2 && newDir[2] != '/')
    {
      newDir.insert (2, "/");
    }
    newDir.insert (0, "/");
    cw.clear();
  }
  else if (newDir.size() >= 2 && newDir[1] == ':' 
    && newDir[0] >= 'a' && newDir[0] <= 'z')
  {
    char dletter = newDir[0] - 'a' + 'A';
    newDir.remove (0);
    newDir.insert (0, SString(&dletter, 1));
    /* d:yuko */
    if (newDir.size() > 2 && newDir[2] != '/')
    {
      newDir.insert (2, "/");
    }
    newDir.insert (0, "/");
    newDir.insert (0, "/");
    cw.clear();
  }
#else
  if (newDir[0] == '/')
  {
    cw.clear();
  }
#endif
  /* relative */ 
  SStringVector nw = SStringVector (newDir, "/");
  for (unsigned int i=0; i<nw.size(); i++)
  {
     if (nw[i].size()==0) continue;
     if (nw[i]==".") continue;
     if (nw[i]=="..")
     {
        if  (cw.size()==0)
        {
          //fprintf (stderr, "cwsize..\n");
          return false;
        }
        if (cw.size()==1) 
        {
          cw.clear();
        }
        else
        {
          cw.truncate (cw.size()-1);
        }
        continue;
     }
     cw.append (nw[i]);
  }
  SString nd = cw.join ("/");
  nd.insert (0, "/");
  SDir d (nd);
  /* cd up till we find a directory */
  bool good = true;
  while (!d.exists() && cw.size()>0)
  {
    cw.truncate (cw.size()-1);
    nd = cw.join ("/");
    nd.insert (0, "/");
    d = SDir(nd);
    good = false;
  }
  name = d.name;
  return good;
}

/**
 * Wait for all waithandles 
 * return false if at leas on of them failed.
 */
int 
SPipe::wait ()
{
  int exitcode = 0;
#ifdef USE_WINAPI
  for (unsigned int i=0; i< waitHandles.size(); i++)
  {
    DWORD ret;
    PROCESS_INFORMATION* pinfo = (PROCESS_INFORMATION*) waitHandles[i];
    WaitForSingleObject (pinfo->hProcess, INFINITE);
    GetExitCodeProcess (pinfo->hProcess, &ret);
    if (ret) exitcode = (int) ret;
    CloseHandle (pinfo->hThread);
    CloseHandle (pinfo->hProcess);
  }
  waitHandles.clear();
  return exitcode;
#else
  for (unsigned int i=0; i< waitHandles.size(); i++)
  {
    int status;
    //pid_t ret = 
    waitpid ((pid_t) waitHandles[i], &status, 0);
    if (status) exitcode = status;
  }
  waitHandles.clear();
  return exitcode; /* FIXME: did not need it - not implemented. */
#endif
}
/**
 * Open a pipe and return the file desctiptor to it.
 * Chances are that 
 * @param command the shell command line.
 * @param output is true if we write to the command.
 */
long 
SPipe::openPipe(bool output)
{
#ifdef USE_WINAPI
   HANDLE pp[2];
   SECURITY_ATTRIBUTES sa;
   memset (&sa, 0, sizeof (sa)); 
   sa.nLength = sizeof (sa);
   sa.lpSecurityDescriptor = 0; 
   sa.bInheritHandle = 0; /* without this pipe would close */
   if (!CreatePipe (&pp[0], &pp[1], &sa, 0))
   {
     fprintf (stderr, "openPipe failed.\n");
     return -1;
   }
   STARTUPINFOW sinfo;
   memset (&sinfo, 0, sizeof (sinfo));
   sinfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
   sinfo.wShowWindow = SW_SHOWDEFAULT;

   STARTUPINFOA sinfoA;
   memset (&sinfoA, 0, sizeof (sinfoA));
   sinfoA.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
   sinfoA.wShowWindow = SW_SHOWDEFAULT;

   HANDLE hProcess = GetCurrentProcess();
   HANDLE dupedHandle = INVALID_HANDLE_VALUE; 
   HANDLE myHandle = INVALID_HANDLE_VALUE; 
   /* ugly but works...*/
   if (output)
   {
     /* dup the read side, make it inheritible, and close the original */
     myHandle = pp[1];
     DuplicateHandle(hProcess, pp[0], hProcess, &dupedHandle,
                0, TRUE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
     sinfo.hStdInput = dupedHandle;
     sinfo.hStdOutput = INVALID_HANDLE_VALUE;
     sinfo.hStdError = INVALID_HANDLE_VALUE;

     sinfoA.hStdInput = dupedHandle;
     sinfoA.hStdOutput = INVALID_HANDLE_VALUE;
     sinfoA.hStdError = INVALID_HANDLE_VALUE;
   }
   else
   {
     /* dup the read side, make it inheritible, and close the original */
     myHandle = pp[0];
     DuplicateHandle(hProcess, pp[1], hProcess, &dupedHandle,
                0, TRUE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
     sinfo.hStdInput = INVALID_HANDLE_VALUE;
     sinfo.hStdOutput = dupedHandle;
     sinfo.hStdError = INVALID_HANDLE_VALUE;

     sinfoA.hStdInput = INVALID_HANDLE_VALUE;
     sinfoA.hStdOutput = dupedHandle;
     sinfoA.hStdError = INVALID_HANDLE_VALUE;
   }

   PROCESS_INFORMATION* pinfo = new PROCESS_INFORMATION[1];

   SEncoder u8("utf-8");
   SEncoder u16("utf-16-le");
   SString cutf8 = command;
   cutf8.append ((char)0);
   SString cmdlineString = u16.encode (u8.decode (cutf8));
   SString cmdlineStringA = utf8ToSystem(cutf8);
   WCHAR* clW = (WCHAR *) cmdlineString.cString();

   if (!CreateProcessW (
        NULL, // module name 
        clW, // command line 
        NULL, // not inheritable handles
        NULL, // not inheritable thread handle
        TRUE, // handles not inherited 
        CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS, // no console
        NULL, // use parent's environment
        NULL, // use parent's starting directory
        &sinfo, // STARTUP_INFO
        pinfo) // PROCESS_INFO
     // Windows98SE does not implement CreateProcessW

    && !CreateProcessA (
        NULL, // module name 
        cmdlineStringA.cString(), // command line 
        NULL, // not inheritable handles
        NULL, // not inheritable thread handle
        TRUE, // handles not inherited 
        CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS, // no console
        NULL, // use parent's environment
        NULL, // use parent's starting directory
        &sinfoA, // STARTUP_INFO
        pinfo)) // PROCESS_INFO
   {

     fprintf (stderr, "Could not create process [%s]\n", clW);
     CloseHandle (myHandle);
     CloseHandle (dupedHandle);
     delete pinfo;
     return -1;
   }
   /* we need to close this because it got duped */
   CloseHandle (dupedHandle);

   /* wait till program starts */
   // wont link ::WaitForInputIdle (pinfo->hProcess, 5000);

   waitHandles.append ((long)pinfo);
   return (long) myHandle;
#else
   SString cmdlineString (command);
   int pp[2];
   if (pipe (pp) == -1)
   {
     fprintf (stderr, "openPipe failed.\n");
     return -1;
   }
   char* clString = cmdlineString.cString();
   int pid = fork();
   if (pid>0)
   {
     delete clString;
     waitHandles.append (pid);
     if (output)
     {
       close (pp[0]);
       //fprintf (stderr, "return parent %d\n", pp[1]);
       return pp[1];
     }
     //fprintf (stderr, "return parent %d\n", pp[0]);
     close (pp[1]);
     return pp[0];
   }
   else if (pid<0)
   {
     close (pp[1]);
     close (pp[0]);
     return -1;
   }
   else
   {
     for (int i=3; i<1024; i++)
     {
       if (i!=pp[0] && i!= pp[1])
       {
         close (i);
       }
     }
     /**
      * TODO: check if fdup2 works
      */
     if (output)
     {
       close (pp[1]);
       close (0);
       if (dup (pp[0]) !=0)
       {
         fprintf (stderr, "fdup failed\n");
       }
       close (pp[0]);
     }
     else
     {
       close (pp[0]);
       close (1);
       if (dup (pp[1]) != 1)
       {
         fprintf (stderr, "fdup failed\n");
       }
//fprintf (stderr, "return child %d\n", pp[1]);
       close (pp[1]);
     }
     execl ("/bin/sh", "sh", "-c", clString, (char*) 0);
     delete clString;
     exit (127);
   }
#endif
} 

/**
 * Create a temporary file.
 */
#ifdef USE_WINAPI
static WCHAR   _tmpFileW [SS_MAX_DIR_LENGTH];
#endif

SString
getTemporaryFileName ()
{
#ifdef USE_WINAPI
  // Windows98SE W does not work.
  if (!GetTempPathW (SS_MAX_DIR_LENGTH-1, _currDirW))
  {
    if (!GetTempPathA (SS_MAX_DIR_LENGTH-1, (char*) _currDirW))
    {
      fprintf (stderr, "Can not get temporary directory.\n");
      return SString ("");
    }
    if (!GetTempFileNameA ((char*)_currDirW, "yudit", 0, (char*) _tmpFileW))
    {
      fprintf (stderr, "Can not get temporary filename.\n");
      return SString ("");
    }
    SString ansi ((char*) _tmpFileW); 
    SString utf8 = systemToUtf8 (ansi);
    return SString (utf8);
  }
  if (!GetTempFileNameW (_currDirW, L"yudit", 0, _tmpFileW))
  {
    fprintf (stderr, "Can not get temporary filename.\n");
    return SString ("");
  }
  SString u16fn ((const char*) _tmpFileW, (unsigned int) 2 * wcslen (_tmpFileW));
  SEncoder u8("utf-8");
  SEncoder u16("utf-16-le");

  SString name = u8.encode (u16.decode (u16fn));
  return SString (name);

#else
  SString ret("/tmp");
  int pid= getpid();
  ret.append ("/yudit");
  ret.print (pid);
  ret.append (".tmp");
  return SString (ret);
#endif
}