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

/* $Rev$ */

#include "stdafx.h"

#include "mhmakefileparser.h"
#include "mhmakeparser.h"
#include "rule.h"
#include "util.h"

/* Calling py2exe is only implemented on windows for now. */
#ifdef WIN32

/* Python exe create script in parts:
import zipfile,tempfile,shutil,os

def UpdateZipFile(SrcZip,DestZip):
  NewZip=tempfile.mktemp('.zip')

  Src=zipfile.ZipFile(SrcZip)

  New=zipfile.ZipFile(NewZip,'w')

  InFile={}
  for name in Src.namelist():
    InFile[name]=1
    New.writestr(name,Src.read(name))
  Src.close()

  try:
    Dest=zipfile.ZipFile(DestZip)

    for name in Dest.namelist():
      if not InFile.has_key(name):
        New.writestr(name,Dest.read(name))
    Dest.close()
  except IOError:
    pass
  New.close()

  shutil.move(NewZip,DestZip)

OutFileName=tempfile.mktemp('.py')
pOut=open(OutFileName,'w')

Script=r'<PYTHONSCRIPT>'
DirScript=os.path.split(Script)[0]
pOut.write(r'''

from distutils.core import setup
import py2exe
import sys
sys.path.append(r'%s')
setup(zipfile=None, console=[r'%s'])
'''%(DirScript,Script))

pOut.close()

import os

stdin,stdout=os.popen4(r'"<PYTHONEXE>" %s py2exe'%OutFileName);
stdout.read()
stdout.close()
stdin.close()

OutDir=os.path.split(Script)[0]

import shutil
def CopyFiles(Src,Dest):
  for File in os.listdir(Src):
    SrcDir=os.path.join(Src,File)
    if File=='library.zip':
      UpdateZipFile(os.path.join(Src,File),os.path.join(Dest,File))
    elif os.path.isdir(SrcDir):
      DestDir=os.path.join(Dest,File)
      os.mkdir(DestDir)
      CopyFiles(SrcDir,DestDir)
    else:
      shutil.copy(os.path.join(Src,File),os.path.join(Dest,File))

if os.path.isdir('dist'):
  CopyFiles('dist',OutDir)

  try:
    shutil.rmtree('dist')
  except:
    pass
  try:
    shutil.rmtree('build')
  except:
    pass
os.remove(OutFileName)
*/

static const string PythonScriptPart1=
"import zipfile,tempfile,shutil,os\n"
"\n"
"def UpdateZipFile(SrcZip,DestZip):\n"
"  NewZip=tempfile.mktemp('.zip')\n"
"\n"
"  Src=zipfile.ZipFile(SrcZip)\n"
"\n"
"  New=zipfile.ZipFile(NewZip,'w')\n"
"\n"
"  InFile={}\n"
"  for name in Src.namelist():\n"
"    InFile[name]=1\n"
"    New.writestr(name,Src.read(name))\n"
"  Src.close()\n"
"\n"
"  try:\n"
"    Dest=zipfile.ZipFile(DestZip)\n"
"\n"
"    for name in Dest.namelist():\n"
"      if not InFile.has_key(name):\n"
"        New.writestr(name,Dest.read(name))\n"
"    Dest.close()\n"
"  except IOError:\n"
"    pass\n"
"  New.close()\n"
"\n"
"  shutil.move(NewZip,DestZip)\n"
"\n"
"OutFileName=tempfile.mktemp('.py')\n"
"pOut=open(OutFileName,'w')\n"
"\n"
"Script=r'"
;

static const string PythonScriptPart2=
"'\n"
"DirScript=os.path.split(Script)[0]\n"
"\n"
"pOut.write(r'''\n"
"\n"
"from distutils.core import setup\n"
"import py2exe\n"
"import sys\n"
"sys.path.append(r'%s')\n"
"setup(console=[r'%s'])\n"
"'''%(DirScript,Script))\n"
"\n"
"pOut.close()\n"
"\n"
"import os\n"
"\n"
"stdin,stdout=os.popen4(r'"
;

static const string PythonScriptPart3=
"%s py2exe'%OutFileName);\n"
"stdout.read()\n"
"stdout.close()\n"
"stdin.close()\n"
"\n"
"OutDir=os.path.split(Script)[0]\n"
"\n"
"import shutil\n"
"def CopyFiles(Src,Dest):\n"
"  for File in os.listdir(Src):\n"
"    SrcDir=os.path.join(Src,File)\n"
"    if File=='library.zip':\n"
"      UpdateZipFile(os.path.join(Src,File),os.path.join(Dest,File))\n"
"    elif os.path.isdir(SrcDir):\n"
"      DestDir=os.path.join(Dest,File)\n"
"      os.mkdir(DestDir)\n"
"      CopyFiles(SrcDir,DestDir)\n"
"    else:\n"
"      shutil.copy(os.path.join(Src,File),os.path.join(Dest,File))\n"
"\n"
"if os.path.isdir('dist'):\n"
"  CopyFiles('dist',OutDir)\n"
"\n"
"  try:\n"
"    shutil.rmtree('dist')\n"
"  except:\n"
"    pass\n"
"  try:\n"
"    shutil.rmtree('build')\n"
"  except:\n"
"    pass\n"
"os.remove(OutFileName)\n"
;
/*****************************************************************************/
/* Converts a python script to an executable if py2exe is installed */

void mhmakefileparser::CreatePythonExe(const string &FullCommand)
{
  /* First create a python script to run */
  cout << "Converting "<<FullCommand<<endl;

  string PythonScript;
  PythonScript+=PythonScriptPart1;
  PythonScript+=FullCommand;
  PythonScript+=PythonScriptPart2;
  PythonScript+=GetPythonExe();
  PythonScript+=PythonScriptPart3;

  char Filename[MAX_PATH];
  int Nr=0;
  FILE *pFile=(FILE*)1;
  while (1)
  {
    sprintf(Filename,"%s\\tmp%d.py",m_MakeDir->GetFullFileName().c_str(),Nr);
    pFile=fopen(Filename,"r");
    if (!pFile)
      break;
    fclose(pFile);
    Nr++;
  }
  pFile=fopen(Filename,"w");
  fprintf(pFile,"%s",PythonScript.c_str());
  fclose(pFile);

  string GenExeCommand=GetPythonExe();
  GenExeCommand+=QuoteFileName(Filename);

  string Output;
  ExecuteCommand(GenExeCommand,&Output);

  remove(Filename);
}
#endif

/*****************************************************************************/
int mhmakefileparser::SearchPath(const char *szCommand, const char *pExt, size_t Len, char *szFullCommand,char **pFilePart) const
{
  static vector< refptr<fileinfo> > vSearchPath;

  string Command(szCommand);
  if (pExt)
    Command+=pExt;
  vector< refptr<fileinfo> >::iterator It;
  vector< refptr<fileinfo> >::iterator ItEnd;

  refptr<fileinfo> CommandFile=GetFileInfo(Command,m_MakeDir);
  if (CommandFile->Exists())
  {
    goto found;
  }
  CommandFile->InvalidateDate(); // It could be created in the makefile later
  if (!vSearchPath.size())
  {
     char *pPath=getenv(PATH);
     if (!pPath)
       return 0;
     char *Path=strdup(pPath); // To be able to use strtok
     char *pTok=strtok(Path,OSPATHENVSEPSTR);
     while (pTok)
     {
       vSearchPath.push_back(GetFileInfo(pTok,m_MakeDir));
       pTok=strtok(NULL,OSPATHENVSEPSTR);
     }
     free(Path);
  }
  It=vSearchPath.begin();
  ItEnd=vSearchPath.end();
  while (It!=ItEnd)
  {
    CommandFile=GetFileInfo(Command,*It);
    if (CommandFile->Exists())
      goto found;
    It++;
  }

  return 0;

found:
  string FullCommand=CommandFile->GetFullFileName();
  size_t CommandLen=FullCommand.size();
  if (CommandLen>Len-1)
  {
    throw string("Command to long: ") + FullCommand;
  }
  strcpy(szFullCommand,FullCommand.c_str());
  return 1;
}

/*****************************************************************************/
string mhmakefileparser::SearchCommand(const string &Command, const string &Extension) const
{
  char FullCommand[MAX_PATH]="";
  unsigned long Size=sizeof(FullCommand);
  const char *pExt;
  if (Extension.empty())
    pExt=NULL;
  else
    pExt=Extension.c_str();
  if (SearchPath(UnquoteFileName(Command).c_str(),pExt,MAX_PATH,FullCommand,NULL))
    return FullCommand;
#ifdef WIN32
  /* See if we have a path for python.exe in the registry */
  HKEY hKey;
  string RegEntry=Command;
  if (pExt)
  {
    RegEntry+=Extension;
  }
  string KeyName=string("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\")+RegEntry;
  if (ERROR_SUCCESS!=RegOpenKey(HKEY_LOCAL_MACHINE,KeyName.c_str(),&hKey))
    return FullCommand;

  RegQueryValueEx(hKey,NULL,NULL,NULL,(LPBYTE)FullCommand,&Size);

  RegCloseKey(hKey);
#endif

  return FullCommand;
}

/*****************************************************************************/
/* Deletes a complete directory or files with wildcard. It can be assumed that the Directory passed does exist */
static bool DeleteDir(const string &Dir,const string WildSearch="*",bool bRemoveDir=true)
{
  bool Error=false;
  string Pattern=Dir+OSPATHSEP+WildSearch;
#ifdef WIN32
  WIN32_FIND_DATA FindData;
  mh_pid_t hFind=FindFirstFile(Pattern.c_str(),&FindData);
  if (hFind==INVALID_HANDLE_VALUE)
  {
    return Error;
  }

  do
  {
    /* Only handle items which are not . and .. */
    if (FindData.cFileName[0]!='.' || (FindData.cFileName[1] && (FindData.cFileName[1]!='.' || FindData.cFileName[2])) )
    {
      string FileName=Dir+OSPATHSEP+FindData.cFileName;
      if (FindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
      {
        Error = DeleteDir(FileName);
      }
      else
      {
        Error = (-1==remove(FileName.c_str()));
      }
    }
  } while (FindNextFile(hFind,&FindData));

  FindClose(hFind);

  if (bRemoveDir)
    Error = (0==RemoveDirectory(Dir.c_str()));
#else
  glob_t Res;
  if (glob (Pattern.c_str(), GLOB_ERR|GLOB_NOSORT|GLOB_MARK, NULL, &Res))
    return Error;

  for (int i=0; i<Res.gl_pathc; i++)
  {
    int Len=strlen(Res.gl_pathv[i])-1;
    if (Res.gl_pathv[i][Len]=='/')
    {
      Res.gl_pathv[i][Len]=0;
      Error = DeleteDir(Res.gl_pathv[i]);
    }
    else
    {
      Error = (-1==remove(Res.gl_pathv[i]));
    }
  }

  globfree(&Res);

  if (bRemoveDir)
    Error = (-1==remove(Dir.c_str()));
#endif

  return Error;
}

/*****************************************************************************/
mh_pid_t mhmakefileparser::DeleteFiles(const string &Params) const
{
  bool IgnoreError=false;
  vector< refptr<fileinfo> > Files;

  // First check if the first parameter is -e meaning don't give an error when file does not exist
  if (Params[1]=='-')
  {
    if (Params[2]=='e')
    {
      IgnoreError=true;
      SplitToItems(Params.substr(4),Files);
    }
    else
    {
      cerr << "Invalid option "<<Params[1]<<" in del statement\n";
      return (mh_pid_t)-1;
    }
  }
  else
  {
    SplitToItems(Params,Files);
  }

  vector< refptr<fileinfo> >::const_iterator It=Files.begin();
  while (It!=Files.end())
  {
    refptr<fileinfo> pFile=*It++;
    string DirSearch="*";
    bool bRemoveDir=true;

    /* Now check if there is a wildcard */
    if (pFile->GetFullFileName().find('*')!=string::npos)
    {
      DirSearch=pFile->GetName();
      pFile=pFile->GetDir();
      bRemoveDir=false;
    }

    pFile->InvalidateDate();
    if (IgnoreError && !pFile->Exists() && !pFile->IsDir())
    {
      continue;
    }

    const string &FileName=pFile->GetFullFileName();
    if (pFile->IsDir())
    {
      if (DeleteDir(FileName,DirSearch,bRemoveDir) && !IgnoreError)
      {
        cerr << "Error deleting "<<FileName<<endl;
        return false;
      }
    }
    else
    {
      if (-1==remove(FileName.c_str()) && !IgnoreError)
      {
        cerr << "Error deleting "<<FileName<<endl;
        return (mh_pid_t)-1;
      }
    }
  }
  return (mh_pid_t)0;
}

/*****************************************************************************/
/* pDest can be a directory or a file */
static bool CopyFile(refptr<fileinfo> pSrc, refptr<fileinfo> pDest)
{
  if (pDest->IsDir())
  {
    pDest=GetFileInfo(pSrc->GetName(),pDest);
  }
  string SrcFileName=pSrc->GetFullFileName();
  string DestFileName=pDest->GetFullFileName();

  /* Now copy the file */
  FILE *pSrcFile=fopen(SrcFileName.c_str(),"rb");
  if (!pSrcFile)
  {
    cerr << "copy: error opening file "<<SrcFileName<<endl;
    return false;
  }
  FILE *pDestFile=fopen(DestFileName.c_str(),"wb");
  if (!pDestFile)
  {
    cerr << "copy: error creating file "<<DestFileName<<endl;
    return false;
  }
  char Buf[4096];
  size_t Ret;

  while ( (Ret=fread(Buf,1,sizeof(Buf),pSrcFile)) > 0)
  {
    fwrite(Buf,1,Ret,pDestFile);
  }
  fclose(pSrcFile);
  fclose(pDestFile);
  pDest->InvalidateDate();
  return true;
}

/*****************************************************************************/
/* Copies a complete directory to a destination (currenlty not recursive */
static bool CopyDir(refptr<fileinfo> pDir,refptr<fileinfo> pDest,const string WildSearch="*")
{
  bool Error=true;
  string Pattern=pDir->GetFullFileName()+OSPATHSEP+WildSearch;
#ifdef WIN32
  WIN32_FIND_DATA FindData;
  mh_pid_t hFind=FindFirstFile(Pattern.c_str(),&FindData);
  if (hFind==INVALID_HANDLE_VALUE)
  {
    return false;
  }

  do
  {
    /* Only handle items which are not . and .. */
    if (FindData.cFileName[0]!='.' || (FindData.cFileName[1] && (FindData.cFileName[1]!='.' || FindData.cFileName[2])) )
    {
      if (FindData.dwFileAttributes&FILE_ATTRIBUTE_HIDDEN)
        continue;
      refptr<fileinfo> pSrc=GetFileInfo(FindData.cFileName,pDir);

      if (pSrc->IsDir())
      {
        refptr<fileinfo> pNewDest=GetFileInfo(FindData.cFileName,pDest);
        if (!pNewDest->IsDir())
        {
          if (pNewDest->Exists())
          {
            cerr << pNewDest->GetFullFileName() << " exists and is not a directory.\n";
            Error = false;
            goto exit;
          }
          if (!CreateDirectory(pNewDest->GetFullFileName().c_str(),NULL))
          {
            cerr << "Error creating directory " << pNewDest->GetFullFileName() << endl;
            Error = false;
            goto exit;
          }
          pNewDest->InvalidateDate();
        }
        Error = CopyDir(pSrc,pNewDest);
        if (!Error) goto exit;
      }
      else
      {
        Error = CopyFile(pSrc,pDest);
        if (!Error) goto exit;
      }
    }
  } while (FindNextFile(hFind,&FindData));

exit:
  FindClose(hFind);
#else
  glob_t Res;
  if (glob (Pattern.c_str(), GLOB_ERR|GLOB_NOSORT|GLOB_MARK, NULL, &Res))
    return Error;

  for (int i=0; i<Res.gl_pathc; i++)
  {
    refptr<fileinfo> pSrc=GetFileInfo(Res.gl_pathv[i],pDir);
    if (pSrc->IsDir())
    {
      *(strrchr(Res.gl_pathv[i],'/'))='\0';
      const char *SrcDirName=strrchr(Res.gl_pathv[i],'/')+1;

      if (SrcDirName[0]=='.')
        continue;

      refptr<fileinfo> pNewDest=GetFileInfo(SrcDirName,pDest);
      if (!pNewDest->IsDir())
      {
        if (pNewDest->Exists())
        {
          cerr << pNewDest->GetQuotedFullFileName() << " exists and is not a directory.\n";
          Error = false;
          goto exit;
        }
        if (-1==mkdir(pNewDest->GetFullFileName().c_str(),0777))
        {
          cerr << "Error creating directory " << pNewDest->GetQuotedFullFileName() << endl;
          Error = false;
          goto exit;
        }
        pNewDest->InvalidateDate();
      }
      Error = CopyDir(pSrc,pNewDest);
      if (!Error) goto exit;
    }
    else
    {
      Error = CopyFile(GetFileInfo(Res.gl_pathv[i],pDir),pDest);
      if (!Error) goto exit;
    }
  }

exit:
  globfree(&Res);
#endif

  return Error;
}

/*****************************************************************************/
mh_pid_t mhmakefileparser::EchoCommand(const string &Params) const
{
    // Find the first > character
  size_t Pos=Params.find_first_of('>');
  if (Pos==string::npos)
  {
    // Just echo it
    cout << Params << endl;
  }
  else
  {
    FILE *pfFile;
     /* Extra the filename */
    string Filename;
    if (Params[Pos+1]=='>')
    {
      NextItem(Params.substr(Pos+2).c_str(),Filename);
      refptr<fileinfo> pFile=GetFileInfo(Filename,m_MakeDir);
        // Open file in append
      pfFile=fopen(pFile->GetFullFileName().c_str(),"a");
    }
    else
    {
      NextItem(Params.substr(Pos+1).c_str(),Filename);
      refptr<fileinfo> pFile=GetFileInfo(Filename,m_MakeDir);
      pfFile=fopen(pFile->GetFullFileName().c_str(),"w");
    }
    if (!pfFile)
    {
      cerr << "Error opening file "<<Filename<<endl;
      return (mh_pid_t)-1;
    }
    int Begin=0;
    while (Params[Begin]==' ' || Params[Begin] == '\t') Begin++;  // Strip leading white space
    string EchoStr=Params.substr(Begin,Pos-1)+"\n";
    if (EchoStr.length()!=fwrite(EchoStr.c_str(),1,EchoStr.length(),pfFile))
    {
      cerr << "Error writing file "<<Filename<<endl;
      return (mh_pid_t)-1;
    }
    fclose(pfFile);
  }
  return (mh_pid_t)0;
}

/*****************************************************************************/
mh_pid_t mhmakefileparser::CopyFiles(const string &Params) const
{
  vector< refptr<fileinfo> > Files;

  SplitToItems(Params,Files);

  size_t NrSrcs=Files.size()-1;

  if (NrSrcs<1)
  {
    cerr << "Wrong number of arguments in copy: "<<Params<<endl;
    return false;
  }

  refptr<fileinfo> pDest=Files[NrSrcs];
  if (NrSrcs>1 && !pDest->IsDir())
  {
    cerr << "copy: Destination must be a directory when more then one source : "<<Params<<endl;
    return (mh_pid_t)-1;
  }

  for (size_t i=0; i<NrSrcs; i++)
  {
    refptr<fileinfo> pSrc=Files[i];

    string SrcFileName=pSrc->GetFullFileName();

    if (pSrc->IsDir())
    {
      SrcFileName+=OSPATHSEPSTR"*";
      pSrc=GetFileInfo(SrcFileName,m_MakeDir);
    }

    //cerr << "copy "<<pSrc->GetFullFileName()<<" "<<pDest->GetFullFileName()<<endl;
    /* Now check if there is a wildcard */
    if (SrcFileName.find('*')!=string::npos)
    {
      if (!CopyDir(pSrc->GetDir(), pDest, pSrc->GetName()))
      {
        cerr << "copy: Error copying directory: " << Params << endl;
        return (mh_pid_t)-1;
      }
    }
    else
    {
      if (!CopyFile(pSrc,pDest))
      {
        cerr << "copy: Error copying file: " << Params << endl;
        return (mh_pid_t)-1;
      }
    }
  }

  return (mh_pid_t)0;

}

/*****************************************************************************/
mh_pid_t mhmakefileparser::TouchFiles(const string &Params) const
{
  vector< refptr<fileinfo> > Files;

  SplitToItems(Params,Files);

  vector< refptr<fileinfo> >::const_iterator It=Files.begin();
  while (It!=Files.end())
  {
    refptr<fileinfo> pFile=*It++;
    const string &FileName=pFile->GetFullFileName();

    /* Since this can be part of a list of commands for a certain rule, and it is possible that the file
     * was generated by one on the previous commands, we first need the invalidate the date so that the
     * existance checking is done again */
    pFile->InvalidateDate();

    if (pFile->IsDir())
    {
      cerr << "touch: Cannot touch a directory: " << FileName << endl;
      return (mh_pid_t)-1;
    }
    if (pFile->Exists())
    {
      int fd;
      char c;
      int status = 0;
      struct stat st;
      int Ret;
      int saved_errno = 0;

      fd = open (FileName.c_str(), O_RDWR);
      if (fd<0)
      {
        st.st_size=0;
      }
      else
      {
        if (fstat (fd, &st) < 0)
        {
          cerr << "touch: Cannot stat file " << FileName << endl;
          return (mh_pid_t)-1;
        }
      }

      if (st.st_size == 0)
      {
        FILE *pFile;
        if (fd>=0 && close(fd) < 0)
        {
          cerr << "touch: Error closing file " << FileName << endl;
          return (mh_pid_t)-1;
        }
        /*Re-Create an empty file */
        pFile=fopen(FileName.c_str(),"wb");
        if (!pFile)
        {
          cerr << "touch: Cannot create file: " << FileName << endl;
          return (mh_pid_t)-1;
        }
        fclose(pFile);
      }
      else
      {
        Ret=read (fd, &c, sizeof(c));
        if (Ret!=sizeof(c) && Ret!=EOF)
        {
          cerr << "touch: Cannot read file " << FileName << ": "<<Ret<<endl;
          return (mh_pid_t)-1;
        }
        if (lseek (fd, (off_t) 0, SEEK_SET) < 0)
        {
          cerr << "touch: Error changing file pointer " << FileName << endl;
          return (mh_pid_t)-1;
        }
        if (write (fd, &c, sizeof c) != sizeof(c))
        {
          cerr << "touch: Error writing file " << FileName << endl;
          return (mh_pid_t)-1;
        }
        if (close (fd) < 0)
        {
          cerr << "touch: Error closing file " << FileName << endl;
          return (mh_pid_t)-1;
        }
      }
    }
    else
    {
      /* Create an empty file */
      FILE *pFile=fopen(FileName.c_str(),"wb");
      if (!pFile)
      {
        cerr << "touch: Cannot create file: " << FileName << endl;
        return (mh_pid_t)-1;
      }
      fclose(pFile);
    }
    pFile->InvalidateDate();
  }
  return (mh_pid_t)0;
}

/*****************************************************************************/
const string &mhmakefileparser::GetPythonExe() const
{
  static string PythonExe;
  if (PythonExe.empty())
  {
    string FullCommand=SearchCommand(PYTHONEXE);
    if (!FullCommand.empty())
    {
      PythonExe=QuoteFileName(FullCommand)+" ";
    }
    else
    {
      cerr<<"python executable not found in path and registry.\n";
      exit(1);
    }
  }
  return PythonExe;
}

/*****************************************************************************/
static const string &GetComspec()
{
  static string Comspec;
  if (Comspec.empty())
  {
    const char *pComspec=getenv(COMSPEC);
    if (pComspec)
    {
      Comspec=getenv(COMSPEC);
      #ifdef WIN32
      Comspec+=" /c ";
      #else
      Comspec+=" -c \"";
      #endif
    }
    else
    {
      #ifdef WIN32
      Comspec="cmd.exe /c ";
      #else
      Comspec="sh -c \"";
      #endif
    }
  }
  return Comspec;
}

/*****************************************************************************/
string mhmakefileparser::GetFullCommand(string Command)
{
  map<string,string>::iterator pFound=m_CommandCache.find(Command);
  string OriCommand=Command;
  if (pFound==m_CommandCache.end())
  {
    bool Found=false;
    // Not found in the stack, search in the environment path
    // Check if an extension is specified
    const char *pBeg=Command.c_str();
    const char *pEnd=pBeg+Command.length()-1;
    bool HasExt=false;
    while (pEnd>pBeg && *pEnd!=OSPATHSEP)
    {
      if (*pEnd=='.')
      {
        HasExt=true;
        break;
      }
      pEnd--;
    }
    if (HasExt)
    {
      string FullCommand=SearchCommand(Command);
      if (!FullCommand.empty())
      {
        Found=true;
        Command=FullCommand;
      }
    }
    else
    {
      static bool s_Py2ExeInstalled=true;
      /* First check for special internal commands */
      if (OriCommand=="del")
      {
        m_CommandCache[OriCommand]="del";
        return Command;
      }
      // Try with different extensions
      string FullCommand=SearchCommand(Command,EXEEXT);
      if (!FullCommand.empty())
      {
        Found=true;
        #ifdef WIN32
        /* Check if a python script also exists, is so try generating the executable again. */
        string PythonFullCommand=SearchCommand(Command,".py");
        Command=FullCommand;
        if (!PythonFullCommand.empty()&&s_Py2ExeInstalled)
        {
          refptr<fileinfo> pExeFile=GetFileInfo(FullCommand,m_MakeDir);
          refptr<fileinfo> pPyFile=GetFileInfo(PythonFullCommand,m_MakeDir);
          bool bBuild=false;
          if (pExeFile->GetDate().IsOlder(pPyFile->GetDate()))
          {
            bBuild=true;
          }
          if (!bBuild)
          {
            deps_t Autodeps;
            GetAutoDeps(pPyFile, Autodeps);
            deps_t::iterator It=Autodeps.begin();
            while (It!=Autodeps.end())
            {
              if (pExeFile->GetDate().IsOlder((*It)->GetDate()))
              {
                bBuild=true;
                break;
              }
              It++;
            }
          }
          if (bBuild)
          {
            if (pExeFile->Exists())
              remove(pExeFile->GetFullFileName().c_str());
            CreatePythonExe(PythonFullCommand);
            // Invalidate the exe date since it could have been recreated by the CreatePythonExe
            pExeFile->InvalidateDate();
          }

        }
        #else
        Command=FullCommand;
        #endif
      }
      else
      {
        FullCommand=SearchCommand(Command,".py");
        if (!FullCommand.empty())
        {
          Found=true;
          #ifdef WIN32
          /* Now first try to create an executable for it */
          if (s_Py2ExeInstalled)
          {
            refptr<fileinfo> pExeFile;
            CreatePythonExe(FullCommand);
            string ExeFullCommand=SearchCommand(Command,EXEEXT);
            if (!ExeFullCommand.empty())
            {
              pExeFile=GetFileInfo(ExeFullCommand,m_MakeDir);
              pExeFile->InvalidateDate(); // The file was just generated, make sure the correct date is taken.
            }
            if (ExeFullCommand.empty() || !pExeFile->Exists())
            {
              s_Py2ExeInstalled=false;
              cout << "\nWarning: cannot convert "<<FullCommand<<".\nCompilation will be faster by installing py2exe.\n\n";
              Command=GetPythonExe()+QuoteFileName(FullCommand);
            }
            else
              Command=ExeFullCommand;
          }
          else
          #endif
            Command=GetPythonExe()+QuoteFileName(FullCommand);
        }
      }
    }
    if (!Found)
    {
      Command=GetComspec()+QuoteFileName(Command);
    }
    m_CommandCache[OriCommand]=Command;
    return Command;
  }
  return pFound->second;
}

mh_pid_t mhmakefileparser::OsExeCommand(const string &Command, const string &Params, bool IgnoreError, string *pOutput) const
{
  string FullCommandLine;
  string ComSpec=GetComspec();
#ifdef WIN32
  STARTUPINFO StartupInfo;
  memset(&StartupInfo,0,sizeof(StartupInfo));
  StartupInfo.cb=sizeof(STARTUPINFO);
  PROCESS_INFORMATION ProcessInfo;

  if (Command.substr(0,ComSpec.size())==ComSpec)
  {
    string tmpCommand=Command.substr(ComSpec.size(),Command.size());
    FullCommandLine=ComSpec;
    FullCommandLine+=g_QuoteString+QuoteFileName(tmpCommand)+Params+g_QuoteString;
  }
  else
  {
    const string PythonExe=GetPythonExe();
    if (!(Command.substr(0,PythonExe.size())==PythonExe))
      FullCommandLine=QuoteFileName(Command)+Params;
    else
      FullCommandLine=Command+Params;
  }
  char *pFullCommand=new char[FullCommandLine.length()+1];
  strcpy(pFullCommand,FullCommandLine.c_str());

  if (pOutput || g_Quiet)
  {
    mh_pid_t hChildStdinRd;
    mh_pid_t hChildStdinWr;
    mh_pid_t hChildStdoutRd;
    mh_pid_t hChildStdoutWr;
    mh_pid_t hChildStdinWrDup;
    mh_pid_t hChildStdoutRdDup;
    SECURITY_ATTRIBUTES saAttr;
    BOOL fSuccess;

    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;

    if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
      return (mh_pid_t)-1;

        /* Create new output read handle and the input write handle. Set
    * the inheritance properties to FALSE. Otherwise, the child inherits
    * the these handles; resulting in non-closeable handles to the pipes
        * being created. */
    fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
                               GetCurrentProcess(), &hChildStdinWrDup, 0,
                               FALSE, DUPLICATE_SAME_ACCESS);
    if (!fSuccess) return (mh_pid_t)-1;
    /* Close the inheritable version of ChildStdin that we're using. */
    CloseHandle(hChildStdinWr);

    if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
      return (mh_pid_t)-1;

    fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
                               GetCurrentProcess(), &hChildStdoutRdDup, 0,
                               FALSE, DUPLICATE_SAME_ACCESS);
    if (!fSuccess) return (mh_pid_t)-1;
    CloseHandle(hChildStdoutRd);

    int hStdIn = _open_osfhandle((long)hChildStdinWrDup, _O_WRONLY|_O_TEXT);
    FILE *pStdIn = _fdopen(hStdIn, "w");
    int hStdOut = _open_osfhandle((long)hChildStdoutRdDup, _O_RDONLY|_O_TEXT);
    FILE *pStdOut = _fdopen(hStdOut, "r");

    StartupInfo.dwFlags = STARTF_USESTDHANDLES;
    StartupInfo.hStdInput = hChildStdinRd;
    StartupInfo.hStdOutput = hChildStdoutWr;
    StartupInfo.hStdError = hChildStdoutWr;

    if (!CreateProcess(NULL,pFullCommand,NULL,NULL,TRUE,CREATE_NO_WINDOW,m_pEnv,m_MakeDir->GetFullFileName().c_str(),&StartupInfo,&ProcessInfo))
    {
      delete[] pFullCommand;
      string ErrorMessage=string("Error starting command: ") + FullCommandLine + " : " + stringify(GetLastError());
      if (IgnoreError)
        cerr << ErrorMessage << endl;
      else
        throw ErrorMessage;
    }
    delete[] pFullCommand;
    if (!CloseHandle(hChildStdinRd)) return (mh_pid_t)-1;
    if (!CloseHandle(hChildStdoutWr)) return (mh_pid_t)-1;

    CloseHandle(ProcessInfo.hThread);
    char Buf[256];
    size_t Nbr;
    while ( (Nbr=fread(Buf,1,sizeof(Buf)-1,pStdOut)) > 0)
    {
      if (pOutput)
      {
        Buf[Nbr]=0;
        *pOutput+=Buf;
      }
    }
    WaitForSingleObject(ProcessInfo.hProcess,INFINITE);
    fclose(pStdIn);
    fclose(pStdOut);

    DWORD ExitCode=0;
    if (!GetExitCodeProcess(ProcessInfo.hProcess,&ExitCode) || ExitCode)
    {
      if (IgnoreError)
      {
        cerr << "Error running command: "<<Command<<", but ignoring error\n";
        return (mh_pid_t)0; // Ignore error
      }
      else
        return (mh_pid_t)-1;
    }
    CloseHandle(ProcessInfo.hProcess);
    return (mh_pid_t)0;
  }
  else
  {
    if (!CreateProcess(NULL,pFullCommand,NULL,NULL,TRUE,0,m_pEnv,m_MakeDir->GetFullFileName().c_str(),&StartupInfo,&ProcessInfo))
    {
      delete[] pFullCommand;
      string ErrorMessage=string("Error starting command: ") + Command + " : " + stringify(GetLastError());
      if (IgnoreError)
        cerr << ErrorMessage << endl;
      else
        throw ErrorMessage;
    }
    delete[] pFullCommand;
    CloseHandle(ProcessInfo.hThread);
    return ProcessInfo.hProcess;
  }
#else
  if (Command.substr(0,ComSpec.size())==ComSpec)
  {
    string tmpCommand=Command.substr(ComSpec.size(),Command.size());
    FullCommandLine=ComSpec;
    FullCommandLine+=QuoteFileName(tmpCommand)+Params;
  }
  else
  {
    FullCommandLine=Command+Params;
  }

  if (pOutput || g_Quiet)
  {
    int pipeto[2];      /* pipe to feed the exec'ed program input */
    int pipefrom[2];    /* pipe to get the exec'ed program output */

    pipe( pipeto );
    pipe( pipefrom );

    pid_t ID=vfork();
    if (ID==-1)
    {
      if (IgnoreError)
      {
        cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
        return (mh_pid_t)0; // Ignore error
      }
      else
        return (mh_pid_t)-1;
    }
    else if (ID==0)
    {
      int argc;
      const char **pargv;

      dup2( pipeto[0], STDIN_FILENO );
      dup2( pipefrom[1], STDOUT_FILENO  );
      /* close unnecessary pipe descriptors for a clean environment */
      close( pipeto[0] );
      close( pipeto[1] );
      close( pipefrom[0] );
      close( pipefrom[1] );

      poptParseArgvString(FullCommandLine.c_str(), &argc, &pargv);
      chdir(m_MakeDir->GetFullFileName().c_str());
      if (m_pEnv)
        execve(pargv[0],(char *const*)pargv,m_pEnv);
      else
        execv(pargv[0],(char *const*)pargv);
      free(pargv);
      _exit (EXIT_FAILURE);
    }
    else
    {
        /* Close unused pipe ends. This is especially important for the
      * pipefrom[1] write descriptor, otherwise readFromPipe will never
        * get an EOF. */
      close( pipeto[0] );
      close( pipefrom[1] );

      pid_t ID2=vfork();
      if (ID2==-1)
      {
        if (IgnoreError)
        {
          cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
          return (mh_pid_t)0; // Ignore error
        }
        else
          return (mh_pid_t)-1;
      }
      else if (ID2==0)
      {
        /* Close pipe write descriptor, or we will never know when the
        * writer process closes its end of the pipe and stops feeding the
        * exec'ed program. */
        close( pipeto[1] );
        char Buf[256];
        int Nbr;
        while ( (Nbr=read(pipefrom[0],Buf,sizeof(Buf)-1)) > 0)
        {
          if (pOutput)
          {
            Buf[Nbr]=0;
            *pOutput+=Buf;
          }
        }
        close( pipefrom[0]);
        _exit (EXIT_FAILURE);
      }
      else
      {
        /* close unused pipe end */
        close( pipefrom[0] );
        close( pipeto[1] );

        int Status;
        waitpid(ID2,&Status,0); // Wait until the reading of the output is finished
      }

      int Status;
      int Ret=waitpid(ID,&Status,0);
      if (Ret!=ID || Status)
      {
        if (IgnoreError)
        {
          cerr << "Error running command: "<<Command<<", but ignoring error\n";
          return (mh_pid_t)0; // Ignore error
        }
        else
          return (mh_pid_t)-1;
      }
    }
  }
  else
  {   // No pOutput
    pid_t ID=fork();
    if (ID==-1)
    {
      if (IgnoreError)
      {
        cerr << "Error forking when try to run command: "<<Command<<", but ignoring error\n";
        return (mh_pid_t)0; // Ignore error
      }
      else
        return (mh_pid_t)-1;
    }
    else if (ID==0)
    {
      int argc;
      const char **pargv;

      poptParseArgvString(FullCommandLine.c_str(), &argc, &pargv);
      chdir(m_MakeDir->GetFullFileName().c_str());
      if (m_pEnv)
        execve(pargv[0],(char *const*)pargv,m_pEnv);
      else
        execv(pargv[0],(char *const*)pargv);
      free(pargv);
      _exit (EXIT_FAILURE);
    }
    else
    {
      return (mh_pid_t)ID;
    }
  }

  return (mh_pid_t)0;
#endif
}

///////////////////////////////////////////////////////////////////////////////
#ifndef WIN32
string EscapeQuotes(const string &Params)
{
  int OldPos=0;
  int Pos;
  string Quote("\\\"");
  string SemiColon(" ; ");
  string Ret;

  while (1)
  {
    int Pos=Params.find_first_of('"',OldPos);
    int Pos2=Params.find(" & ",OldPos);
    string ToReplace(Quote);
    int Inc=1;

    if (Pos==string::npos)
    {
      if (Pos2==string::npos)
        break;
      Pos=Pos2;
      ToReplace=SemiColon;
      Inc=3;
    }
    else
    {
      if (Pos2!=string::npos && Pos2<Pos)
      {
        Pos=Pos2;
        ToReplace=SemiColon;
        Inc=3;
      }
    }
    Ret+=Params.substr(OldPos,Pos-OldPos);
    Ret+=ToReplace;
    OldPos=Pos+Inc;
  }
  Ret+=Params.substr(OldPos);
  return Ret;
}
#endif

///////////////////////////////////////////////////////////////////////////////
mh_pid_t mhmakefileparser::ExecuteCommand(string Command, bool &IgnoreError, string *pOutput)
{
  bool Echo=true;
  IgnoreError=false;
  while (1)
  {
    if (Command[0]=='@')
    {
      Echo=false;
      Command=Command.substr(1);
      continue;
    }
    if (Command[0]=='-')
    {
      IgnoreError=true;
      Command=Command.substr(1);
      continue;
    }
    break;
  }
  string InCommand=Command;
  if (g_Quiet)
    Echo=false;

  const char *pCom=Command.c_str();
  int StartCommandPos;
  int EndCommandPos;
  int BeginParamPos;
  if (*pCom=='"')
  {
    StartCommandPos=1;
    EndCommandPos=1;
    while (pCom[EndCommandPos]!='"') EndCommandPos++;
  }
  else
  {
    StartCommandPos=0;
    EndCommandPos=0;
  }
  while (!strchr(" \t",pCom[EndCommandPos])) EndCommandPos++;
  BeginParamPos=EndCommandPos;
  string Params=Command.substr(BeginParamPos);
  Command=Command.substr(StartCommandPos,EndCommandPos-StartCommandPos);

  // If we have special characters in the params we always call the command via the shell
  unsigned i;
  for (i=0; i<Params.size(); i++)
  {
    if (strchr("<>|&",Params[i]))
    {
      break;
    }
  }
  if (i==Params.size())
  {
    if (Command!="del" && Command!="touch" && Command!="copy" && Command!="echo")
      Command=GetFullCommand(Command);
#ifndef WIN32
    if (Command.substr(0,GetComspec().size())==GetComspec())
    {
      Params=EscapeQuotes(Params);
      Params+="\"";
    }
#endif
  }
  else
  {
    if (Command!="echo")
    {
      string FullCommand=GetFullCommand(Command);
      string ComSpec=GetComspec();
      if (FullCommand.substr(0,ComSpec.size())!=ComSpec)
        Command=FullCommand; // Only use FullCommand when it was found and not prepending by the comspec.
      Command=ComSpec+Command;
#ifndef WIN32
      Params=EscapeQuotes(Params);
      Params+="\"";
#endif
    }
  }
  if (Echo
      #ifdef _DEBUG
      || g_DoNotExecute
      #endif
      )
  {
    #ifdef _DEBUG
    if (g_PrintAdditionalInfo)
      cout << Command << Params << endl;
    else
      cout << InCommand << endl;
    #endif
  }

  /* first we check special internal commands */
  #ifdef _DEBUG
  if (pOutput || !g_DoNotExecute)
  {
  #endif
    if (Command=="del")
    {
      return DeleteFiles(Params);
    }
    else if (Command=="touch")
    {
      return TouchFiles(Params);
    }
    else if (Command=="copy")
    {
      return CopyFiles(Params);
    }
    else if (Command=="echo")
    {
      return EchoCommand(Params);
    }

    return OsExeCommand(Command,Params,IgnoreError,pOutput);
  #ifdef _DEBUG
  }
  #endif
  return (mh_pid_t)0; /* No Error */
}

///////////////////////////////////////////////////////////////////////////////
void mhmakefileparser::BuildDependencies(const refptr<rule> &pRule, const refptr<fileinfo> &Target, mh_time_t TargetDate, mh_time_t &YoungestDate, bool &MakeTarget)
{

  vector< refptr<fileinfo> > &Deps=Target->GetDeps();
  vector< refptr<fileinfo> >::iterator pDepIt=Deps.begin();
  while (pDepIt!=Deps.end())
  {
    StartBuildTarget(*pDepIt);
    pDepIt++;
  }
  pDepIt=Deps.begin();
  while (pDepIt!=Deps.end())
  {
    mh_time_t DepDate=WaitBuildTarget(*pDepIt);
    if (DepDate.IsNewer(YoungestDate))
      YoungestDate=DepDate;
    if (DepDate.IsNewer(TargetDate))
    {
      #ifdef _DEBUG
      if (pRule&&g_pPrintDependencyCheck && DepDate.IsExistingFile() && TargetDate.IsExistingFile())
        cout<<"Going to build "<<Target->GetQuotedFullFileName()<<" because "<<(*pDepIt)->GetQuotedFullFileName()<<" is more recent\n";
      #endif
      MakeTarget=true;
    }
    pDepIt++;
  }
}

///////////////////////////////////////////////////////////////////////////////
mh_time_t mhmakefileparser::StartBuildTarget(const refptr<fileinfo> &Target,bool bCheckTargetDir)
{
  #ifdef _DEBUG
  if (g_CheckCircularDeps)
  {
    deque< refptr<fileinfo> >::const_iterator pFind=find(m_TargetStack.begin(),m_TargetStack.end(),Target);
    if (pFind!=m_TargetStack.end())
    {
      cout << "Circular dependency detected.\n"<<Target->GetQuotedFullFileName()<<" depending on itself.\n";
      cout << "Dependency stack:\n";
      deque< refptr<fileinfo> >::const_iterator pIt=m_TargetStack.begin();
      while (pIt!=m_TargetStack.end())
      {
        cout << "  " << (*pIt)->GetQuotedFullFileName() << endl;
        pIt++;
      }
    }
    if (!Target->IsBuildStarted()) m_TargetStack.push_back(Target);
  }
  #endif

  #ifdef _DEBUG
  static int Indent;
  #endif

  if (g_StopCompiling)
  {
    throw string("Compilation Interrupted by user.");
  }

  if (Target->IsBuild())
  {
    #ifdef _DEBUG
    if (g_pPrintDependencyCheck)
    {
      for (int i=0; i<Indent; i++)
        cout<<"  ";
      cout<<"  Already build "<<Target->GetQuotedFullFileName()<<" : "<<Target->GetDate()<<endl;
    }
    #endif
    return Target->GetDate();
  }
  if (Target->IsBuilding())
    return mh_time_t();  // Target is still building, so we have to wait

  #ifdef _DEBUG
  if (g_GenProjectTree)
    cout << Target->GetQuotedFullFileName() << endl;

  Indent++;
  if (g_pPrintDependencyCheck)
  {
    for (int i=0; i<Indent; i++)
      cout<<"  ";
    cout<<"Building dependencies of "<<Target->GetQuotedFullFileName()<<endl;
  }
  #endif

  Target->SetBuild();

  /* Optimisation: do not build target when target dir does not exist,
     but first build the target dir, in case there exists a rule for it*/
  refptr<rule> pRule=Target->GetRule();

  if (!pRule && bCheckTargetDir)
  {
    refptr<fileinfo> TargetDir=Target->GetDir();
    mh_time_t TargetDirDate=BuildTarget(TargetDir,false);

    if (!TargetDir->Exists())
    {
      #ifdef _DEBUG
      Indent--;
      if (g_CheckCircularDeps)
      {
        m_TargetStack.pop_back();
      }
      #endif
      return TargetDirDate;
    }
  }

  mh_time_t TargetDate=Target->GetDate();
  bool MakeTarget=false;
  mh_time_t YoungestDate=TargetDate;

  if (!pRule || !pRule->GetCommands().size())
  {
    vector< pair<refptr<fileinfo>,refptr<rule> > > Result;


    IMPLICITRULE::SearchImplicitRule(Target,Result);

    vector< pair<refptr<fileinfo>,refptr<rule> > >::iterator ResultIt=Result.begin();
    while (ResultIt!=Result.end())
    {
      if (ResultIt->first==NullFileInfo)
      {
        pRule=ResultIt->second;
        Target->SetRule(pRule);
        #ifdef _DEBUG
        if (g_PrintAdditionalInfo)
        {
          cout<<"Found implicit rule for "<<Target->GetQuotedFullFileName()<<endl;
          pRule->PrintCommands(Target);
        }
        #endif
        break;
      }
      else
      {
        #ifdef _DEBUG
        m_ImplicitSearch++;
        #endif
        mh_time_t DepDate=BuildTarget(ResultIt->first);
        #ifdef _DEBUG
        m_ImplicitSearch--;
        #endif
        if (DepDate.DoesExist()) {
          if (DepDate.IsNewer(YoungestDate))
            YoungestDate=DepDate;
          pRule=ResultIt->second;
          Target->AddMainDep(ResultIt->first);
          Target->SetRule(pRule);  /* This is an implicit rule so do not add the target */
          #ifdef _DEBUG
          if (g_PrintAdditionalInfo)
          {
            cout<<"Found implicit rule for "<<Target->GetQuotedFullFileName()<<". Dependent "<<ResultIt->first->GetQuotedFullFileName()<<endl;
            pRule->PrintCommands(Target);
          }
          #endif
          if (DepDate.IsNewer(TargetDate))
          {
            #ifdef _DEBUG
            if (pRule,g_pPrintDependencyCheck && DepDate.IsExistingFile() && TargetDate.IsExistingFile())
              cout<<"Going to build "<<Target->GetQuotedFullFileName()<<" because "<<ResultIt->first->GetQuotedFullFileName()<<" is more recent\n";
            #endif
            MakeTarget=true;
          }
          break;
        }
      }
      ResultIt++;
    }
    if (pRule)
    {
      #ifdef _DEBUG
      Target->SetBuilding();
      Target->SetRule(pRule);
      Target->ClearBuilding();
      #else
      Target->SetRule(pRule);
      #endif
    }
  }

  mhmakeparser *pMakefile=NULL;
  if (pRule)
  {
    pMakefile=pRule->GetMakefile();
    if (pMakefile->ForceAutoDepRescan()||MakeTarget==true)
      pMakefile->UpdateAutomaticDependencies(Target);
  }
  else if (Target->GetAutoDepsMakefile())
    Target->GetAutoDepsMakefile()->UpdateNoRuleAutomaticDependencies(Target);

  BuildDependencies(pRule,Target,TargetDate,YoungestDate,MakeTarget);

  if (pRule)
  {
    #ifdef _DEBUG
    if (g_pPrintDependencyCheck)
    {
      for (int i=0; i<Indent; i++)
        cout<<"  ";
      cout<<"Building "<<Target->GetQuotedFullFileName()<<endl;
    }
    #endif
    if (!MakeTarget)
    {
      if (!TargetDate.DoesExist() || ( (g_RebuildAll || pMakefile->m_RebuildAll) && TargetDate.IsOlder(m_sBuildTime)))
      {
        #ifdef _DEBUG
        if (g_pPrintDependencyCheck)
        {
          if (!TargetDate.DoesExist())
          {
            if (!m_ImplicitSearch && !Target->IsPhony())
              cout<<"Building "<<Target->GetQuotedFullFileName()<<" because it does not exist yet\n";
          }
          else if (TargetDate.IsOlder(m_sBuildTime))
          {
            cout<<"Building "<<Target->GetQuotedFullFileName()<<" because need to rebuild all (-a)\n";
          }
        }
        #endif
        MakeTarget=true;
      }
    }

    // Now execute the commands
    vector<string> &Commands=pRule->GetCommands();

    if (!MakeTarget)
    {
      vector<string>::iterator CommandIt=Commands.begin();

      md5_context ctx;
      md5_starts( &ctx );
      while (CommandIt!=Commands.end())
      {
        pMakefile->SetRuleThatIsBuild(Target); // Make sure that the command expension is correct
        string Command=pMakefile->ExpandExpression(*CommandIt);
        pMakefile->ClearRuleThatIsBuild();  /* Make sure that further expansion is not taking this rule into account.*/
        md5_update( &ctx, (uint8 *)Command.c_str(), (unsigned long)Command.size());
        CommandIt++;
      }

      uint32 Md5_32=md5_finish32( &ctx);
      if (!Target->CompareMd5_32(Md5_32))
      {
        if (TargetDate.IsNewerOrSame(m_sBuildTime) || TargetDate.IsDir())
        {
          // Only rebuild if it is not yet rebuild in this current run. This may happen for implicit rules that have multiple targets (implicit rules that build more then one target at the same time
          Target->SetCommandsMd5_32(Md5_32);
          pMakefile->AddTarget(Target);
          pMakefile->SetAutoDepsDirty();  /* We need to update the autodeps file if the md5 has been changed */
        }
        else
        {
          #ifdef _DEBUG
          if (!g_GenProjectTree)
            cout << "Md5 is different for " << Target->GetQuotedFullFileName() << " Old:"<<hex<<Target->GetCommandsMd5_32()<<", New: "<<Md5_32<<". Commandline must have been changed so recompiling\n";
          #endif

          #ifdef _DEBUG
          Indent--;
          if (g_CheckCircularDeps)
          {
            m_TargetStack.pop_back();
          }
          #endif

          MakeTarget=true;
        }
      }
    }
    if (MakeTarget)
    {
      // Queue for execution
//      Target->SetDate(YoungestDate);
      if (sm_CommandQueue.QueueTarget(Target))
        return mh_time_t();
      mh_time_t NewDate=Target->GetDate();
      if (NewDate.IsNewer(YoungestDate))
        YoungestDate=NewDate;
    }
  }

  #ifdef _DEBUG
  if (g_pPrintDependencyCheck)
  {
    for (int i=0; i<Indent; i++)
      cout<<"  ";
    cout<<"Building "<<Target->GetQuotedFullFileName()<<" finished : "<< YoungestDate << endl;
  }
  Indent--;
  if (g_CheckCircularDeps)
  {
    m_TargetStack.pop_back();
  }

  if (!m_ImplicitSearch && !Target->Exists() && !Target->IsPhony() && !g_DoNotExecute && !g_GenProjectTree)
  {
    // This is only a warning for phony messages
    cout<<"Warning: don't know how to make "<<Target->GetQuotedFullFileName()<<"\nMake the rule a phony rule to avoid this warning (but only do it when it is really phony).\n";;
  }
  #endif
  Target->SetDate(YoungestDate); /* This is especially needed for phony targets in between real targets */
  return YoungestDate;
}

///////////////////////////////////////////////////////////////////////////////
mh_time_t mhmakefileparser::WaitBuildTarget(const refptr<fileinfo> &Target)
{
  return sm_CommandQueue.WaitForTarget(Target);
}

///////////////////////////////////////////////////////////////////////////////
void mhmakefileparser::BuildIncludedMakefiles()
{
  vector< refptr<fileinfo> >::iterator MakefileIt=m_IncludedMakefiles.begin();
  while (MakefileIt!=m_IncludedMakefiles.end())
  {
    #ifdef _DEBUG
    if (g_PrintAdditionalInfo)
      cout<<"Building include file "<<(*MakefileIt)->GetQuotedFullFileName()<<endl;
    #endif
    BuildTarget(*MakefileIt);
    MakefileIt++;
  }
}