build system: taken include.mk stuff as well as compiler stuff out of generated makef...
[sdk] / ide / src / project / Project.ec
1 #ifdef ECERE_STATIC
2 public import static "ecere"
3 #else
4 public import "ecere"
5 #endif
6
7 #ifndef MAKEFILE_GENERATOR
8 import "ide"
9 // We should have the .sln/.vcproj generation even on other platforms
10 // e.g. detect from an environment variable pointing to a Windows drive
11 #ifdef __WIN32__
12 import "vsSupport"
13 #endif
14 #endif
15
16 import "ProjectConfig"
17 import "ProjectNode"
18 import "IDESettings"
19
20 default:
21
22 static void DummyFunction()
23 {
24 int a;
25 a.OnFree();
26 }
27
28 private:
29
30 extern int __ecereVMethodID_class_OnCompare;
31 extern int __ecereVMethodID_class_OnFree;
32
33 #ifdef __WIN32__
34 define cfDir = "C:/temp/";
35 #else
36 define cfDir = "/home/redj/.ecereIDE/";
37 #endif
38
39 IDESettings ideSettings;
40
41 IDESettingsContainer settingsContainer
42 {
43    driver = "JSON";
44    dataOwner = &ideSettings;
45    dataClass = class(IDESettings);
46
47    void OnLoad(GlobalSettingsData data)
48    {
49       IDESettings settings = (IDESettings)data;
50 #ifndef MAKEFILE_GENERATOR
51       globalSettingsDialog.ideSettings = settings;
52       ide.UpdateRecentMenus();
53       // ide.UpdateMakefiles(); -- can't really regenerate on Load since all recent menus changes will happen
54 #endif
55    }
56 };
57
58 #ifdef MAKEFILE_GENERATOR
59 CompilerConfig defaultCompiler;
60 #endif
61
62 // LEGACY BINARY EPJ LOADING
63
64 SetBool ParseTrueFalseValue(char * string)
65 {
66    if(!strcmpi(string, "True")) return true;
67    return false;
68 }
69
70 void ParseArrayValue(Array<String> array, char * equal)
71 {
72    char * start, * comma;
73    char * string;
74    string = CopyString(equal);
75    start = string;
76    while(start)
77    {
78       comma = strstr(start, ",");
79       if(comma)
80          comma[0] = '\0';
81       array.Add(CopyString(start));
82       if(comma)
83          comma++;
84       if(comma)
85          comma++;
86       start = comma;
87    }
88    delete string;
89 }
90
91 void ProjectNode::LegacyBinaryLoadNode(File f)
92 {
93    int len, count, c;
94    int fileNameLen;
95
96    f.Read(&len, sizeof(len), 1);
97    name = new char[len+1];
98    fileNameLen = len;
99    f.Read(name, sizeof(char), len+1);
100    f.Read(&len, sizeof(len), 1);
101    fileNameLen += len;
102    path = new char[len+1];
103    f.Read(path, sizeof(char), len+1);
104    
105    /*
106    fileName = new char[fileNameLen+2];
107    strcpy(fileName, path);
108    if(fileName[0]) strcat(fileName, "/");
109    strcat(fileName, name);
110    */
111
112    f.Read(&type, sizeof(type), 1);
113    f.Read(&count, sizeof(count), 1);
114    
115    if(type == file)
116    {
117       nodeType = file;
118       icon = NodeIcons::SelectFileIcon(name);
119    }
120    else
121    {
122       nodeType = folder;
123       icon = NodeIcons::SelectNodeIcon(type);
124    }
125
126    if(count && !files) files = { };
127    for(c = 0; c < count; c++)
128    {
129       ProjectNode child { };
130       files.Add(child);
131       child.parent = this;
132       child.indent = indent + 1;
133       LegacyBinaryLoadNode(child, f);
134    }
135 }
136
137 /*void LegacyBinarySaveNode(File f)
138 {
139    int len;
140    ProjectNode child;
141    len = strlen(name);
142    f.Write(&len, sizeof(len), 1);
143    f.Write(name, sizeof(char), len+1);
144
145    if(type == project)
146    {
147       // Projects Absolute Path Are Not Saved
148       len = 0;
149       f.Write(&len, sizeof(len), 1);
150       f.Write(&len, sizeof(char), 1);
151    }
152    else
153    {
154       len = strlen(path);
155       f.Write(&len, sizeof(len), 1);
156       f.Write(path, sizeof(char), len+1);
157    }
158    f.Write(&type, sizeof(type), 1);
159    f.Write(&children.count, sizeof(children.count), 1);
160    for(child = children.first; child; child.next)
161       child.SaveNode(f);
162 }*/
163
164 void ProjectNode::LegacyAsciiSaveNode(File f, char * indentation, char * insidePath)
165 {
166    int len;
167    char printPath[MAX_LOCATION];
168
169    if(type == project && (files.count /*|| preprocessorDefs.first*/))
170    {
171       f.Printf("\n   Files\n");
172    }
173    else if(type == file)
174    {
175       if(!strcmp(path, insidePath))
176          f.Printf("%s - %s\n", indentation, name);
177       else
178       {
179          strcpy(printPath, path);
180          len = strlen(printPath);
181          if(len)
182             if(printPath[len-1] != '/')
183                strcat(printPath, "/");
184          strcat(printPath, name);
185          f.Printf("%s = %s\n", indentation, printPath);
186       }
187       if(files.count)
188          f.Printf("\nError\n\n");
189    }
190    else if(type == folder)
191    {
192       f.Printf("%s + %s\n", indentation, name);
193    }
194    else if(type == resources && files.count)
195    {
196       PathCatSlash(insidePath, path);
197       f.Printf("\n%sResources\n", indentation);
198       if(path && path[0])
199          f.Printf("%s   Path = %s\n", indentation, path);
200    }
201    
202    /*if(buildExclusions.first && type != project)
203    {
204       for(item = buildExclusions.first; item; item = item.next)
205       {
206          if(item == buildExclusions.first)
207             f.Printf("%s      Build Exclusions = %s", indentation, item.name);
208          else
209             f.Printf(", %s", item.name);
210       }
211       f.Printf("\n");
212    }
213
214    if(preprocessorDefs.first && (type == project || ((type == file || type == folder) && !isInResources)))
215    {
216       for(item = preprocessorDefs.first; item; item = item.next)
217       {
218          if(item == preprocessorDefs.first)
219             f.Printf("%s%s   Preprocessor Definitions = %s", indentation, type == project ? "" : "   ", item.name);
220          else
221             f.Printf(", %s", item.name);
222       }
223       f.Printf("\n");
224    }
225    */
226    
227    if(type == project && (files.count /*|| preprocessorDefs.first*/))
228    {
229       f.Printf("\n");
230       for(child : files)
231          LegacyAsciiSaveNode(child, f, indentation, insidePath);
232    }
233    else if(type == folder)
234    {
235       strcat(indentation, "   ");
236       // WHAT WAS THIS: strcpy(printPath, path);
237       // TOCHECK: why is Unix/PathCat not used here
238       len = strlen(insidePath);
239       if(len)
240          if(insidePath[len-1] != '/')
241             strcat(insidePath, "/");
242       strcat(insidePath, name);
243
244       for(child : files)
245          LegacyAsciiSaveNode(child, f, indentation, insidePath);
246       f.Printf("%s -\n", indentation);
247       indentation[strlen(indentation) - 3] = '\0';
248       StripLastDirectory(insidePath, insidePath);
249    }
250    else if(type == resources && files.count)
251    {
252       f.Printf("\n");
253       for(child : files)
254          LegacyAsciiSaveNode(child, f, indentation, insidePath);
255       StripLastDirectory(insidePath, insidePath);
256    }
257 }
258
259 /*
260 void ProjectConfig::LegacyProjectConfigSave(File f)
261 {
262    char * indentation = "      ";
263    //if(isCommonConfig)
264       //f.Printf("\n * Common\n");
265    //else
266       f.Printf("\n + %s\n", name);
267    f.Printf("\n   Compiler\n\n");
268    if(objDir.expression[0])
269       f.Printf("%sIntermediate Directory = %s\n", indentation, objDir.expression);
270    f.Printf("%sDebug = %s\n", indentation, (options.debug == true) ? "True" : "False");
271    switch(options.optimization)
272    {
273       // case none:   f.Printf("%sOptimize = %s\n", indentation, "None"); break;
274       case speed: f.Printf("%sOptimize = %s\n", indentation, "Speed"); break;
275       case size:  f.Printf("%sOptimize = %s\n", indentation, "Size");  break;
276    }
277    f.Printf("%sAllWarnings = %s\n", indentation, (options.warnings == all) ? "True" : "False");
278    if(options.profile)
279       f.Printf("%sProfile = %s\n", indentation, (options.profile == true) ? "True" : "False");
280    if(options.memoryGuard == true)
281       f.Printf("%sMemoryGuard = %s\n", indentation, (options.memoryGuard == true) ? "True" : "False");
282    if(options.strictNameSpaces == true)
283       f.Printf("%sStrict Name Spaces = %s\n", indentation, (options.strictNameSpaces == true) ? "True" : "False");
284    if(options.defaultNameSpace && strlen(options.defaultNameSpace))
285       f.Printf("%sDefault Name Space = %s\n", indentation, options.defaultNameSpace);
286     TOFIX: Compiler Bug {
287       if(options.preprocessorDefinitions.count)
288       {
289          bool isFirst = true;
290          for(item : options.preprocessorDefinitions)
291          {
292             if(isFirst)
293             {
294                f.Printf("\n%sPreprocessor Definitions = %s", indentation, item);
295                isFirst = false;
296             }
297             else
298                f.Printf(", %s", item);
299          }
300          f.Printf("\n");
301       }
302    }
303    if(options.includeDirs.count)
304    {
305       f.Printf("\n%sInclude Directories\n", indentation);
306       for(item : options.includeDirs)
307          f.Printf("%s - %s\n", indentation, name);
308       f.Printf("\n");
309    }
310
311    f.Printf("\n%sLinker\n\n", indentation);
312    f.Printf("%sTarget Name = %s\n", indentation, options.targetFileName);
313    switch(options.targetType)
314    {
315       case executable:     f.Printf("%sTarget Type = %s\n", indentation, "Executable"); break;
316       case sharedLibrary:  f.Printf("%sTarget Type = %s\n", indentation, "Shared");     break;
317       case staticLibrary:  f.Printf("%sTarget Type = %s\n", indentation, "Static");     break;
318    }
319    if(targetDir.expression[0])
320       f.Printf("%sTarget Directory = %s\n", indentation, targetDir.expression);
321    if(options.console)
322       f.Printf("%sConsole = %s\n", indentation, options.console ? "True" : "False");
323    if(options.compress)
324       f.Printf("%sCompress = %s\n", indentation, options.compress ? "True" : "False");
325    if(options.libraries.count)
326    {
327       bool isFirst = true;
328       for(item : options.libraries)
329       {
330          if(isFirst)
331          {
332             f.Printf("\n%sLibraries = %s", indentation, name);
333             isFirst = false;
334          }
335          else
336             f.Printf(", %s", item);
337       }
338       f.Printf("\n");
339    }
340    if(options.libraryDirs.count)
341    {
342       f.Printf("\n%sLibrary Directories\n\n", indentation);
343       for(item : options.libraryDirs)
344          f.Printf("       - %s\n", indentation, item);
345    }
346 }
347
348 void LegacyAsciiSaveProject(File f, Project project)
349 {
350    char indentation[128*3];
351    char path[MAX_LOCATION];
352
353    f.Printf("\nECERE Project File : Format Version 0.1b\n");
354    f.Printf("\nDescription\n%s\n.\n", project.description);
355    f.Printf("\nLicense\n%s\n.\n", project.license);
356    f.Printf("\nModule Name = %s\n", project.moduleName);
357    f.Printf("\n   Configurations\n");
358    //////////////////////////////////////commonConfig.Save(f, true);
359    for(cfg : project.configurations)
360       LegacyProjectConfigSave(cfg, f);
361
362    strcpy(indentation, "   ");
363    path[0] = '\0';
364    LegacyAsciiSaveNode(project.topNode, f, indentation, path);
365    // f.Printf("\n");
366    delete f;
367 }
368 */
369
370 // *** NEW JSON PROJECT FORMAT ***
371 public enum ProjectNodeType { file, folder };
372
373 // *******************************
374
375 define PEEK_RESOLUTION = (18.2 * 10);
376
377 // On Windows & UNIX
378 #define SEPS    "/"
379 #define SEP     '/'
380
381 static byte epjSignature[] = { 'E', 'P', 'J', 0x04, 0x01, 0x12, 0x03, 0x12 };
382
383 enum GenMakefilePrintTypes { objects, cObjects, symbols, imports, sources, resources, eCsources };
384
385 define WorkspaceExtension = "ews";
386 define ProjectExtension = "epj";
387
388 define stringInFileIncludedFrom = "In file included from ";
389
390 void ReplaceSpaces(char * output, char * source)
391 {
392    int c, dc;
393    char ch, pch = 0;
394
395    for(c = 0, dc = 0; (ch = source[c]); c++, dc++)
396    {
397       if(ch == ' ') output[dc++] = '\\';
398       if(pch != '$')
399       {
400          if(ch == '(' || ch == ')') output[dc++] = '\\';
401          pch = ch;
402       }
403       else if(ch == ')')
404          pch = 0;
405       output[dc] = ch;
406    }
407    output[dc] = '\0';
408 }
409
410 void ReplaceUnwantedMakeChars(char * output, char * source)
411 {
412    int c, dc;
413    char ch, pch = 0;
414
415    for(c = 0, dc = 0; (ch = source[c]); c++, dc++)
416    {
417       if(pch != '$')
418       {
419          if(ch == '(' || ch == ')') output[dc++] = '\\';
420          pch = ch;
421       }
422       else if(ch == ')')
423          pch = 0;
424       if(ch == ' ')
425          output[dc] = 127;
426       else
427          output[dc] = ch;
428    }
429    output[dc] = '\0';
430 }
431
432 static void OutputNoSpace(File f, char * source)
433 {
434    char * output = new char[strlen(source)+1024];
435    ReplaceSpaces(output, source);
436    f.Puts(output);
437    delete output;
438 }
439
440 enum ListOutputMethod { inPlace, newLine, lineEach };
441
442 int OutputFileList(File f, char * name, Array<String> list, Map<String, int> varStringLenDiffs, char * prefix)
443 {
444    int numOfBreaks = 0;
445    const int breakListLength = 1536;
446    const int breakLineLength = 78; // TODO: turn this into an option.
447
448    int c, len, itemCount = 0;
449    Array<int> breaks { };
450    if(list.count)
451    {
452       int charCount = 0;
453       MapNode<String, int> mn;
454       for(c=0; c<list.count; c++)
455       {
456          len = strlen(list[c]) + 3;
457          if(strstr(list[c], "$(") && varStringLenDiffs && varStringLenDiffs.count)
458          {
459             for(mn = varStringLenDiffs.root.minimum; mn; mn = mn.next)
460             {
461                if(strstr(list[c], mn.key))
462                   len += mn.value;
463             }
464          }
465          if(charCount + len > breakListLength)
466          {
467             breaks.Add(itemCount);
468             itemCount = 0;
469             charCount = len;
470          }
471          itemCount++;
472          charCount += len;
473       }
474       if(itemCount)
475          breaks.Add(itemCount);
476       numOfBreaks = breaks.count;
477    }
478
479    if(numOfBreaks > 1)
480    {
481       f.Printf("%s =%s%s", name, prefix ? " " : "", prefix ? prefix : "");
482       for(c=0; c<numOfBreaks; c++)
483          f.Printf(" $(%s%d)", name, c+1);
484       f.Printf("\n");
485    }
486    else
487       f.Printf("%s =%s%s", name, prefix ? " " : "", prefix ? prefix : "");
488
489    if(numOfBreaks)
490    {
491       int n, offset = 0;
492
493       for(c=0; c<numOfBreaks; c++)
494       {
495          if(numOfBreaks > 1)
496             f.Printf("%s%d =", name, c+1);
497          
498          len = 3;
499          itemCount = breaks[c];
500          for(n=offset; n<offset+itemCount; n++)
501          {
502             if(false) // TODO: turn this into an option.
503             {
504                int itemLen = strlen(list[n]);
505                if(len > 3 && len + itemLen > breakLineLength)
506                {
507                   f.Printf(" \\\n\t%s", list[n]);
508                   len = 3;
509                }
510                else
511                {
512                   len += itemLen;
513                   f.Printf(" %s", list[n]);
514                }
515             }
516             else
517                f.Printf(" \\\n\t%s", list[n]);
518          }
519          offset += itemCount;
520          f.Printf("\n");
521       }
522       list.Free();
523       list.count = 0;
524    }
525    else
526       f.Printf("\n");
527    f.Printf("\n");
528    delete breaks;
529    return numOfBreaks;
530 }
531
532 void OutputCleanActions(File f, char * name, int parts)
533 {
534    if(parts > 1)
535    {
536       int c;
537       for(c=0; c<parts; c++)
538          f.Printf("\t$(call rmq,$(%s%d))\n", name, c+1);
539    }
540    else
541       f.Printf("\t$(call rmq,$(%s))\n", name);
542 }
543
544 void OutputListOption(File f, char * option, Array<String> list, ListOutputMethod method, bool noSpace)
545 {
546    if(list.count)
547    {
548       if(method == newLine)
549          f.Printf(" \\\n\t");
550       for(item : list)
551       {
552          if(method == lineEach)
553             f.Printf(" \\\n\t");
554          f.Printf(" -%s", option);
555          if(noSpace)
556             OutputNoSpace(f, item);
557          else
558             f.Printf("%s", item);
559       }
560    }
561 }
562
563 static void OutputLibraries(File f, Array<String> libraries)
564 {
565    for(item : libraries)
566    {
567       char ext[MAX_EXTENSION];
568       char temp[MAX_LOCATION];
569       char * s = item;
570       GetExtension(item, ext);
571       if(!strcmp(ext, "o") || !strcmp(ext, "a"))
572          f.Printf(" ");
573       else
574       {
575          if(!strcmp(ext, "so") || !strcmp(ext, "dylib"))
576          {
577             if(!strncmp(item, "lib", 3))
578                strcpy(temp, item + 3);
579             else
580                strcpy(temp, item);
581             StripExtension(temp);
582             s = temp;
583          } 
584          f.Printf(" -l");
585       }
586       OutputNoSpace(f, s);
587    }
588 }
589
590 void CamelCase(char * string)
591 {
592    int c, len = strlen(string);
593    for(c=0; c<len && string[c] >= 'A' && string[c] <= 'Z'; c++)
594       string[c] = (char)tolower(string[c]);
595 }
596
597 CompilerConfig GetCompilerConfig()
598 {
599 #ifndef MAKEFILE_GENERATOR
600    CompilerConfig compiler = null;
601    if(ide && ide.workspace)
602       compiler = ideSettings.GetCompilerConfig(ide.workspace.compiler);
603    return compiler;
604 #else
605    incref defaultCompiler;
606    return defaultCompiler;
607 #endif
608 }
609
610 define localTargetType = config && config.options && config.options.targetType ?
611             config.options.targetType : options && options.targetType ?
612             options.targetType : TargetTypes::executable;
613 define localWarnings = config && config.options && config.options.warnings ?
614             config.options.warnings : options && options.warnings ?
615             options.warnings : WarningsOption::unset;
616 define localDebug = config && config.options && config.options.debug ?
617             config.options.debug : options && options.debug ?
618             options.debug : SetBool::unset;
619 define localMemoryGuard = config && config.options && config.options.memoryGuard ?
620             config.options.memoryGuard : options && options.memoryGuard ?
621             options.memoryGuard : SetBool::unset;
622 define localNoLineNumbers = config && config.options && config.options.noLineNumbers ?
623             config.options.noLineNumbers : options && options.noLineNumbers ?
624             options.noLineNumbers : SetBool::unset;
625 define localProfile = config && config.options && config.options.profile ?
626             config.options.profile : options && options.profile ?
627             options.profile : SetBool::unset;
628 define localOptimization = config && config.options && config.options.optimization ?
629             config.options.optimization : options && options.optimization ?
630             options.optimization : OptimizationStrategy::none;
631 define localDefaultNameSpace = config && config.options && config.options.defaultNameSpace ?
632             config.options.defaultNameSpace : options && options.defaultNameSpace ?
633             options.defaultNameSpace : null;
634 define localStrictNameSpaces = config && config.options && config.options.strictNameSpaces ?
635             config.options.strictNameSpaces : options && options.strictNameSpaces ?
636             options.strictNameSpaces : SetBool::unset;
637 // TODO: I would rather have null here, check if it'll be ok, have the property return "" if required
638 define localTargetFileName = config && config.options && config.options.targetFileName ?
639             config.options.targetFileName : options && options.targetFileName ?
640             options.targetFileName : "";
641 define localTargetDirectory = config && config.options && config.options.targetDirectory && config.options.targetDirectory[0] ?
642             config.options.targetDirectory : options && options.targetDirectory && options.targetDirectory[0] ?
643             options.targetDirectory : null;
644 define settingsTargetDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
645             ideSettings.projectDefaultIntermediateObjDir[0] ?
646             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
647 define localObjectsDirectory = config && config.options && config.options.objectsDirectory && config.options.objectsDirectory[0] ?
648             config.options.objectsDirectory : options && options.objectsDirectory && options.objectsDirectory[0] ?
649             options.objectsDirectory : null;
650 define settingsObjectsDirectory = ideSettings && ideSettings.projectDefaultIntermediateObjDir &&
651             ideSettings.projectDefaultIntermediateObjDir[0] ?
652             ideSettings.projectDefaultIntermediateObjDir : defaultObjDirExpression;
653 define localConsole = config && config.options && config.options.console ?
654             config.options.console : options && options.console ?
655             options.console : SetBool::unset;
656 define localCompress = config && config.options && config.options.compress ?
657             config.options.compress : options && options.compress ?
658             options.compress : SetBool::unset;
659
660 define platformTargetType =
661          configPOs && configPOs.options && configPOs.options.targetType && configPOs.options.targetType != localTargetType ?
662                configPOs.options.targetType :
663          projectPOs && projectPOs.options && projectPOs.options.targetType && projectPOs.options.targetType != localTargetType ?
664                projectPOs.options.targetType : TargetTypes::unset;
665
666
667 // we should have some kind of direct mapping between a platform and it's makefile variable
668 char * PlatformToMakefileVariable(Platform platform)
669 {
670    return platform == win32 ? "WINDOWS" :
671           platform == tux   ? "LINUX"   :
672           platform == apple ? "OSX"/*"APPLE"*/ :
673                               platform;
674 }
675
676 char * TargetTypeToMakefileVariable(TargetTypes targetType)
677 {
678    return targetType == executable    ? "executable" :
679           targetType == sharedLibrary ? "sharedlib"  :
680           targetType == staticLibrary ? "staticlib"  :
681                                         "unknown";
682 }
683
684 // Move this to ProjectConfig? null vs Common to consider...
685 char * GetConfigName(ProjectConfig config)
686 {
687    return config ? config.name : "Common";
688 }
689
690 class Project : struct
691 {
692    class_no_expansion;  // To use Find on the Container<Project> in Workspace::projects
693                         // We might want to tweak this default behavior of regular classes ?
694                         // Expansion/the current default kind of Find matching we want for things like BitmapResource, FontResource (Also regular classes)
695 public:
696    float version;
697    String moduleName;
698
699    property ProjectOptions options { get { return options; } set { options = value; } isset { return options && !options.isEmpty; } }
700    property Array<PlatformOptions> platforms
701    {
702       get { return platforms; }
703       set
704       {
705          if(platforms) { platforms.Free(); delete platforms; }
706          if(value)
707          {
708             List<PlatformOptions> empty { };
709             Iterator<PlatformOptions> it { value };
710             platforms = value;
711             for(p : platforms; !p.options || p.options.isEmpty) empty.Add(p);
712             for(p : empty; it.Find(p)) platforms.Delete(it.pointer);
713             delete empty;
714          }
715       }
716       isset
717       {
718          if(platforms)
719          {
720             for(p : platforms)
721             {
722                if(p.options && !p.options.isEmpty)
723                   return true;
724             }
725          }
726          return false;
727       }
728    }
729    List<ProjectConfig> configurations;
730    LinkList<ProjectNode> files;
731    String resourcesPath;
732    LinkList<ProjectNode> resources;
733
734    property char * description
735    {
736       set { delete description; if(value && value[0]) description = CopyString(value); }
737       get { return description ? description : ""; }
738       isset { return description != null && description[0]; }
739    }
740
741    property char * license
742    {
743       set { delete license; if(value && value[0]) license = CopyString(value); }
744       get { return license ? license : ""; }
745       isset { return license != null && license[0]; }
746    }
747
748 private:
749    // topNode.name holds the file name (.epj)
750    ProjectOptions options;
751    Array<PlatformOptions> platforms;
752    ProjectNode topNode { type = project, icon = epjFile, files = LinkList<ProjectNode>{ }, project = this };
753    ProjectNode resNode;
754
755    ProjectConfig config;
756    String filePath;
757    // This is the file name stripped of the epj extension
758    // It should NOT be edited, saved or loaded anywhere
759    String name;
760
761    String description;
762    String license;
763
764    ~Project()
765    {
766       /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
767       topNode.configurations = null;
768       topNode.platforms = null;
769       topNode.options = null;
770       */
771
772       if(platforms) { platforms.Free(); delete platforms; }
773       if(configurations) { configurations.Free(); delete configurations; }
774       if(files) { files.Free(); delete files; }
775       if(resources) { resources.Free(); delete resources; }
776       delete options;
777       delete resourcesPath;
778
779       delete description;
780       delete license;
781       delete moduleName;
782       delete filePath;
783       delete topNode;
784       delete name;
785    }
786
787    property ProjectConfig config
788    {
789       set
790       {
791          config = value;
792          delete topNode.info;
793          topNode.info = CopyString(GetConfigName(config));
794       }
795    }
796    property char * filePath
797    {
798       set
799       {
800          if(value)
801          {
802             char string[MAX_LOCATION];
803             GetLastDirectory(value, string);
804             delete topNode.name;
805             topNode.name = CopyString(string);
806             StripExtension(string);
807             delete name;
808             name = CopyString(string);
809             StripLastDirectory(value, string);
810             delete topNode.path;
811             topNode.path = CopyString(string);
812             delete filePath;
813             filePath = CopyString(value);
814          }
815       }
816    }
817
818    TargetTypes GetTargetType(ProjectConfig config)
819    {
820       TargetTypes targetType = localTargetType;
821       return targetType;
822    }
823
824    bool GetTargetTypeIsSetByPlatform(ProjectConfig config)
825    {
826       Platform platform;
827       for(platform = (Platform)1; platform < Platform::enumSize; platform++)
828       {
829          PlatformOptions projectPOs, configPOs;
830          MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
831          if(platformTargetType)
832             return true;
833       }
834       return false;
835    }
836
837
838    char * GetObjDirExpression(CompilerConfig compiler, ProjectConfig config)
839    {
840       // TODO: Support platform options
841       char * expression = localObjectsDirectory;
842       if(!expression)
843          expression = settingsObjectsDirectory;
844       return expression;
845    }
846
847    DirExpression GetObjDir(CompilerConfig compiler, ProjectConfig config)
848    {
849       char * expression = GetObjDirExpression(compiler, config);
850       DirExpression objDir { type = intermediateObjectsDir };
851       objDir.Evaluate(expression, this, compiler, config);
852       return objDir;
853    }
854
855    char * GetTargetDirExpression(CompilerConfig compiler, ProjectConfig config)
856    {
857       // TODO: Support platform options
858       char * expression = localTargetDirectory;
859       if(!expression)
860          expression = settingsTargetDirectory;
861       return expression;
862    }
863
864    DirExpression GetTargetDir(CompilerConfig compiler, ProjectConfig config)
865    {
866       char * expression = GetTargetDirExpression(compiler, config);
867       DirExpression targetDir { type = DirExpressionType::targetDir /*intermediateObjectsDir*/};
868       targetDir.Evaluate(expression, this, compiler, config);
869       return targetDir;
870    }
871
872    WarningsOption GetWarnings(ProjectConfig config)
873    {
874       WarningsOption warnings = localWarnings;
875       return warnings;
876    }
877
878    bool GetDebug(ProjectConfig config)
879    {
880       SetBool debug = localDebug;
881       return debug == true;
882    }
883
884    bool GetMemoryGuard(ProjectConfig config)
885    {
886       SetBool memoryGuard = localMemoryGuard;
887       return memoryGuard == true;
888    }
889
890    bool GetNoLineNumbers(ProjectConfig config)
891    {
892       SetBool noLineNumbers = localNoLineNumbers;
893       return noLineNumbers == true;
894    }
895
896    bool GetProfile(ProjectConfig config)
897    {
898       SetBool profile = localProfile;
899       return profile == true;
900    }
901
902    OptimizationStrategy GetOptimization(ProjectConfig config)
903    {
904       OptimizationStrategy optimization = localOptimization;
905       return optimization;
906    }
907
908    String GetDefaultNameSpace(ProjectConfig config)
909    {
910       String defaultNameSpace = localDefaultNameSpace;
911       return defaultNameSpace;
912    }
913
914    bool GetStrictNameSpaces(ProjectConfig config)
915    {
916       SetBool strictNameSpaces = localStrictNameSpaces;
917       return strictNameSpaces == true;
918    }
919
920    String GetTargetFileName(ProjectConfig config)
921    {
922       String targetFileName = localTargetFileName;
923       return targetFileName;
924    }
925
926    //String targetDirectory;
927    //String objectsDirectory;
928    bool GetConsole(ProjectConfig config)
929    {
930       SetBool console = localConsole;
931       return console == true;
932    }
933
934    bool GetCompress(ProjectConfig config)
935    {
936       SetBool compress = localCompress;
937       return compress == true;
938    }
939    //SetBool excludeFromBuild;
940
941    bool GetConfigIsInActiveDebugSession(ProjectConfig config)
942    {
943 #ifndef MAKEFILE_GENERATOR
944       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isActive;
945 #endif
946    }
947
948    bool GetConfigIsInDebugSession(ProjectConfig config)
949    {
950 #ifndef MAKEFILE_GENERATOR
951       return ide.project == this && ide.debugger && ide.debugger.prjConfig == config && ide.debugger.isPrepared;
952 #endif
953    }
954
955    void SetPath(bool projectsDirs, CompilerConfig compiler, ProjectConfig config)
956    {
957 #ifndef MAKEFILE_GENERATOR
958       ide.SetPath(projectsDirs, compiler, config);
959 #endif
960    }
961
962 #ifndef MAKEFILE_GENERATOR
963    bool Save(char * fileName)
964    {
965       File f;
966       /*char output[MAX_LOCATION];
967        ChangeExtension(fileName, "json", output);
968       f = FileOpen(output, write);*/
969       f = FileOpen(fileName, write);
970       if(f)
971       {
972          files = topNode.files;
973          resources = resNode.files;
974          resourcesPath = resNode.path;
975
976          files.Remove(resNode);
977          version = 0.2f;
978
979          WriteJSONObject(f, class(Project), this, 0);
980
981          files.Add(resNode);
982
983          files = null;
984          resources = null;
985          resourcesPath = null;
986          delete f;
987       }
988       return true;
989    }
990 #endif
991
992 #ifndef MAKEFILE_GENERATOR
993    bool GetRelativePath(char * filePath, char * relativePath)
994    {
995       ProjectNode node;
996       char moduleName[MAX_FILENAME];
997       GetLastDirectory(filePath, moduleName);
998       // try with workspace dir first?
999       if((node = topNode.Find(moduleName, false)))
1000       {
1001          strcpy(relativePath, strcmp(node.path, ".") ? node.path : "");
1002          PathCatSlash(relativePath, node.name);
1003          return true;
1004       }
1005       // WARNING: On failure, relative path is uninitialized
1006       return false;   
1007    }
1008 #endif
1009
1010    void CatTargetFileName(char * string, CompilerConfig compiler, ProjectConfig config)
1011    {
1012       TargetTypes targetType = GetTargetType(config);
1013       String targetFileName = GetTargetFileName(config);
1014       if(targetType == staticLibrary)
1015       {
1016          PathCatSlash(string, "lib");
1017          strcat(string, targetFileName);
1018       }
1019       else if(compiler.targetPlatform != win32 && targetType == sharedLibrary)
1020       {
1021          PathCatSlash(string, "lib");
1022          strcat(string, targetFileName);
1023       }
1024       else
1025          PathCatSlash(string, targetFileName);
1026       
1027       switch(targetType)
1028       {
1029          case executable:
1030             if(compiler.targetPlatform == win32)
1031                strcat(string, ".exe");
1032             break;
1033          case sharedLibrary:
1034             if(compiler.targetPlatform == win32)
1035                strcat(string, ".dll");
1036             else if(compiler.targetPlatform == apple)
1037                strcat(string, ".dylib");
1038             else
1039                strcat(string, ".so");
1040             break;
1041          case staticLibrary:
1042             strcat(string, ".a");
1043             break;
1044       }
1045    }
1046
1047    void CatMakeFileName(char * string, CompilerConfig compiler, ProjectConfig config)
1048    {
1049       char projectName[MAX_LOCATION];
1050       strcpy(projectName, name);
1051       if(strcmpi(compiler.name, defaultCompilerName))
1052          sprintf(string, "%s-%s-%s.Makefile", projectName, compiler.name, config.name);
1053       else
1054          sprintf(string, "%s%s%s.Makefile", projectName, config ? "-" : "", config ? config.name : "");
1055    }
1056
1057 #ifndef MAKEFILE_GENERATOR
1058    void MarkChanges(ProjectNode node)
1059    {
1060       for(cfg : topNode.configurations)
1061       {
1062          ProjectConfig c = null;
1063          for(i : node.configurations; !strcmpi(i.name, cfg.name)) { c = i; break; }
1064
1065          if(c && ((c.options && cfg.options && cfg.options.console != c.options.console) ||
1066                (!c.options || !cfg.options)))
1067             cfg.symbolGenModified = true;
1068
1069          cfg.makingModified = true;
1070       }
1071    }
1072
1073    void ModifiedAllConfigs(bool making, bool compiling, bool linking, bool symbolGen)
1074    {
1075       for(cfg : configurations)
1076       {
1077          if(making)
1078             cfg.makingModified = true;
1079          if(compiling)
1080             cfg.compilingModified = true;
1081          if(linking)
1082             cfg.linkingModified = true;
1083          if(symbolGen)
1084             cfg.symbolGenModified = true;
1085       }
1086       if(compiling || linking)
1087       {
1088          ide.projectView.modifiedDocument = true;
1089          ide.workspace.modified = true;
1090       }
1091    }
1092    
1093    void RotateActiveConfig(bool forward)
1094    {
1095       if(configurations.first && configurations.last != configurations.first)
1096       {
1097          Iterator<ProjectConfig> cfg { configurations };
1098          while(forward ? cfg.Next() : cfg.Prev())
1099             if(cfg.data == config)
1100                break;
1101
1102          if(forward)
1103          {
1104             if(!cfg.Next())
1105                cfg.Next();
1106          }
1107          else
1108          {
1109             if(!cfg.Prev())
1110                cfg.Prev();
1111          }
1112
1113          property::config = cfg.data;
1114          ide.workspace.modified = true;
1115          ide.projectView.Update(null);
1116       }
1117    }
1118
1119    void ProcessPipeOutputRaw(DualPipe f)
1120    {
1121       char line[65536];
1122       while(!f.Eof() && !ide.ShouldStopBuild())
1123       {
1124          bool result = true;
1125          double lastTime = GetTime();
1126          bool wait = true;
1127          while(result)
1128          {
1129             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1130             {
1131                ide.outputView.buildBox.Logf("%s\n", line);
1132             }
1133             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1134          }
1135          //printf("Processing Input...\n");
1136          if(app.ProcessInput(true))
1137             wait = false;
1138          app.UpdateDisplay();
1139          if(wait)
1140          {
1141             //printf("Waiting...\n");
1142             app.Wait();
1143          }
1144          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1145       }
1146       if(ide.ShouldStopBuild())
1147       {
1148          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1149          f.Terminate();
1150       }
1151    }
1152
1153    bool ProcessBuildPipeOutput(DualPipe f, DirExpression objDirExp, bool isARun, ProjectNode onlyNode,
1154       CompilerConfig compiler, ProjectConfig config)
1155    {
1156       char line[65536];
1157       bool compiling = false, linking = false, precompiling = false;
1158       int compilingEC = 0;
1159       int numErrors = 0, numWarnings = 0;
1160       bool loggedALine = false;
1161       char * configName = config.name;
1162       int lenMakeCommand = strlen(compiler.makeCommand);
1163
1164       char cppCommand[MAX_LOCATION];
1165       char ccCommand[MAX_LOCATION];
1166       char ecpCommand[MAX_LOCATION];
1167       char eccCommand[MAX_LOCATION];
1168       char ecsCommand[MAX_LOCATION];
1169       char earCommand[MAX_LOCATION];
1170
1171       char * cc = compiler.ccCommand;
1172       char * cpp = compiler.cppCommand;
1173       sprintf(cppCommand, "%s%s%s%s ",
1174             compiler.ccacheEnabled ? "ccache " : "",
1175             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1176             compiler.distccEnabled ? "distcc " : "",
1177             compiler.cppCommand);
1178       sprintf(ccCommand, "%s%s%s%s ",
1179             compiler.ccacheEnabled ? "ccache " : "",
1180             compiler.ccacheEnabled && !compiler.distccEnabled ? " " : "",
1181             compiler.distccEnabled ? "distcc " : "",
1182             compiler.ccCommand);
1183       sprintf(ecpCommand, "%s ", compiler.ecpCommand);
1184       sprintf(eccCommand, "%s ", compiler.eccCommand);
1185       sprintf(ecsCommand, "%s ", compiler.ecsCommand);
1186       sprintf(earCommand, "%s ", compiler.earCommand);
1187
1188       while(!f.Eof() && !ide.ShouldStopBuild())
1189       {
1190          bool result = true;
1191          double lastTime = GetTime();
1192          bool wait = true;
1193          while(result)
1194          {
1195             //printf("Peeking and GetLine...\n");
1196             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1197             {
1198                char * inFileIncludedFrom = strstr(line, stringInFileIncludedFrom);
1199                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':')
1200                {
1201                   char * module = strstr(line, "No rule to make target `");
1202                   if(module)
1203                   {
1204                      char * end;
1205                      module = strchr(module, '`') + 1;
1206                      end = strchr(module, '\'');
1207                      if(end)
1208                      {
1209                         *end = '\0';
1210                         ide.outputView.buildBox.Logf($"   %s: No such file or directory\n", module);
1211                         // ide.outputView.buildBox.Logf("error: %s\n   No such file or directory\n", module);
1212                         numErrors++;
1213                      }
1214                   }
1215                   //else
1216                   //{
1217                      //ide.outputView.buildBox.Logf("error: %s\n", line);
1218                      //numErrors++;
1219                   //}
1220                }
1221                else if(strstr(line, "ear ") == line);
1222                else if(strstr(line, "strip ") == line);
1223                else if(strstr(line, ccCommand) == line || strstr(line, ecpCommand) == line || strstr(line, eccCommand) == line)
1224                {
1225                   char moduleName[MAX_FILENAME];
1226                   byte * tokens[1];
1227                   char * module;
1228                   bool isPrecomp = false;
1229
1230                   if(strstr(line, ccCommand) == line)
1231                   {
1232                      module = strstr(line, " -c ");
1233                      if(module) module += 4;
1234                   }
1235                   else if(strstr(line, eccCommand) == line)
1236                   {
1237                      module = strstr(line, " -c ");
1238                      if(module) module += 4;
1239                      //module = line + 3;
1240                      // Don't show GCC warnings about generated C code because it does not compile clean yet...
1241                      compilingEC = 3;//2;
1242                   }
1243                   else if(strstr(line, ecpCommand) == line)
1244                   {
1245                      // module = line + 8;
1246                      module = strstr(line, " -c ");
1247                      if(module) module += 4;
1248                      isPrecomp = true;
1249                      compilingEC = 0;
1250                   }
1251
1252                   loggedALine = true;
1253
1254                   if(module)
1255                   {
1256                      if(!compiling && !isPrecomp)
1257                      {
1258                         ide.outputView.buildBox.Logf($"Compiling...\n");
1259                         compiling = true;
1260                      }
1261                      else if(!precompiling && isPrecomp)
1262                      {
1263                         ide.outputView.buildBox.Logf($"Generating symbols...\n");
1264                         precompiling = true;
1265                      }
1266                      // Changed escapeBackSlashes here to handle paths with spaces
1267                      Tokenize(module, 1, tokens, true); // false);
1268                      GetLastDirectory(module, moduleName);
1269                      ide.outputView.buildBox.Logf("%s\n", moduleName);
1270                   }
1271                   else if((module = strstr(line, " -o ")))
1272                   {
1273                      compiling = false;
1274                      precompiling = false;
1275                      linking = true;
1276                      ide.outputView.buildBox.Logf($"Linking...\n");
1277                   }
1278                   else
1279                   {
1280                      ide.outputView.buildBox.Logf("%s\n", line);
1281                      numErrors++;
1282                   }
1283
1284                   if(compilingEC) compilingEC--;
1285                }
1286                else if(strstr(line, "ar rcs") == line)
1287                   ide.outputView.buildBox.Logf($"Building library...\n");
1288                else if(strstr(line, ecsCommand) == line)
1289                   ide.outputView.buildBox.Logf($"Writing symbol loader...\n");
1290                else
1291                {
1292                   if(linking || compiling || precompiling)
1293                   {
1294                      char * colon = strstr(line, ":"); //, * bracket;
1295                      if(colon && (colon[1] == '/' || colon[1] == '\\'))
1296                         colon = strstr(colon + 1, ":");
1297                      if(colon)
1298                      {
1299                         char moduleName[MAX_LOCATION], temp[MAX_LOCATION];
1300                         char * pointer;
1301                         char * error;
1302                         char * start = inFileIncludedFrom ? line + strlen(stringInFileIncludedFrom) : line;
1303                         int len = (int)(colon - start);
1304                         len = Min(len, MAX_LOCATION-1);
1305                         // Don't be mistaken by the drive letter colon
1306                         // Cut module name
1307                         // TODO: need to fix colon - line gives char *
1308                         // warning: incompatible expression colon - line (char *); expected int
1309                         /*
1310                         strncpy(moduleName, line, (int)(colon - line));
1311                         moduleName[colon - line] = '\0';
1312                         */
1313                         strncpy(moduleName, start, len);
1314                         moduleName[len] = '\0';
1315                         // Remove stuff in brackets
1316                         //bracket = strstr(moduleName, "(");
1317                         //if(bracket) *bracket = '\0';
1318
1319                         GetLastDirectory(moduleName, temp);
1320                         if(linking && (!strcmp(temp, "ld") || !strcmp(temp, "ld.exe")))
1321                         {
1322                            numErrors++;
1323                            strcpy(moduleName, $"Linker Error");
1324                         }
1325                         else
1326                         {
1327                            strcpy(temp, topNode.path);
1328                            PathCatSlash(temp, moduleName);
1329                            MakePathRelative(temp, topNode.path, moduleName);
1330                         }
1331                         if(strstr(line, "error:"))
1332                            numErrors ++;
1333                         else
1334                         {
1335                            // Silence warnings for compiled EC
1336                            char * objDir = strstr(moduleName, objDirExp.dir);
1337                         
1338                            if(linking)
1339                            {
1340                               if((pointer = strstr(line, "undefined"))  ||
1341                                    (pointer = strstr(line, "No such file")) ||
1342                                    (pointer = strstr(line, "token")))
1343                               {
1344                                  strncat(moduleName, colon, pointer - colon);
1345                                  strcat(moduleName, "error: ");
1346                                  colon = pointer;
1347                                  numErrors ++;
1348                               }
1349                            }
1350                            else if((pointer = strstr(line, "No such file")))
1351                            {
1352                               strncat(moduleName, colon, pointer - colon);
1353                               strcat(moduleName, "error: ");
1354                               colon = pointer;
1355                               numErrors ++;
1356                            }
1357                            else if(compilingEC == 1 || (objDir && objDir == moduleName))
1358                               continue;
1359                            else if(strstr(line, "warning:"))
1360                            {
1361                               numWarnings++;
1362                            }
1363                         }
1364                         if(this == ide.workspace.projects.firstIterator.data)
1365                            ide.outputView.buildBox.Logf("   %s%s\n", moduleName, colon);
1366                         else
1367                         {
1368                            char fullModuleName[MAX_LOCATION];
1369                            strcpy(fullModuleName, topNode.path);
1370                            PathCat(fullModuleName, moduleName);
1371                            MakePathRelative(fullModuleName, ide.workspace.projects.firstIterator.data.topNode.path, fullModuleName);
1372                            MakeSystemPath(fullModuleName);
1373                            ide.outputView.buildBox.Logf("   %s%s%s\n", inFileIncludedFrom ? stringInFileIncludedFrom : "", fullModuleName, colon);
1374                         }
1375                      }
1376                      else
1377                      {
1378                         ide.outputView.buildBox.Logf("%s\n", line);
1379                         linking = compiling = precompiling = false;
1380                      }
1381                   }
1382                   else
1383                      ide.outputView.buildBox.Logf("%s\n", line);
1384                }
1385                wait = false;
1386             }
1387             //printf("Done getting line\n");
1388             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1389          }
1390          //printf("Processing Input...\n");
1391          if(app.ProcessInput(true))
1392             wait = false;
1393          app.UpdateDisplay();
1394          if(wait)
1395          {
1396             //printf("Waiting...\n");
1397             app.Wait();
1398          }
1399          //if(!result) Sleep(1.0 / PEEK_RESOLUTION);
1400       }
1401       if(ide.ShouldStopBuild())
1402       {
1403          ide.outputView.buildBox.Logf($"\nBuild cancelled by user.\n", line);
1404          f.Terminate();
1405       }
1406       else if(loggedALine || !isARun)
1407       {
1408          if(f.GetExitCode() && !numErrors)
1409          {
1410             bool result = f.GetLine(line, sizeof(line)-1);
1411             ide.outputView.buildBox.Logf($"Fatal Error: child process terminated unexpectedly\n");
1412          }
1413          else
1414          {
1415             if(!onlyNode)
1416                ide.outputView.buildBox.Logf("\n%s (%s) - ", GetTargetFileName(config), configName);
1417             if(numErrors)
1418                ide.outputView.buildBox.Logf("%d %s, ", numErrors, (numErrors > 1) ? $"errors" : $"error");
1419             else
1420                ide.outputView.buildBox.Logf($"no error, ");
1421    
1422             if(numWarnings)
1423                ide.outputView.buildBox.Logf("%d %s\n", numWarnings, (numWarnings > 1) ? $"warnings" : $"warning");
1424             else
1425                ide.outputView.buildBox.Logf($"no warning\n");
1426          }
1427       }
1428       return numErrors == 0;
1429    }
1430
1431    void ProcessCleanPipeOutput(DualPipe f, CompilerConfig compiler, ProjectConfig config)
1432    {
1433       char line[65536];
1434       int lenMakeCommand = strlen(compiler.makeCommand);
1435       while(!f.Eof())
1436       {
1437          bool result = true;
1438          bool wait = true;
1439          double lastTime = GetTime();
1440          while(result)
1441          {
1442             if((result = f.Peek()) && (result = f.GetLine(line, sizeof(line)-1)))
1443             {
1444                if(strstr(line, compiler.makeCommand) == line && line[lenMakeCommand] == ':');
1445                else if(strstr(line, "del") == line);
1446                else if(strstr(line, "rm") == line);
1447                else if(strstr(line, "Could Not Find") == line);
1448                else
1449                {
1450                   ide.outputView.buildBox.Logf(line);
1451                   ide.outputView.buildBox.Logf("\n");
1452                }
1453                wait = false;
1454             }
1455             if(GetTime() - lastTime > 1.0 / PEEK_RESOLUTION) break;
1456          }
1457          if(app.ProcessInput(true))
1458             wait = false;
1459          app.UpdateDisplay();
1460          if(wait)
1461             app.Wait();
1462          //Sleep(1.0 / PEEK_RESOLUTION);
1463       }
1464    }
1465
1466    bool Build(bool isARun, ProjectNode onlyNode, CompilerConfig compiler, ProjectConfig config)
1467    {
1468       bool result = false;
1469       DualPipe f;
1470       char targetFileName[MAX_LOCATION] = "";
1471       char makeTarget[MAX_LOCATION] = "";
1472       char makeFile[MAX_LOCATION];
1473       char makeFilePath[MAX_LOCATION];
1474       char configName[MAX_LOCATION];
1475       DirExpression objDirExp = GetObjDir(compiler, config);
1476       PathBackup pathBackup { };
1477
1478       int numJobs = compiler.numJobs;
1479       char command[MAX_LOCATION];
1480       char * compilerName;
1481
1482       compilerName = CopyString(compiler.name);
1483       CamelCase(compilerName);
1484
1485       strcpy(configName, config ? config.name : "Common");
1486
1487       SetPath(false, compiler, config); //true
1488       CatTargetFileName(targetFileName, compiler, config);
1489
1490       strcpy(makeFilePath, topNode.path);
1491       CatMakeFileName(makeFile, compiler, config);
1492       PathCatSlash(makeFilePath, makeFile);
1493       
1494       // TODO: TEST ON UNIX IF \" around makeTarget is ok
1495       if(onlyNode)
1496       {
1497          if(compiler.type.isVC)
1498          {
1499             PrintLn("compiling a single file is not yet supported");
1500          }
1501          else
1502          {
1503             int len;
1504             char pushD[MAX_LOCATION];
1505             GetWorkingDir(pushD, sizeof(pushD));
1506             ChangeWorkingDir(topNode.path);
1507             // Create object dir if it does not exist already
1508             if(!FileExists(objDirExp.dir).isDirectory)
1509                Execute("%s E_IDE_CF_DIR=%s COMPILER=%s objdir -C \"%s\" -f \"%s\"", compiler.makeCommand, cfDir, compilerName, topNode.path, makeFilePath);
1510             ChangeWorkingDir(pushD);
1511
1512             PathCatSlash(makeTarget+1, objDirExp.dir);
1513             PathCatSlash(makeTarget+1, onlyNode.name);
1514             StripExtension(makeTarget+1);
1515             strcat(makeTarget+1, ".o");
1516             makeTarget[0] = '\"';
1517             len = strlen(makeTarget);
1518             makeTarget[len++] = '\"';
1519             makeTarget[len++] = '\0';
1520          }
1521       }
1522
1523       if(compiler.type.isVC)
1524       {
1525          bool result = false;
1526          char oldwd[MAX_LOCATION];
1527          GetWorkingDir(oldwd, sizeof(oldwd));
1528          ChangeWorkingDir(topNode.path);
1529
1530          sprintf(command, "%s /useenv /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1531          ide.outputView.buildBox.Logf("command: %s\n", command);
1532          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1533          {
1534             ProcessPipeOutputRaw(f);
1535             delete f;
1536             result = true;
1537          }
1538          ChangeWorkingDir(oldwd);
1539       }
1540       else
1541       {
1542          sprintf(command, "%s E_IDE_CF_DIR=%s COMPILER=%s -j%d %s%s%s -C \"%s\" -f \"%s\"", compiler.makeCommand, cfDir, compilerName, numJobs,
1543                compiler.ccacheEnabled ? "CCACHE=y " : "",
1544                compiler.distccEnabled ? "DISTCC=y " : "",
1545                makeTarget, topNode.path, makeFilePath);
1546          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1547          {
1548             result = ProcessBuildPipeOutput(f, objDirExp, isARun, onlyNode, compiler, config);
1549             delete f;
1550          }
1551          else
1552             ide.outputView.buildBox.Logf($"Error executing make (%s) command\n", compiler.makeCommand);
1553       }
1554
1555       delete pathBackup;
1556       delete objDirExp;
1557       delete compilerName;
1558       return result;
1559    }
1560
1561    void Clean(CompilerConfig compiler, ProjectConfig config, bool realclean)
1562    {
1563       char makeFile[MAX_LOCATION];
1564       char makeFilePath[MAX_LOCATION];
1565       char command[MAX_LOCATION];
1566       char * compilerName;
1567       DualPipe f;
1568       PathBackup pathBackup { };
1569
1570       compilerName = CopyString(compiler.name);
1571       CamelCase(compilerName);
1572
1573       SetPath(false, compiler, config);
1574
1575       strcpy(makeFilePath, topNode.path);
1576       CatMakeFileName(makeFile, compiler, config);
1577       PathCatSlash(makeFilePath, makeFile);
1578       
1579       if(compiler.type.isVC)
1580       {
1581          bool result = false;
1582          char oldwd[MAX_LOCATION];
1583          GetWorkingDir(oldwd, sizeof(oldwd));
1584          ChangeWorkingDir(topNode.path);
1585          
1586          sprintf(command, "%s /useenv /clean /nologo /logcommands %s.sln %s|Win32", compiler.makeCommand, name, config.name);
1587          ide.outputView.buildBox.Logf("command: %s\n", command);
1588          if((f = DualPipeOpen(PipeOpenMode { output = true, error = true, input = true }, command)))
1589          {
1590             ProcessPipeOutputRaw(f);
1591             delete f;
1592             result = true;
1593          }
1594          ChangeWorkingDir(oldwd);
1595          return result;
1596       }
1597       else
1598       {
1599          sprintf(command, "%s E_IDE_CF_DIR=%s COMPILER=%s %sclean -C \"%s\" -f \"%s\"", compiler.makeCommand, cfDir, compilerName, realclean ? "real" : "", topNode.path, makeFilePath);
1600          if((f = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
1601          {
1602             ide.outputView.buildBox.Tell($"Deleting target and object files...");
1603             ProcessCleanPipeOutput(f, compiler, config);
1604             delete f;
1605
1606             ide.outputView.buildBox.Logf($"Target and object files deleted\n");
1607          }
1608       }
1609
1610       delete pathBackup;
1611       delete compilerName;
1612    }
1613
1614    void Run(char * args, CompilerConfig compiler, ProjectConfig config)
1615    {   
1616       String target = new char[maxPathLen];
1617       char oldDirectory[MAX_LOCATION];
1618       DirExpression targetDirExp = GetTargetDir(compiler, config);
1619       PathBackup pathBackup { };
1620
1621       // Build(project, ideMain, true, null);
1622
1623    #if defined(__WIN32__)
1624       strcpy(target, topNode.path);
1625    #else
1626       strcpy(target, "");
1627    #endif
1628       PathCatSlash(target, targetDirExp.dir);
1629       CatTargetFileName(target, compiler, config);
1630       sprintf(target, "%s %s", target, args);
1631       GetWorkingDir(oldDirectory, MAX_LOCATION);
1632
1633       if(strlen(ide.workspace.debugDir))
1634       {
1635          char temp[MAX_LOCATION];
1636          strcpy(temp, topNode.path);
1637          PathCatSlash(temp, ide.workspace.debugDir);
1638          ChangeWorkingDir(temp);
1639       }
1640       else
1641          ChangeWorkingDir(topNode.path);
1642       // ChangeWorkingDir(topNode.path);
1643       SetPath(true, compiler, config);
1644       if(compiler.execPrefixCommand)
1645       {
1646          char * prefixedTarget = new char[strlen(compiler.execPrefixCommand) + strlen(target) + 2];
1647          prefixedTarget[0] = '\0';
1648          strcat(prefixedTarget, compiler.execPrefixCommand);
1649          strcat(prefixedTarget, " ");
1650          strcat(prefixedTarget, target);
1651          Execute(prefixedTarget);
1652          delete prefixedTarget;
1653       }
1654       else
1655          Execute(target);
1656
1657       ChangeWorkingDir(oldDirectory);
1658       delete pathBackup;
1659
1660       delete targetDirExp;
1661       delete target;
1662    }
1663
1664    void Compile(ProjectNode node, CompilerConfig compiler, ProjectConfig config)
1665    {
1666       Build(false, node, compiler, config);
1667    }
1668 #endif
1669
1670    void GetMakefileTargetFileName(TargetTypes targetType, char * fileName, ProjectConfig config)
1671    {
1672       fileName[0] = '\0';
1673       if(targetType == staticLibrary || targetType == sharedLibrary)
1674          strcat(fileName, "$(LP)");
1675       // !!! ReplaceSpaces must be done after all PathCat calls !!!
1676       // ReplaceSpaces(s, GetTargetFileName(config));
1677       strcat(fileName, GetTargetFileName(config));
1678       switch(targetType)
1679       {
1680          case executable:
1681             strcat(fileName, "$(E)");
1682             break;
1683          case sharedLibrary:
1684             strcat(fileName, "$(SO)");
1685             break;
1686          case staticLibrary:
1687             strcat(fileName, "$(A)");
1688             break;
1689       }
1690    }
1691
1692    bool GenerateDebugCf(CompilerConfig compiler)
1693    {
1694       bool result = false;
1695       char path[MAX_LOCATION];
1696
1697       GetWorkingDir(path, sizeof(path));
1698       PathCatSlash(path, cfDir);
1699       PathCatSlash(path, "debug.cf");
1700
1701       if(!FileExists(path))
1702       {
1703          File f = FileOpen(path, write);
1704          if(f)
1705          {
1706             f.Printf(".PHONY: debug_lists\n");
1707             f.Printf("\n");
1708
1709             f.Printf("ifdef WINDOWS\n");
1710             f.Printf(".PHONY: debug_openssl\n");
1711             f.Printf("debug_openssl:\n");
1712             f.Printf("  @$(call echo,OPENSSL_CONF = $(OPENSSL_CONF))\n");
1713             f.Printf("  @$(call echo,_OPENSSL_CONF = $(_OPENSSL_CONF))\n");
1714             f.Printf("  @$(call echo,OPENSSL_INCLUDE_DIR = $(OPENSSL_INCLUDE_DIR))\n");
1715             f.Printf("  @$(call echo,OPENSSL_LIB_DIR = $(OPENSSL_LIB_DIR))\n");
1716             f.Printf("  @$(call echo,OPENSSL_BIN_DIR = $(OPENSSL_BIN_DIR))\n");
1717             f.Printf("endif\n");
1718             f.Printf("\n");
1719
1720             f.Printf("debug_lists:\n");
1721             f.Printf("  @$(call echo,ECSOURCES = $(ECSOURCES))\n");
1722             f.Printf("  @$(call echo,SYMBOLS = $(SYMBOLS))\n");
1723             f.Printf("  @$(call echo,IMPORTS = $(IMPORTS))\n");
1724             f.Printf("  @$(call echo,COBJECTS = $(COBJECTS))\n");
1725
1726             delete f;
1727          }
1728       }
1729       return result;
1730    }
1731
1732    bool GenerateCrossPlatformCf()
1733    {
1734       bool result = false;
1735       char path[MAX_LOCATION];
1736
1737       GetWorkingDir(path, sizeof(path));
1738       PathCatSlash(path, cfDir);
1739       PathCatSlash(path, "crossplatform.cf");
1740
1741       if(!FileExists(path))
1742       {
1743          File f = FileOpen(path, write);
1744          if(f)
1745          {
1746             File include = FileOpen(":include.mk", read);
1747             if(include)
1748             {
1749                for(; !include.Eof(); )
1750                {
1751                   char buffer[4096];
1752                   int count = include.Read(buffer, 1, 4096);
1753                   f.Write(buffer, 1, count);
1754                }
1755                delete include;
1756                result = true;
1757             }
1758             delete f;
1759          }
1760       }
1761       return result;
1762    }
1763
1764    bool GenerateCompilerMk(CompilerConfig compiler)
1765    {
1766       bool result = false;
1767       char path[MAX_LOCATION];
1768       char * name;
1769       char * compilerName;
1770       Platform platform = GetRuntimePlatform();
1771
1772       compilerName = CopyString(compiler.name);
1773       CamelCase(compilerName);
1774       name = PrintString(platform, "-", compilerName, ".cf");
1775
1776       GetWorkingDir(path, sizeof(path));
1777       PathCatSlash(path, cfDir);
1778       PathCatSlash(path, name);
1779
1780       if(!FileExists(path))
1781       {
1782          File f = FileOpen(path, write);
1783          if(f)
1784          {
1785             bool crossCompiling = compiler.targetPlatform != platform;
1786
1787             if(strcmpi(compiler.cppCommand, "cpp") ||
1788                   strcmpi(compiler.ccCommand,  "gcc") ||
1789                   strcmpi(compiler.ecpCommand, "ecp") ||
1790                   strcmpi(compiler.eccCommand, "ecc") ||
1791                   strcmpi(compiler.ecsCommand, "ecs") || crossCompiling ||
1792                   strcmpi(compiler.earCommand, "ear"))
1793             {
1794                f.Printf("# TOOLCHAIN\n\n");
1795
1796                //f.Printf("SHELL := %s\n", "ar"/*compiler.arCommand*/); // is this really needed?
1797                if(strcmpi(compiler.cppCommand, "cpp"))
1798                   f.Printf("CPP := $(CCACHE_COMPILE) $(DISTCC_COMPILE) %s\n", compiler.cppCommand);
1799                if(strcmpi(compiler.ccCommand,  "gcc"))
1800                   f.Printf("CC := $(CCACHE_COMPILE) $(DISTCC_COMPILE) %s\n", compiler.ccCommand);
1801                if(strcmpi(compiler.ecpCommand, "ecp"))
1802                   f.Printf("ECP := %s\n", compiler.ecpCommand);
1803                if(strcmpi(compiler.eccCommand, "ecc"))
1804                   f.Printf("ECC := %s\n", compiler.eccCommand);
1805                if(strcmpi(compiler.ecsCommand, "ecs") || crossCompiling)
1806                {
1807                   f.Printf("ECS := %s%s%s\n", compiler.ecsCommand,
1808                         crossCompiling ? " -t " : "", crossCompiling ? (char*)compiler.targetPlatform : "");
1809                }
1810                if(strcmpi(compiler.earCommand, "ear"))
1811                   f.Printf("EAR := %s\n", compiler.earCommand);
1812                f.Printf("\n");
1813             }
1814
1815             f.Printf("UPXFLAGS = -9\n\n"); // TOFEAT: Compression Level Option? Other UPX Options?
1816
1817             f.Printf("# HARD CODED PLATFORM-SPECIFIC OPTIONS\n");
1818             f.Printf("ifdef %s\n", PlatformToMakefileVariable(tux));
1819             f.Printf("OFLAGS += -Wl,--no-undefined\n");
1820             f.Printf("endif\n\n");
1821
1822             // JF's
1823             f.Printf("ifdef %s\n", PlatformToMakefileVariable(apple));
1824             f.Printf("OFLAGS += -framework cocoa -framework OpenGL\n");
1825             f.Printf("endif\n\n");
1826
1827             delete f;
1828          }
1829       }
1830       delete name;
1831       delete compilerName;
1832       return result;
1833    }
1834
1835    bool GenerateMakefile(char * altMakefilePath, bool noResources, char * includemkPath,
1836       CompilerConfig compiler, ProjectConfig config)
1837    {
1838       bool result = false;
1839       char filePath[MAX_LOCATION];
1840       char makeFile[MAX_LOCATION];
1841       // PathBackup pathBackup { };
1842       // char oldDirectory[MAX_LOCATION];
1843       File f = null;
1844
1845       if(!altMakefilePath)
1846       {
1847          strcpy(filePath, topNode.path);
1848          CatMakeFileName(makeFile, compiler, config);
1849          PathCatSlash(filePath, makeFile);
1850       }
1851
1852 #if defined(__WIN32__) && !defined(MAKEFILE_GENERATOR)
1853       if(compiler.type.isVC)
1854       {
1855          GenerateVSSolutionFile(this, compiler);
1856          GenerateVCProjectFile(this, compiler);
1857       }
1858       else
1859 #endif
1860       f = FileOpen(altMakefilePath ? altMakefilePath : filePath, write);
1861
1862       /*SetPath(false, compiler, config);
1863       GetWorkingDir(oldDirectory, MAX_LOCATION);
1864       ChangeWorkingDir(topNode.path);*/
1865
1866       if(f)
1867       {
1868          bool test;
1869          int ifCount;
1870          Platform platform;
1871          Platform runtimePlatform = GetRuntimePlatform();
1872          char targetDir[MAX_LOCATION];
1873          char objDirExpNoSpaces[MAX_LOCATION];
1874          char objDirNoSpaces[MAX_LOCATION];
1875          char resDirNoSpaces[MAX_LOCATION];
1876          char targetDirExpNoSpaces[MAX_LOCATION];
1877          char fixedModuleName[MAX_FILENAME];
1878          char fixedConfigName[MAX_FILENAME];
1879          char fixedCompilerName[MAX_FILENAME];
1880          int c, len;
1881          int numCObjects = 0;
1882          bool sameObjTargetDirs;
1883          DirExpression objDirExp = GetObjDir(compiler, config);
1884          TargetTypes targetType = GetTargetType(config);
1885
1886          bool crossCompiling = compiler.targetPlatform != runtimePlatform;
1887          bool gccCompiler = compiler.ccCommand && strstr(compiler.ccCommand, "gcc") != null;
1888          bool tccCompiler = compiler.ccCommand && strstr(compiler.ccCommand, "tcc") != null;
1889          bool defaultPreprocessor = compiler.cppCommand && (strstr(compiler.cppCommand, "gcc") != null || compiler.cppCommand && strstr(compiler.cppCommand, "cpp") != null);
1890
1891          int objectsParts, eCsourcesParts;
1892          Array<String> listItems { };
1893          Map<String, int> varStringLenDiffs { };
1894          Map<String, NameCollisionInfo> namesInfo { };
1895
1896          ReplaceSpaces(objDirNoSpaces, objDirExp.dir);
1897          strcpy(targetDir, GetTargetDirExpression(compiler, config));
1898          ReplaceSpaces(targetDirExpNoSpaces, targetDir);
1899
1900          strcpy(objDirExpNoSpaces, GetObjDirExpression(compiler, config));
1901          ChangeCh(objDirExpNoSpaces, '\\', '/'); // TODO: this is a hack, paths should never include win32 path seperators - fix this in ProjectSettings and ProjectLoad instead
1902          ReplaceSpaces(objDirExpNoSpaces, objDirExpNoSpaces);
1903          ReplaceSpaces(resDirNoSpaces, resNode.path ? resNode.path : "");
1904          //ReplaceSpaces(fixedPrjName, name);
1905          ReplaceSpaces(fixedModuleName, moduleName);
1906          ReplaceSpaces(fixedConfigName, GetConfigName(config));
1907          ReplaceSpaces(fixedCompilerName, compiler.name);
1908          //CamelCase(fixedModuleName); // case is important for static linking
1909          CamelCase(fixedConfigName);
1910          CamelCase(fixedCompilerName);
1911
1912          sameObjTargetDirs = !fstrcmp(objDirExpNoSpaces, targetDirExpNoSpaces);
1913
1914          f.Printf(".PHONY: all objdir%s clean realclean\n\n", sameObjTargetDirs ? "" : " targetdir");
1915
1916          f.Printf("# CONTENT\n\n");
1917
1918          f.Printf("MODULE := %s\n", fixedModuleName);
1919          //f.Printf("VERSION = %s\n", version);
1920          f.Printf("CONFIG := %s\n", fixedConfigName);
1921          f.Printf("ifndef COMPILER\n");
1922          f.Printf("COMPILER := %s\n", fixedCompilerName);
1923          f.Printf("endif\n");
1924          if(crossCompiling)
1925             f.Printf("PLATFORM = %s\n", (char *)compiler.targetPlatform);
1926          test = GetTargetTypeIsSetByPlatform(config);
1927          if(test)
1928          {
1929             ifCount = 0;
1930             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
1931             {
1932                TargetTypes targetType;
1933                PlatformOptions projectPOs, configPOs;
1934                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
1935                targetType = platformTargetType;
1936                if(targetType)
1937                {
1938                   if(ifCount)
1939                      f.Printf("else\n");
1940                   ifCount++;
1941                   f.Printf("ifdef %s\n", PlatformToMakefileVariable(platform));
1942
1943                   f.Printf("TARGET_TYPE = ");
1944                   f.Printf(TargetTypeToMakefileVariable(targetType));
1945                   f.Printf("\n");
1946                }
1947             }
1948             f.Printf("else\n"); // ifCount should always be > 0
1949          }
1950          f.Printf("TARGET_TYPE = ");
1951          f.Printf(TargetTypeToMakefileVariable(targetType));
1952          f.Printf("\n");
1953          if(test)
1954          {
1955             if(ifCount)
1956             {
1957                for(c = 0; c < ifCount; c++)
1958                   f.Printf("endif\n");
1959             }
1960          }
1961          f.Printf("\n");
1962
1963          f.Printf("# FLAGS\n\n");
1964
1965          f.Printf("CFLAGS =\n");
1966          f.Printf("CECFLAGS =\n");
1967          f.Printf("ECFLAGS =\n");
1968          f.Printf("OFLAGS =\n");
1969          f.Printf("LIBS =\n");
1970          f.Printf("\n");
1971
1972          f.Printf("# INCLUDES\n\n");
1973
1974          f.Printf("include %s\n", includemkPath ? includemkPath : "$(E_IDE_CF_DIR)crossplatform.cf");
1975          f.Printf("include $(E_IDE_CF_DIR)%s-%s.cf\n", (char*)runtimePlatform, fixedCompilerName);
1976          f.Printf("\n");
1977
1978          f.Printf("# VARIABLES\n\n");
1979
1980          f.Printf("OBJ = %s%s\n\n", objDirExpNoSpaces, objDirExpNoSpaces[0] ? "/" : "");
1981
1982          f.Printf("RES = %s%s\n\n", resDirNoSpaces, resDirNoSpaces[0] ? "/" : "");
1983
1984          // test = GetTargetTypeIsSetByPlatform(config);
1985          {
1986             char target[MAX_LOCATION];
1987             char targetNoSpaces[MAX_LOCATION];
1988          if(test)
1989          {
1990             TargetTypes type;
1991             ifCount = 0;
1992             for(type = (TargetTypes)1; type < TargetTypes::enumSize; type++)
1993             {
1994                if(type != targetType)
1995                {
1996                   if(ifCount)
1997                      f.Printf("else\n");
1998                   ifCount++;
1999                   f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(type));
2000
2001                   GetMakefileTargetFileName(type, target, config);
2002                   strcpy(targetNoSpaces, targetDir);
2003                   PathCatSlash(targetNoSpaces, target);
2004                   ReplaceSpaces(targetNoSpaces, targetNoSpaces);
2005                   f.Printf("TARGET = %s\n", targetNoSpaces);
2006                }
2007             }
2008             f.Printf("else\n"); // ifCount should always be > 0
2009          }
2010          GetMakefileTargetFileName(targetType, target, config);
2011          strcpy(targetNoSpaces, targetDir);
2012          PathCatSlash(targetNoSpaces, target);
2013          ReplaceSpaces(targetNoSpaces, targetNoSpaces);
2014          f.Printf("TARGET = %s\n", targetNoSpaces);
2015          if(test)
2016          {
2017             if(ifCount)
2018             {
2019                for(c = 0; c < ifCount; c++)
2020                   f.Printf("endif\n");
2021             }
2022          }
2023          }
2024          f.Printf("\n");
2025
2026          varStringLenDiffs["$(OBJ)"] = strlen(objDirNoSpaces) - 6;
2027
2028          topNode.GenMakefileGetNameCollisionInfo(namesInfo, config);
2029
2030          numCObjects = topNode.GenMakefilePrintNode(f, this, objects, namesInfo, listItems, config);
2031          if(numCObjects)
2032             listItems.Add(CopyString("$(OBJ)$(MODULE).main$(O)"));
2033          objectsParts = OutputFileList(f, "OBJECTS", listItems, varStringLenDiffs, null);
2034
2035          {
2036             int c;
2037             char * map[3][2] = { { "COBJECTS", "C" }, { "SYMBOLS", "S" }, { "IMPORTS", "I" } };
2038
2039             topNode.GenMakefilePrintNode(f, this, eCsources, namesInfo, listItems, config);
2040             eCsourcesParts = OutputFileList(f, "_ECSOURCES", listItems, varStringLenDiffs, null);
2041
2042             f.Printf("ECSOURCES = $(call shwspace,$(_ECSOURCES))\n");
2043             if(eCsourcesParts > 1)
2044             {
2045                for(c = 1; c <= eCsourcesParts; c++)
2046                   f.Printf("ECSOURCES%d = $(call shwspace,$(_ECSOURCES%d))\n", c, c);
2047             }
2048             f.Printf("\n");
2049
2050             for(c = 0; c < 3; c++)
2051             {
2052                if(eCsourcesParts > 1)
2053                {
2054                   int n;
2055                   f.Printf("%s =", map[c][0]);
2056                   for(n = 1; n <= eCsourcesParts; n++)
2057                      f.Printf(" $(%s%d)", map[c][0], n);
2058                   f.Printf("\n");
2059                   for(n = 1; n <= eCsourcesParts; n++)
2060                      f.Printf("%s%d = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES%d)))))\n", map[c][0], n, map[c][1], n);
2061                }
2062                else if(eCsourcesParts == 1)
2063                   f.Printf("%s = $(call shwspace,$(addprefix $(OBJ),$(patsubst %%.ec,%%$(%s),$(notdir $(_ECSOURCES)))))\n", map[c][0], map[c][1]);
2064                f.Printf("\n");
2065             }
2066          }
2067
2068          topNode.GenMakefilePrintNode(f, this, sources, null, listItems, config);
2069          OutputFileList(f, "SOURCES", listItems, varStringLenDiffs, "$(ECSOURCES)");
2070
2071          if(!noResources)
2072             resNode.GenMakefilePrintNode(f, this, resources, null, listItems, config);
2073          OutputFileList(f, "RESOURCES", listItems, varStringLenDiffs, null);
2074
2075          f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(executable));
2076          f.Printf("CONSOLE = %s\n", GetConsole(config) ? "-mconsole" : "-mwindows");
2077          f.Printf("endif\n\n");
2078
2079          if((compiler.includeDirs && compiler.includeDirs.count) ||
2080                (compiler.libraryDirs && compiler.libraryDirs.count))
2081          {
2082             if(compiler.includeDirs && compiler.includeDirs.count)
2083             {
2084                f.Printf("CFLAGS +=");
2085                OutputListOption(f, gccCompiler ? "isystem " : "I", compiler.includeDirs, lineEach, true);
2086                f.Printf("\n");
2087             }
2088             if(compiler.libraryDirs && compiler.libraryDirs.count)
2089             {
2090                f.Printf("OFLAGS +=");
2091                OutputListOption(f, "L", compiler.libraryDirs, lineEach, true);
2092                f.Printf("\n");
2093             }
2094             f.Printf("\n");
2095          }
2096
2097          if((config && config.options && config.options.libraries) ||
2098                (options && options.libraries))
2099          {
2100             f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2101             f.Printf("LIBS +=");
2102             if(config && config.options && config.options.libraries)
2103                OutputLibraries(f, config.options.libraries);
2104             else if(options && options.libraries)
2105                OutputLibraries(f, options.libraries);
2106             f.Printf("\n");
2107             f.Printf("endif\n");
2108             f.Printf("\n");
2109          }
2110          f.Printf("LIBS += $(SHAREDLIB) $(EXECUTABLE) $(LINKOPT)\n\n");
2111
2112          if(platforms || (config && config.platforms))
2113          {
2114             ifCount = 0;
2115             //for(platform = firstPlatform; platform <= lastPlatform; platform++)
2116             //for(platform = win32; platform <= apple; platform++)
2117
2118             f.Printf("# PLATFORM-SPECIFIC OPTIONS\n\n");
2119             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2120             {
2121                PlatformOptions projectPlatformOptions, configPlatformOptions;
2122                MatchProjectAndConfigPlatformOptions(config, platform, &projectPlatformOptions, &configPlatformOptions);
2123
2124                if(projectPlatformOptions || configPlatformOptions)
2125                {
2126                   if(ifCount)
2127                      f.Printf("else\n");
2128                   ifCount++;
2129                   f.Printf("ifdef ");
2130                   f.Printf(PlatformToMakefileVariable(platform));
2131                   f.Printf("\n\n");
2132
2133                   if((projectPlatformOptions && projectPlatformOptions.options.preprocessorDefinitions && projectPlatformOptions.options.preprocessorDefinitions.count) ||
2134                      (configPlatformOptions && configPlatformOptions.options.preprocessorDefinitions && configPlatformOptions.options.preprocessorDefinitions.count) ||
2135                      (projectPlatformOptions && projectPlatformOptions.options.includeDirs && projectPlatformOptions.options.includeDirs.count) ||
2136                      (configPlatformOptions && configPlatformOptions.options.includeDirs && configPlatformOptions.options.includeDirs.count))
2137                   {
2138                      f.Printf("CFLAGS +=");
2139                      if(projectPlatformOptions && projectPlatformOptions.options.linkerOptions && projectPlatformOptions.options.linkerOptions.count)
2140                      {
2141                         f.Printf(" \\\n\t -Wl");
2142                         for(s : projectPlatformOptions.options.linkerOptions)
2143                            f.Printf(",%s", s);
2144                      }
2145                      if(configPlatformOptions && configPlatformOptions.options.linkerOptions && configPlatformOptions.options.linkerOptions.count)
2146                      {
2147                         f.Printf(" \\\n\t -Wl");
2148                         for(s : configPlatformOptions.options.linkerOptions)
2149                            f.Printf(",%s", s);
2150                      }
2151                      if(projectPlatformOptions && projectPlatformOptions.options.preprocessorDefinitions)
2152                         OutputListOption(f, "D", projectPlatformOptions.options.preprocessorDefinitions, newLine, false);
2153                      if(configPlatformOptions && configPlatformOptions.options.preprocessorDefinitions)
2154                         OutputListOption(f, "D", configPlatformOptions.options.preprocessorDefinitions, newLine, false );
2155                      if(configPlatformOptions && configPlatformOptions.options.includeDirs)
2156                         OutputListOption(f, "I", configPlatformOptions.options.includeDirs, lineEach, true);
2157                      if(projectPlatformOptions && projectPlatformOptions.options.includeDirs)
2158                         OutputListOption(f, "I", projectPlatformOptions.options.includeDirs, lineEach, true);
2159                      f.Printf("\n\n");
2160                   }
2161
2162                   if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2163                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count) ||
2164                         (projectPlatformOptions && projectPlatformOptions.options.libraries && projectPlatformOptions.options.libraries.count) ||
2165                         (configPlatformOptions && configPlatformOptions.options.libraries && configPlatformOptions.options.libraries.count))
2166                   {
2167                      f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2168                      if((projectPlatformOptions && projectPlatformOptions.options.libraryDirs && projectPlatformOptions.options.libraryDirs.count) ||
2169                         (configPlatformOptions && configPlatformOptions.options.libraryDirs && configPlatformOptions.options.libraryDirs.count))
2170                      {
2171                         f.Printf("OFLAGS +=");
2172                         if(configPlatformOptions && configPlatformOptions.options.libraryDirs)
2173                            OutputListOption(f, "L", configPlatformOptions.options.libraryDirs, lineEach, true);
2174                         if(projectPlatformOptions && projectPlatformOptions.options.libraryDirs)
2175                            OutputListOption(f, "L", projectPlatformOptions.options.libraryDirs, lineEach, true);
2176                         f.Printf("\n");
2177                      }
2178
2179                      if(projectPlatformOptions && projectPlatformOptions.options.libraries &&
2180                            projectPlatformOptions.options.libraries.count)
2181                      {
2182                         f.Printf("LIBS +=");
2183                         OutputLibraries(f, projectPlatformOptions.options.libraries);
2184                         f.Printf("\n");
2185                      }
2186                      if((configPlatformOptions && configPlatformOptions.options.libraries &&
2187                            configPlatformOptions.options.libraries.count))
2188                      {
2189                         f.Printf("LIBS +=");
2190                         OutputLibraries(f, configPlatformOptions.options.libraries);
2191                         f.Printf("\n");
2192                      }
2193                      f.Printf("endif\n\n");
2194                   }
2195                }
2196             }
2197             if(ifCount)
2198             {
2199                for(c = 0; c < ifCount; c++)
2200                   f.Printf("endif\n");
2201             }
2202             f.Printf("\n");
2203          }
2204
2205          f.Printf("CFLAGS +=");
2206          if(gccCompiler)
2207          {
2208             f.Printf(" -fmessage-length=0");
2209             switch(GetOptimization(config))
2210             {
2211                case speed:
2212                   f.Printf(" -O2");
2213                   f.Printf(" -ffast-math");
2214                   break;
2215                case size:
2216                   f.Printf(" -Os");
2217                   break;
2218             }
2219             //if(compiler.targetPlatform.is32Bits)
2220                f.Printf(" -m32");
2221             //else if(compiler.targetPlatform.is64Bits)
2222             //   f.Printf(" -m64");
2223             f.Printf(" $(FPIC)");
2224             //f.Printf(" -fpack-struct");
2225          }
2226          switch(GetWarnings(config))
2227          {
2228             case all: f.Printf(" -Wall"); break;
2229             case none: f.Printf(" -w"); break;
2230          }
2231          if(GetDebug(config))
2232             f.Printf(" -g");
2233          if(GetProfile(config))
2234             f.Printf(" -pg");
2235          if(options && options.linkerOptions && options.linkerOptions.count)
2236          {
2237             f.Printf(" \\\n\t -Wl");
2238             for(s : options.linkerOptions)
2239                f.Printf(",%s", s);
2240          }
2241
2242          if(options && options.preprocessorDefinitions)
2243             OutputListOption(f, "D", options.preprocessorDefinitions, newLine, false);
2244          if(config && config.options && config.options.preprocessorDefinitions)
2245             OutputListOption(f, "D", config.options.preprocessorDefinitions, newLine, false);
2246          if(config && config.options && config.options.includeDirs)
2247             OutputListOption(f, "I", config.options.includeDirs, lineEach, true);
2248          if(options && options.includeDirs)
2249             OutputListOption(f, "I", options.includeDirs, lineEach, true);
2250          f.Printf("\n\n");
2251
2252          f.Printf("CECFLAGS +=%s%s%s%s", defaultPreprocessor ? "" : " -cpp ", defaultPreprocessor ? "" : compiler.cppCommand,
2253                crossCompiling ? " -t " : "", crossCompiling ? (char*)compiler.targetPlatform : "");
2254          f.Printf("\n\n");
2255
2256          f.Printf("ECFLAGS +=");
2257          if(GetMemoryGuard(config))
2258             f.Printf(" -memguard");
2259          if(GetStrictNameSpaces(config))
2260             f.Printf(" -strictns");
2261          if(GetNoLineNumbers(config))
2262             f.Printf(" -nolinenumbers");
2263          {
2264             char * s;
2265             if((s = GetDefaultNameSpace(config)) && s[0])
2266                f.Printf(" -defaultns %s", s);
2267          }
2268          f.Printf("\n\n");
2269
2270          f.Printf("OFLAGS +=\n");
2271          f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2272          f.Printf("OFLAGS += -m32");
2273          if(GetProfile(config))
2274             f.Printf(" -pg");
2275          if(config && config.options && config.options.libraryDirs)
2276             OutputListOption(f, "L", config.options.libraryDirs, lineEach, true);
2277          if(options && options.libraryDirs)
2278             OutputListOption(f, "L", options.libraryDirs, lineEach, true);
2279          f.Printf("\n");
2280          f.Printf("endif\n\n");
2281
2282          f.Printf("# TARGETS\n\n");
2283
2284          f.Printf("all: objdir%s $(TARGET)\n\n", sameObjTargetDirs ? "" : " targetdir");
2285
2286          f.Printf("objdir:\n");
2287             f.Printf("\t$(if $(wildcard $(OBJ)),,$(call mkdirq,$(OBJ)))\n");
2288          //f.Printf("# PRE-BUILD COMMANDS\n");
2289          if(options && options.prebuildCommands)
2290          {
2291             for(s : options.prebuildCommands)
2292                if(s && s[0]) f.Printf("\t%s\n", s);
2293          }
2294          if(config && config.options && config.options.prebuildCommands)
2295          {
2296             for(s : config.options.prebuildCommands)
2297                if(s && s[0]) f.Printf("\t%s\n", s);
2298          }
2299          if(platforms || (config && config.platforms))
2300          {
2301             ifCount = 0;
2302             //f.Printf("# PLATFORM-SPECIFIC PRE-BUILD COMMANDS\n");
2303             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2304             {
2305                PlatformOptions projectPOs, configPOs;
2306                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2307
2308                if((projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count) ||
2309                      (configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count))
2310                {
2311                   if(ifCount)
2312                      f.Printf("else\n");
2313                   ifCount++;
2314                   f.Printf("ifdef ");
2315                   f.Printf(PlatformToMakefileVariable(platform));
2316                   f.Printf("\n");
2317
2318                   if(projectPOs && projectPOs.options.prebuildCommands && projectPOs.options.prebuildCommands.count)
2319                   {
2320                      for(s : projectPOs.options.prebuildCommands)
2321                         if(s && s[0]) f.Printf("\t%s\n", s);
2322                   }
2323                   if(configPOs && configPOs.options.prebuildCommands && configPOs.options.prebuildCommands.count)
2324                   {
2325                      for(s : configPOs.options.prebuildCommands)
2326                         if(s && s[0]) f.Printf("\t%s\n", s);
2327                   }
2328                }
2329             }
2330             if(ifCount)
2331             {
2332                int c;
2333                for(c = 0; c < ifCount; c++)
2334                   f.Printf("endif\n");
2335             }
2336          }
2337          f.Printf("\n");
2338
2339          if(!sameObjTargetDirs)
2340          {
2341             f.Printf("targetdir:\n");
2342                f.Printf("\t$(if $(wildcard %s),,$(call mkdirq,%s))\n\n", targetDirExpNoSpaces, targetDirExpNoSpaces);
2343          }
2344
2345          if(numCObjects)
2346          {
2347             // Main Module (Linking) for ECERE C modules
2348             f.Printf("$(OBJ)$(MODULE).main.ec: $(SYMBOLS) $(COBJECTS)\n");
2349             // use of objDirExpNoSpaces used instead of $(OBJ) to prevent problematic joining of arguments in ecs
2350             f.Printf("\t$(ECS)%s $(ECSLIBOPT) $(SYMBOLS) $(IMPORTS) -symbols %s -o $(OBJ)$(MODULE).main.ec\n\n", 
2351                GetConsole(config) ? " -console" : "", objDirExpNoSpaces);
2352             // Main Module (Linking) for ECERE C modules
2353             f.Printf("$(OBJ)$(MODULE).main.c: $(OBJ)$(MODULE).main.ec\n");
2354             f.Printf("\t$(ECP) $(CECFLAGS) $(ECFLAGS) $(CFLAGS)"
2355                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.sym -symbols $(OBJ)\n");
2356             f.Printf("\t$(ECC) $(CECFLAGS) $(ECFLAGS) $(CFLAGS) $(FVISIBILITY)"
2357                   " -c $(OBJ)$(MODULE).main.ec -o $(OBJ)$(MODULE).main.c -symbols $(OBJ)\n\n");
2358          }
2359
2360          // *** Target ***
2361
2362          // This would not rebuild the target on updated objects
2363          // f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) | objdir $(SYMBOLS) $(OBJECTS)%s\n", sameObjTargetDirs ? "" : " targetdir");
2364
2365          // This should fix it for good!
2366          f.Printf("$(SYMBOLS): | objdir\n");
2367          f.Printf("$(OBJECTS): | objdir\n");
2368
2369          // This alone was breaking the tarball, object directory does not get created first (order-only rules happen last it seems!)
2370          f.Printf("$(TARGET): $(SOURCES) $(RESOURCES) $(SYMBOLS) $(OBJECTS) | objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2371
2372          f.Printf("ifneq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(staticLibrary));
2373          f.Printf("\t$(CC) $(OFLAGS) $(OBJECTS) $(LIBS) -o $(TARGET) $(INSTALLNAME)\n");
2374          if(!GetDebug(config))
2375          {
2376             f.Printf("ifndef NOSTRIP\n");
2377             f.Printf("\t$(STRIP) $(STRIPOPT) $(TARGET)\n");
2378             f.Printf("endif\n");
2379
2380             if(GetCompress(config))
2381             {
2382                f.Printf("ifndef WINDOWS\n");
2383                f.Printf("ifeq \"$(TARGET_TYPE)\" \"%s\"\n", TargetTypeToMakefileVariable(executable));
2384                   f.Printf("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2385                f.Printf("endif\n");
2386                f.Printf("else\n");
2387                   f.Printf("\t$(UPX) $(UPXFLAGS) $(TARGET)\n");
2388                f.Printf("endif\n");
2389             }
2390          }
2391          if(resNode.files && resNode.files.count && !noResources)
2392             resNode.GenMakefileAddResources(f, resNode.path, config);
2393          f.Printf("else\n");
2394          f.Printf("\t$(AR) rcs $(TARGET) $(OBJECTS) $(LIBS)\n");
2395          f.Printf("endif\n");
2396
2397          //f.Printf("# POST-BUILD COMMANDS\n");
2398          if(options && options.postbuildCommands)
2399          {
2400             for(s : options.postbuildCommands)
2401                if(s && s[0]) f.Printf("\t%s\n", s);
2402          }
2403          if(config && config.options && config.options.postbuildCommands)
2404          {
2405             for(s : config.options.postbuildCommands)
2406                if(s && s[0]) f.Printf("\t%s\n", s);
2407          }
2408          if(platforms || (config && config.platforms))
2409          {
2410             ifCount = 0;
2411             //f.Printf("# PLATFORM-SPECIFIC POST-BUILD COMMANDS\n");
2412             for(platform = (Platform)1; platform < Platform::enumSize; platform++)
2413             {
2414                PlatformOptions projectPOs, configPOs;
2415                MatchProjectAndConfigPlatformOptions(config, platform, &projectPOs, &configPOs);
2416
2417                if((projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count) ||
2418                      (configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count))
2419                {
2420                   if(ifCount)
2421                      f.Printf("else\n");
2422                   ifCount++;
2423                   f.Printf("ifdef ");
2424                   f.Printf(PlatformToMakefileVariable(platform));
2425                   f.Printf("\n");
2426
2427                   if(projectPOs && projectPOs.options.postbuildCommands && projectPOs.options.postbuildCommands.count)
2428                   {
2429                      for(s : projectPOs.options.postbuildCommands)
2430                         if(s && s[0]) f.Printf("\t%s\n", s);
2431                   }
2432                   if(configPOs && configPOs.options.postbuildCommands && configPOs.options.postbuildCommands.count)
2433                   {
2434                      for(s : configPOs.options.postbuildCommands)
2435                         if(s && s[0]) f.Printf("\t%s\n", s);
2436                   }
2437                }
2438             }
2439             if(ifCount)
2440             {
2441                int c;
2442                for(c = 0; c < ifCount; c++)
2443                   f.Printf("endif\n");
2444             }
2445          }
2446          f.Printf("\n");
2447
2448          f.Printf("# SYMBOL RULES\n\n");
2449          {
2450             Map<Platform, bool> excludedPlatforms { };
2451             topNode.GenMakefilePrintSymbolRules(f, this, compiler, config, excludedPlatforms);
2452             delete excludedPlatforms;
2453          }
2454
2455          f.Printf("# C OBJECT RULES\n\n");
2456          {
2457             Map<Platform, bool> excludedPlatforms { };
2458             topNode.GenMakefilePrintCObjectRules(f, this, compiler, config, excludedPlatforms);
2459             delete excludedPlatforms;
2460          }
2461
2462          f.Printf("# OBJECT RULES\n\n");
2463          // todo call this still but only generate rules whith specific options
2464          // see we-have-file-specific-options in ProjectNode.ec
2465          {
2466             Map<Platform, bool> excludedPlatforms { };
2467             topNode.GenMakefilePrintObjectRules(f, this, namesInfo, compiler, config, excludedPlatforms);
2468             delete excludedPlatforms;
2469          }
2470
2471          if(numCObjects)
2472             GenMakefilePrintMainObjectRule(f, compiler, config);
2473
2474          f.Printf("clean: objdir%s\n", sameObjTargetDirs ? "" : " targetdir");
2475          f.Printf("\t$(call rmq,%s$(TARGET))\n", numCObjects ? "$(OBJ)$(MODULE).main.c $(OBJ)$(MODULE).main.ec $(OBJ)$(MODULE).main$(I) $(OBJ)$(MODULE).main$(S) " : "");
2476          OutputCleanActions(f, "OBJECTS", objectsParts);
2477          OutputCleanActions(f, "COBJECTS", eCsourcesParts);
2478          if(numCObjects)
2479          {
2480             OutputCleanActions(f, "IMPORTS", eCsourcesParts);
2481             OutputCleanActions(f, "SYMBOLS", eCsourcesParts);
2482          }
2483          f.Printf("\n");
2484
2485          f.Printf("realclean: clean\n");
2486          f.Printf("\t$(call rmrq,$(OBJ))\n");
2487          if(!sameObjTargetDirs)
2488             f.Printf("\t$(call rmdirq,%s)\n", targetDirExpNoSpaces);
2489          f.Printf("\n");
2490
2491          f.Printf("include $(E_IDE_CF_DIR)debug.cf\n");
2492
2493          delete f;
2494          delete objDirExp;
2495          listItems.Free();
2496          delete listItems;
2497          varStringLenDiffs.Free();
2498          delete varStringLenDiffs;
2499          namesInfo.Free();
2500          delete namesInfo;
2501
2502          result = true;
2503       }
2504
2505       // ChangeWorkingDir(oldDirectory);
2506       // delete pathBackup;
2507
2508       if(config)
2509          config.makingModified = false;
2510       return result;
2511    }
2512
2513    void GenMakefilePrintMainObjectRule(File f, CompilerConfig compiler, ProjectConfig config)
2514    {
2515       char extension[MAX_EXTENSION] = "c";
2516       char modulePath[MAX_LOCATION];
2517       char fixedModuleName[MAX_FILENAME];
2518       DualPipe dep;
2519       char command[2048];
2520       char objDirNoSpaces[MAX_LOCATION];
2521       DirExpression objDirExp = GetObjDir(compiler, config);
2522
2523       ReplaceSpaces(objDirNoSpaces, objDirExp.dir);
2524       ReplaceSpaces(fixedModuleName, moduleName);
2525       
2526       //sprintf(fixedModuleName, "%s.main", fixedPrjName);
2527       //strcat(fixedModuleName, ".main");
2528
2529 #if 0       // TODO: Fix nospaces stuff
2530       // *** Dependency command ***
2531       sprintf(command, "gcc -MT $(OBJ)%s$(O) -MM $(OBJ)%s.c", fixedModuleName, fixedModuleName);
2532
2533       // System Includes (from global settings)
2534       for(item : compiler.dirs[Includes])
2535       {
2536          strcat(command, " -isystem ");
2537          if(strchr(item.name, ' '))
2538          {
2539             strcat(command, "\"");
2540             strcat(command, item);
2541             strcat(command, "\"");
2542          }
2543          else
2544             strcat(command, item);
2545       }
2546
2547       for(item = includeDirs.first; item; item = item.next)
2548       {
2549          strcat(command, " -I");
2550          if(strchr(item.name, ' '))
2551          {
2552             strcat(command, "\"");
2553             strcat(command, item.name);
2554             strcat(command, "\"");
2555          }
2556          else
2557             strcat(command, item.name);
2558       }
2559       for(item = preprocessorDefs.first; item; item = item.next)
2560       {
2561          strcat(command, " -D");
2562          strcat(command, item.name);
2563       }
2564
2565       // Execute it
2566       if((dep = DualPipeOpen(PipeOpenMode { output = 1, error = 1, input = 2 }, command)))
2567       {
2568          char line[1024];
2569          bool result = true;
2570          bool firstLine = true;
2571
2572          // To do some time: auto save external dependencies?
2573          while(!dep.Eof())
2574          {
2575             if(dep.GetLine(line, sizeof(line)-1))
2576             {
2577                if(firstLine)
2578                {
2579                   char * colon = strstr(line, ":");
2580                   if(strstr(line, "No such file") || strstr(line, ",") || (colon && strstr(colon+1, ":")))
2581                   {
2582                      result = false;
2583                      break;
2584                   }
2585                   firstLine = false;
2586                }
2587                f.Puts(line);
2588                f.Puts("\n");
2589             }
2590             if(!result) break;
2591          }
2592          delete dep;
2593
2594          // If we failed to generate dependencies...
2595          if(!result)
2596          {
2597 #endif
2598             f.Printf("$(OBJ)$(MODULE).main$(O): $(OBJ)$(MODULE).main.c\n");
2599 #if 0
2600          }
2601       }
2602 #endif
2603
2604       f.Printf("\t$(CC) $(CFLAGS) $(FVISIBILITY) -c $(OBJ)$(MODULE).main.%s -o $(OBJ)$(MODULE).main$(O)\n\n", extension);
2605
2606       delete objDirExp;
2607    }
2608
2609    void MatchProjectAndConfigPlatformOptions(ProjectConfig config, Platform platform,
2610          PlatformOptions * projectPlatformOptions, PlatformOptions * configPlatformOptions)
2611    {
2612       *projectPlatformOptions = null;
2613       *configPlatformOptions = null;
2614       if(platforms)
2615       {
2616          for(p : platforms)
2617          {
2618             if(!strcmpi(p.name, platform))
2619             {
2620                *projectPlatformOptions = p;
2621                break;
2622             }
2623          }
2624       }
2625       if(config && config.platforms)
2626       {
2627          for(p : config.platforms)
2628          {
2629             if(!strcmpi(p.name, platform))
2630             {
2631                *configPlatformOptions = p;
2632                break;
2633             }
2634          }
2635       }
2636    }
2637 }
2638
2639 Project LegacyBinaryLoadProject(File f, char * filePath)
2640 {
2641    Project project = null;
2642    char signature[sizeof(epjSignature)];
2643
2644    f.Read(signature, sizeof(signature), 1);
2645    if(!strncmp(signature, (char *)epjSignature, sizeof(epjSignature)))
2646    {
2647       char topNodePath[MAX_LOCATION];
2648       /*ProjectConfig newConfig
2649       {
2650          name = CopyString("Default");
2651          makingModified = true;
2652          compilingModified = true;
2653          linkingModified = true;
2654          options = { };
2655       };*/
2656
2657       project = Project { options = { } };
2658       LegacyBinaryLoadNode(project.topNode, f);
2659       delete project.topNode.path;
2660       GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
2661       MakeSlashPath(topNodePath);
2662
2663       PathCatSlash(topNodePath, filePath);
2664       project.filePath = topNodePath;
2665       
2666       /* THIS IS ALREADY DONE BY filePath property
2667       StripLastDirectory(topNodePath, topNodePath);
2668       project.topNode.path = CopyString(topNodePath);
2669       */
2670       // Shouldn't this be done BEFORE the StripLastDirectory? project.filePath = topNodePath;
2671       
2672       // newConfig.options.defaultNameSpace = "";
2673       /*newConfig.objDir.dir = "obj";
2674       newConfig.targetDir.dir = "";*/
2675
2676       //project.configurations = { [ newConfig ] };
2677       //project.config = newConfig;
2678
2679       // Project Settings
2680       if(!f.Eof())
2681       {
2682          int temp;
2683          int len,c, count;
2684          String targetFileName, targetDirectory, objectsDirectory;
2685
2686          // { executable = 0, sharedLibrary = 1, staticLibrary = 2 };
2687          f.Read(&temp, sizeof(int),1);
2688          switch(temp)
2689          {
2690             case 0: project.options.targetType = executable; break;
2691             case 1: project.options.targetType = sharedLibrary; break;
2692             case 2: project.options.targetType = staticLibrary; break;
2693          }
2694
2695          f.Read(&len, sizeof(int),1);
2696          targetFileName = new char[len+1];
2697          f.Read(targetFileName, sizeof(char), len+1);
2698          project.options.targetFileName = targetFileName;
2699          delete targetFileName;
2700
2701          f.Read(&len, sizeof(int),1);
2702          targetDirectory = new char[len+1];
2703          f.Read(targetDirectory, sizeof(char), len+1);
2704          project.options.targetDirectory = targetDirectory;
2705          delete targetDirectory;
2706
2707          f.Read(&len, sizeof(int),1);
2708          objectsDirectory = new byte[len+1];
2709          f.Read(objectsDirectory, sizeof(char), len+1);
2710          project.options.objectsDirectory = objectsDirectory;
2711          delete objectsDirectory;
2712
2713          f.Read(&temp, sizeof(int),1);
2714          project./*config.*/options.debug = temp ? true : false;
2715          f.Read(&temp, sizeof(int),1);         
2716          project./*config.*/options.optimization = temp ? speed : none;
2717          f.Read(&temp, sizeof(int),1);
2718          project./*config.*/options.profile = temp ? true : false;
2719          f.Read(&temp, sizeof(int),1);
2720          project.options.warnings = temp ? all : unset;
2721
2722          f.Read(&count, sizeof(int),1);
2723          if(count)
2724          {
2725             project.options.includeDirs = { };
2726             for(c = 0; c < count; c++)
2727             {
2728                char * name;
2729                f.Read(&len, sizeof(int),1);
2730                name = new char[len+1];
2731                f.Read(name, sizeof(char), len+1);
2732                project.options.includeDirs.Add(name);
2733             }
2734          }
2735
2736          f.Read(&count, sizeof(int),1);
2737          if(count)
2738          {
2739             project.options.libraryDirs = { };
2740             for(c = 0; c < count; c++)
2741             {
2742                char * name;            
2743                f.Read(&len, sizeof(int),1);
2744                name = new char[len+1];
2745                f.Read(name, sizeof(char), len+1);
2746                project.options.libraryDirs.Add(name);
2747             }
2748          }
2749
2750          f.Read(&count, sizeof(int),1);
2751          if(count)
2752          {
2753             project.options.libraries = { };
2754             for(c = 0; c < count; c++)
2755             {
2756                char * name;
2757                f.Read(&len, sizeof(int),1);
2758                name = new char[len+1];
2759                f.Read(name, sizeof(char), len+1);
2760                project.options.libraries.Add(name);
2761             }
2762          }
2763
2764          f.Read(&count, sizeof(int),1);
2765          if(count)
2766          {
2767             project.options.preprocessorDefinitions = { };
2768             for(c = 0; c < count; c++)
2769             {
2770                char * name;
2771                f.Read(&len, sizeof(int),1);
2772                name = new char[len+1];
2773                f.Read(name, sizeof(char), len+1);
2774                project.options.preprocessorDefinitions.Add(name);
2775             }
2776          }
2777
2778          f.Read(&temp, sizeof(int),1);
2779          project.options.console = temp ? true : false;
2780       }
2781
2782       for(node : project.topNode.files)
2783       {
2784          if(node.type == resources)
2785          {
2786             project.resNode = node;
2787             break;
2788          }
2789       }
2790    }
2791    else
2792       f.Seek(0, start);
2793    return project;
2794 }
2795
2796 void ProjectConfig::LegacyProjectConfigLoad(File f)
2797 {  
2798    delete options;
2799    options = { };
2800    while(!f.Eof())
2801    {
2802       char buffer[65536];
2803       char section[128];
2804       char subSection[128];
2805       char * equal;
2806       int len;
2807       uint pos;
2808       
2809       pos = f.Tell();
2810       f.GetLine(buffer, 65536 - 1);
2811       TrimLSpaces(buffer, buffer);
2812       TrimRSpaces(buffer, buffer);
2813       if(strlen(buffer))
2814       {
2815          if(buffer[0] == '-')
2816          {
2817             equal = &buffer[0];
2818             equal[0] = ' ';
2819             TrimLSpaces(equal, equal);
2820             if(!strcmpi(subSection, "LibraryDirs"))
2821             {
2822                if(!options.libraryDirs)
2823                   options.libraryDirs = { [ CopyString(equal) ] };
2824                else
2825                   options.libraryDirs.Add(CopyString(equal));
2826             }
2827             else if(!strcmpi(subSection, "IncludeDirs"))
2828             {
2829                if(!options.includeDirs)
2830                   options.includeDirs = { [ CopyString(equal) ] };
2831                else
2832                   options.includeDirs.Add(CopyString(equal));
2833             }
2834          }
2835          else if(buffer[0] == '+')
2836          {
2837             if(name)
2838             {
2839                f.Seek(pos, start);
2840                break;
2841             }
2842             else
2843             {
2844                equal = &buffer[0];
2845                equal[0] = ' ';
2846                TrimLSpaces(equal, equal);
2847                delete name; name = CopyString(equal); // property::name = equal;
2848             }
2849          }
2850          else if(!strcmpi(buffer, "Compiler Options"))
2851             strcpy(section, buffer);
2852          else if(!strcmpi(buffer, "IncludeDirs"))
2853             strcpy(subSection, buffer);
2854          else if(!strcmpi(buffer, "Linker Options"))
2855             strcpy(section, buffer);
2856          else if(!strcmpi(buffer, "LibraryDirs"))
2857             strcpy(subSection, buffer);
2858          else if(!strcmpi(buffer, "Files") || !strcmpi(buffer, "Resources"))
2859          {
2860             f.Seek(pos, start);
2861             break;
2862          }
2863          else
2864          {
2865             equal = strstr(buffer, "=");
2866             if(equal)
2867             {
2868                equal[0] = '\0';
2869                TrimRSpaces(buffer, buffer);
2870                equal++;
2871                TrimLSpaces(equal, equal);
2872                if(!strcmpi(buffer, "Target Name"))
2873                   options.targetFileName = /*CopyString(*/equal/*)*/;
2874                else if(!strcmpi(buffer, "Target Type"))
2875                {
2876                   if(!strcmpi(equal, "Executable"))
2877                      options.targetType = executable;
2878                   else if(!strcmpi(equal, "Shared"))
2879                      options.targetType = sharedLibrary;
2880                   else if(!strcmpi(equal, "Static"))
2881                      options.targetType = staticLibrary;
2882                   else
2883                      options.targetType = executable;
2884                }
2885                else if(!strcmpi(buffer, "Target Directory"))
2886                   options.targetDirectory = /*CopyString(*/equal/*)*/;
2887                else if(!strcmpi(buffer, "Console"))
2888                   options.console = ParseTrueFalseValue(equal);
2889                else if(!strcmpi(buffer, "Libraries"))
2890                {
2891                   if(!options.libraries) options.libraries = { };
2892                   ParseArrayValue(options.libraries, equal);
2893                }
2894                else if(!strcmpi(buffer, "Intermediate Directory"))
2895                   options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
2896                else if(!strcmpi(buffer, "Debug"))
2897                   options.debug = ParseTrueFalseValue(equal);
2898                else if(!strcmpi(buffer, "Optimize"))
2899                {
2900                   if(!strcmpi(equal, "None"))
2901                      options.optimization = none;
2902                   else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
2903                      options.optimization = speed;
2904                   else if(!strcmpi(equal, "Size"))
2905                      options.optimization = size;
2906                   else
2907                      options.optimization = none;
2908                }
2909                else if(!strcmpi(buffer, "Compress"))
2910                   options.compress = ParseTrueFalseValue(equal);
2911                else if(!strcmpi(buffer, "Profile"))
2912                   options.profile = ParseTrueFalseValue(equal);
2913                else if(!strcmpi(buffer, "AllWarnings"))
2914                   options.warnings = ParseTrueFalseValue(equal) ? all : unset;
2915                else if(!strcmpi(buffer, "MemoryGuard"))
2916                   options.memoryGuard = ParseTrueFalseValue(equal);
2917                else if(!strcmpi(buffer, "Default Name Space"))
2918                   options.defaultNameSpace = CopyString(equal);
2919                else if(!strcmpi(buffer, "Strict Name Spaces"))
2920                   options.strictNameSpaces = ParseTrueFalseValue(equal);
2921                else if(!strcmpi(buffer, "Preprocessor Definitions"))
2922                {
2923                   if(!options.preprocessorDefinitions) options.preprocessorDefinitions = { };
2924                   ParseArrayValue(options.preprocessorDefinitions, equal);
2925                }
2926             }
2927          }
2928       }
2929    }
2930    if(!options.targetDirectory && options.objectsDirectory)
2931       options.targetDirectory = /*CopyString(*/options.objectsDirectory/*)*/;
2932    //if(!objDir.dir) objDir.dir = "obj";
2933    //if(!targetDir.dir) targetDir.dir = "";
2934    // if(!targetName) property::targetName = "";   // How can a targetFileName be nothing???
2935    // if(!defaultNameSpace) property::defaultNameSpace = "";
2936    makingModified = true;
2937 }
2938
2939 Project LegacyAsciiLoadProject(File f, char * filePath)
2940 {
2941    Project project = null;
2942    ProjectNode node = null;
2943    int pos;
2944    char parentPath[MAX_LOCATION];
2945    char section[128] = "";
2946    char subSection[128] = "";
2947    ProjectNode parent;
2948    bool configurationsPresent = false;
2949
2950    f.Seek(0, start);
2951    while(!f.Eof())
2952    {
2953       char buffer[65536];
2954       //char version[16];
2955       char * equal;
2956       int len;
2957       pos = f.Tell();
2958       f.GetLine(buffer, 65536 - 1);
2959       TrimLSpaces(buffer, buffer);
2960       TrimRSpaces(buffer, buffer);
2961       if(strlen(buffer))
2962       {
2963          if(buffer[0] == '-' || buffer[0] == '=')
2964          {
2965             bool simple = buffer[0] == '-';
2966             equal = &buffer[0];
2967             equal[0] = ' ';
2968             TrimLSpaces(equal, equal);
2969             if(!strcmpi(section, "Target") && !strcmpi(subSection, "LibraryDirs"))
2970             {
2971                if(!project.config.options.libraryDirs) project.config.options.libraryDirs = { };
2972                project.config.options.libraryDirs.Add(CopyString(equal));
2973             }
2974             else if(!strcmpi(section, "Target") && !strcmpi(subSection, "IncludeDirs"))
2975             {
2976                if(!project.config.options.includeDirs) project.config.options.includeDirs = { };
2977                project.config.options.includeDirs.Add(CopyString(equal));
2978             }
2979             else if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
2980             {
2981                len = strlen(equal);
2982                if(len)
2983                {
2984                   char temp[MAX_LOCATION];
2985                   ProjectNode child { };
2986                   // We don't need to do this anymore, fileName is just a property that sets name & path
2987                   // child.fileName = CopyString(equal);
2988                   if(simple)
2989                   {
2990                      child.name = CopyString(equal);
2991                      child.path = CopyString(parentPath);
2992                   }
2993                   else
2994                   {
2995                      GetLastDirectory(equal, temp);
2996                      child.name = CopyString(temp);
2997                      StripLastDirectory(equal, temp);
2998                      child.path = CopyString(temp);
2999                   }
3000                   child.nodeType = file;
3001                   child.parent = parent;
3002                   child.indent = parent.indent + 1;
3003                   child.type = file;
3004                   child.icon = NodeIcons::SelectFileIcon(child.name);
3005                   parent.files.Add(child);
3006                   node = child;
3007                   //child = null;
3008                }
3009                else
3010                {
3011                   StripLastDirectory(parentPath, parentPath);
3012                   parent = parent.parent;
3013                }
3014             }
3015          }
3016          else if(buffer[0] == '+')
3017          {
3018             equal = &buffer[0];
3019             equal[0] = ' ';
3020             TrimLSpaces(equal, equal);
3021             if(!strcmpi(section, "Target") && (!strcmpi(subSection, "Files") || !strcmpi(subSection, "Resources")))
3022             {
3023                char temp[MAX_LOCATION];
3024                ProjectNode child { };
3025                // NEW: Folders now have a path set like files
3026                child.name = CopyString(equal);
3027                strcpy(temp, parentPath);
3028                PathCatSlash(temp, child.name);
3029                child.path = CopyString(temp);
3030
3031                child.parent = parent;
3032                child.indent = parent.indent + 1;
3033                child.type = folder;
3034                child.nodeType = folder;
3035                child.files = { };
3036                child.icon = folder;
3037                PathCatSlash(parentPath, child.name);
3038                parent.files.Add(child);
3039                parent = child;
3040                node = child;
3041                //child = null;
3042             }
3043             else if(!strcmpi(section, "Configurations"))
3044             {
3045                ProjectConfig newConfig
3046                {
3047                   makingModified = true;
3048                   options = { };
3049                };
3050                f.Seek(pos, start);
3051                LegacyProjectConfigLoad(newConfig, f);
3052                project.configurations.Add(newConfig);
3053             }
3054          }
3055          else if(!strcmpi(buffer, "ECERE Project File"));
3056          else if(!strcmpi(buffer, "Version 0a"))
3057             ; //strcpy(version, "0a");
3058          else if(!strcmpi(buffer, "Version 0.1a"))
3059             ; //strcpy(version, "0.1a");
3060          else if(!strcmpi(buffer, "Configurations"))
3061          {
3062             project.configurations.Free();
3063             project.config = null;
3064             strcpy(section, buffer);
3065             configurationsPresent = true;
3066          }
3067          else if(!strcmpi(buffer, "Target") || !strnicmp(buffer, "Target \"", strlen("Target \"")))
3068          {
3069             ProjectConfig newConfig { name = CopyString("Default"), options = { } };
3070             char topNodePath[MAX_LOCATION];
3071             // newConfig.defaultNameSpace = "";
3072             //newConfig.objDir.dir = "obj";
3073             //newConfig.targetDir.dir = "";
3074             project = Project { /*options = { }*/ };
3075             project.configurations = { [ newConfig ] };
3076             project.config = newConfig;
3077             // if(project.topNode.path) delete project.topNode.path;
3078             GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3079             MakeSlashPath(topNodePath);
3080             PathCatSlash(topNodePath, filePath);
3081             project.filePath = topNodePath;
3082             parentPath[0] = '\0';
3083             parent = project.topNode;
3084             node = parent;
3085             strcpy(section, "Target");
3086             equal = &buffer[6];
3087             if(equal[0] == ' ')
3088             {
3089                equal++;
3090                if(equal[0] == '\"')
3091                {
3092                   StripQuotes(equal, equal);
3093                   delete project.moduleName; project.moduleName = CopyString(equal);
3094                }
3095             }
3096          }
3097          else if(!strcmpi(buffer, "Compiler Options"));
3098          else if(!strcmpi(buffer, "IncludeDirs"))
3099             strcpy(subSection, buffer);
3100          else if(!strcmpi(buffer, "Linker Options"));
3101          else if(!strcmpi(buffer, "LibraryDirs"))
3102             strcpy(subSection, buffer);
3103          else if(!strcmpi(buffer, "Files"))
3104          {
3105             strcpy(section, "Target");
3106             strcpy(subSection, buffer);
3107          }
3108          else if(!strcmpi(buffer, "Resources"))
3109          {
3110             ProjectNode child { };
3111             parent.files.Add(child);
3112             child.parent = parent;
3113             child.indent = parent.indent + 1;
3114             child.name = CopyString(buffer);
3115             child.path = CopyString("");
3116             child.type = resources;
3117             child.files = { };
3118             child.icon = archiveFile;
3119             project.resNode = child;
3120             parent = child;
3121             node = child;
3122             strcpy(subSection, buffer);
3123          }
3124          else
3125          {
3126             equal = strstr(buffer, "=");
3127             if(equal)
3128             {
3129                equal[0] = '\0';
3130                TrimRSpaces(buffer, buffer);
3131                equal++;
3132                TrimLSpaces(equal, equal);
3133
3134                if(!strcmpi(section, "Target"))
3135                {
3136                   if(!strcmpi(buffer, "Build Exclusions"))
3137                   {
3138                      if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3139                      {
3140                         /*if(node && node.type != NodeTypes::project)
3141                            ParseListValue(node.buildExclusions, equal);*/
3142                      }
3143                   }
3144                   else if(!strcmpi(buffer, "Path") && !strcmpi(subSection, "Resources"))
3145                   {
3146                      delete project.resNode.path;
3147                      project.resNode.path = CopyString(equal);
3148                      PathCatSlash(parentPath, equal);
3149                   }
3150
3151                   // Config Settings
3152                   else if(!strcmpi(buffer, "Intermediate Directory"))
3153                      project.config.options.objectsDirectory = /*CopyString(*/equal/*)*/; //objDir.expression = equal;
3154                   else if(!strcmpi(buffer, "Debug"))
3155                      project.config.options.debug = ParseTrueFalseValue(equal);
3156                   else if(!strcmpi(buffer, "Optimize"))
3157                   {
3158                      if(!strcmpi(equal, "None"))
3159                         project.config.options.optimization = none;
3160                      else if(!strcmpi(equal, "Speed") || !strcmpi(equal, "True"))
3161                         project.config.options.optimization = speed;
3162                      else if(!strcmpi(equal, "Size"))
3163                         project.config.options.optimization = size;
3164                      else
3165                         project.config.options.optimization = none;
3166                   }
3167                   else if(!strcmpi(buffer, "Profile"))
3168                      project.config.options.profile = ParseTrueFalseValue(equal);
3169                   else if(!strcmpi(buffer, "MemoryGuard"))
3170                      project.config.options.memoryGuard = ParseTrueFalseValue(equal);
3171                   else
3172                   {
3173                      if(!project.options) project.options = { };
3174
3175                      // Project Wide Settings (All configs)
3176                      if(!strcmpi(buffer, "Target Name"))
3177                         project.options.targetFileName = /*CopyString(*/equal/*)*/;
3178                      else if(!strcmpi(buffer, "Target Type"))
3179                      {
3180                         if(!strcmpi(equal, "Executable"))
3181                            project.options.targetType = executable;
3182                         else if(!strcmpi(equal, "Shared"))
3183                            project.options.targetType = sharedLibrary;
3184                         else if(!strcmpi(equal, "Static"))
3185                            project.options.targetType = staticLibrary;
3186                         else
3187                            project.options.targetType = executable;
3188                      }
3189                      else if(!strcmpi(buffer, "Target Directory"))
3190                         project.options.targetDirectory = /*CopyString(*/equal/*)*/;
3191                      else if(!strcmpi(buffer, "Console"))
3192                         project.options.console = ParseTrueFalseValue(equal);
3193                      else if(!strcmpi(buffer, "Libraries"))
3194                      {
3195                         if(!project.options.libraries) project.options.libraries = { };
3196                         ParseArrayValue(project.options.libraries, equal);
3197                      }
3198                      else if(!strcmpi(buffer, "AllWarnings"))
3199                         project.options.warnings = ParseTrueFalseValue(equal) ? all : unset;
3200                      else if(!strcmpi(buffer, "Preprocessor Definitions"))
3201                      {
3202                         if(!strcmpi(section, "Target") && !strcmpi(subSection, "Files"))
3203                         {
3204                            /*if(node && (node.type == NodeTypes::project || (node.type == file && !node.isInResources) || node.type == folder))
3205                               ParseListValue(node.preprocessorDefs, equal);*/
3206                         }
3207                         else
3208                         {
3209                            if(!project.options.preprocessorDefinitions) project.options.preprocessorDefinitions = { };
3210                            ParseArrayValue(project.options.preprocessorDefinitions, equal);
3211                         }
3212                      }
3213                   }
3214                }
3215             }
3216          }
3217       }
3218    }
3219    parent = null;
3220
3221    SplitPlatformLibraries(project);
3222
3223    if(configurationsPresent)
3224       CombineIdenticalConfigOptions(project);
3225    return project;
3226 }
3227
3228 void SplitPlatformLibraries(Project project)
3229 {
3230    if(project && project.configurations)
3231    {
3232       for(cfg : project.configurations)
3233       {
3234          if(cfg.options.libraries && cfg.options.libraries.count)
3235          {
3236             Iterator<String> it { cfg.options.libraries };
3237             while(it.Next())
3238             {
3239                String l = it.data;
3240                char * platformName = strstr(l, ":");
3241                if(platformName)
3242                {
3243                   PlatformOptions platform = null;
3244                   platformName++;
3245                   if(!cfg.platforms) cfg.platforms = { };
3246                   for(p : cfg.platforms)
3247                   {
3248                      if(!strcmpi(platformName, p.name))
3249                      {
3250                         platform = p;
3251                         break;
3252                      }
3253                   }
3254                   if(!platform)
3255                   {
3256                      platform = { name = CopyString(platformName), options = { libraries = { } } };
3257                      cfg.platforms.Add(platform);
3258                   }
3259                   *(platformName-1) = 0;
3260                   platform.options.libraries.Add(CopyString(l));
3261
3262                   cfg.options.libraries.Delete(it.pointer);
3263                   it.pointer = null;
3264                }
3265             }
3266          }
3267       }      
3268    }
3269 }
3270
3271 void CombineIdenticalConfigOptions(Project project)
3272 {
3273    if(project && project.configurations && project.configurations.count)
3274    {
3275       DataMember member;
3276       ProjectOptions nullOptions { };
3277       ProjectConfig firstConfig = null;
3278       for(cfg : project.configurations)
3279       {
3280          if(cfg.options.targetType != staticLibrary)
3281          {
3282             firstConfig = cfg;
3283             break;
3284          }
3285       }
3286       if(!firstConfig)
3287          firstConfig = project.configurations.firstIterator.data;
3288
3289       for(member = class(ProjectOptions).membersAndProperties.first; member; member = member.next)
3290       {
3291          if(!member.isProperty)
3292          {
3293             Class type = eSystem_FindClass(__thisModule, member.dataTypeString);
3294             if(type)
3295             {
3296                bool same = true;
3297
3298                for(cfg : project.configurations)
3299                {
3300                   if(cfg != firstConfig)
3301                   {
3302                      if(cfg.options.targetType != staticLibrary)
3303                      {
3304                         int result;
3305                         
3306                         if(type.type == noHeadClass || type.type == normalClass)
3307                         {
3308                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3309                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3310                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3311                         }
3312                         else
3313                         {
3314                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3315                               (byte *)firstConfig.options + member.offset + member._class.offset,
3316                               (byte *)cfg.options         + member.offset + member._class.offset);
3317                         }
3318                         if(result)
3319                         {
3320                            same = false;
3321                            break;
3322                         }
3323                      }
3324                   }                  
3325                }
3326                if(same)
3327                {
3328                   if(type.type == noHeadClass || type.type == normalClass)
3329                   {
3330                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3331                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3332                         *(void **)((byte *)nullOptions         + member.offset + member._class.offset)))
3333                         continue;
3334                   }
3335                   else
3336                   {
3337                      if(!type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3338                         (byte *)firstConfig.options + member.offset + member._class.offset,
3339                         (byte *)nullOptions         + member.offset + member._class.offset))
3340                         continue;
3341                   }
3342
3343                   if(!project.options) project.options = { };
3344                   
3345                   /*if(type.type == noHeadClass || type.type == normalClass)
3346                   {
3347                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3348                         (byte *)project.options + member.offset + member._class.offset,
3349                         *(void **)((byte *)firstConfig.options + member.offset + member._class.offset));
3350                   }
3351                   else
3352                   {
3353                      void * address = (byte *)firstConfig.options + member.offset + member._class.offset;
3354                      // TOFIX: ListBox::SetData / OnCopy mess
3355                      type._vTbl[__ecereVMethodID_class_OnCopy](type, 
3356                         (byte *)project.options + member.offset + member._class.offset,
3357                         (type.typeSize > 4) ? address : 
3358                            ((type.typeSize == 4) ? (void *)*(uint32 *)address : 
3359                               ((type.typeSize == 2) ? (void *)*(uint16*)address : 
3360                                  (void *)*(byte *)address )));                              
3361                   }*/
3362                   memcpy(
3363                      (byte *)project.options + member.offset + member._class.offset,
3364                      (byte *)firstConfig.options + member.offset + member._class.offset, type.typeSize);
3365
3366                   for(cfg : project.configurations)
3367                   {
3368                      if(cfg.options.targetType == staticLibrary)
3369                      {
3370                         int result;
3371                         
3372                         if(type.type == noHeadClass || type.type == normalClass)
3373                         {
3374                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3375                               *(void **)((byte *)firstConfig.options + member.offset + member._class.offset),
3376                               *(void **)((byte *)cfg.options         + member.offset + member._class.offset));
3377                         }
3378                         else
3379                         {
3380                            result = type._vTbl[__ecereVMethodID_class_OnCompare](type, 
3381                               (byte *)firstConfig.options + member.offset + member._class.offset,
3382                               (byte *)cfg.options         + member.offset + member._class.offset);
3383                         }
3384                         if(result)
3385                            continue;
3386                      }
3387                      if(cfg != firstConfig)
3388                      {
3389                         if(type.type == noHeadClass || type.type == normalClass)
3390                         {
3391                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3392                               *(void **)((byte *)cfg.options + member.offset + member._class.offset));
3393                         }
3394                         else
3395                         {
3396                            type._vTbl[__ecereVMethodID_class_OnFree](type, 
3397                               (byte *)cfg.options + member.offset + member._class.offset);
3398                         }
3399                         memset((byte *)cfg.options + member.offset + member._class.offset, 0, type.typeSize);
3400                      }                     
3401                   }
3402                   memset((byte *)firstConfig.options + member.offset + member._class.offset, 0, type.typeSize);
3403                }
3404             }
3405          }
3406       }
3407       delete nullOptions;
3408
3409       // Compare Platform Specific Settings
3410       {
3411          bool same = true;
3412          for(cfg : project.configurations)
3413          {
3414             if(cfg != firstConfig && cfg.options.targetType != staticLibrary && (firstConfig.platforms || cfg.platforms) &&
3415                ((!firstConfig.platforms && cfg.platforms) || firstConfig.platforms.OnCompare(cfg.platforms)))
3416             {
3417                same = false;
3418                break;
3419             }
3420          }
3421          if(same && firstConfig.platforms)
3422          {
3423             for(cfg : project.configurations)
3424             {
3425                if(cfg.options.targetType == staticLibrary && firstConfig.platforms.OnCompare(cfg.platforms))
3426                   continue;
3427                if(cfg != firstConfig)
3428                {
3429                   cfg.platforms.Free();
3430                   delete cfg.platforms;
3431                }
3432             }
3433             project.platforms = firstConfig.platforms;
3434             firstConfig.platforms = null;
3435          }
3436       }
3437
3438       // Static libraries can't contain libraries
3439       for(cfg : project.configurations)
3440       {
3441          if(cfg.options.targetType == staticLibrary)
3442          {
3443             if(!cfg.options.libraries) cfg.options.libraries = { };
3444             cfg.options.libraries.Free();
3445          }
3446       }
3447    }
3448 }
3449
3450 Project LoadProject(char * filePath)
3451 {
3452    Project project = null;
3453    File f = FileOpen(filePath, read);
3454    if(f)
3455    {
3456       project = LegacyBinaryLoadProject(f, filePath);
3457       if(!project)
3458       {
3459          JSONParser parser { f = f };
3460          JSONResult result = parser.GetObject(class(Project), &project);
3461          if(project)
3462          {
3463             char insidePath[MAX_LOCATION];
3464
3465             delete project.topNode.files;
3466             if(!project.files) project.files = { };
3467             project.topNode.files = project.files;
3468             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3469             delete project.resNode.path;
3470             project.resNode.path = project.resourcesPath;
3471             project.resourcesPath = null;
3472             project.resNode.nodeType = (ProjectNodeType)-1;
3473             delete project.resNode.files;
3474             project.resNode.files = project.resources;
3475             project.files = null;
3476             project.resources = null;
3477             if(!project.configurations) project.configurations = { };
3478
3479             {
3480                char topNodePath[MAX_LOCATION];
3481                GetWorkingDir(topNodePath, sizeof(topNodePath)-1);
3482                MakeSlashPath(topNodePath);
3483                PathCatSlash(topNodePath, filePath);
3484                project.filePath = topNodePath;//filePath;
3485             }
3486
3487             project.topNode.FixupNode(insidePath);
3488          }
3489          delete parser;
3490       }
3491       if(!project)
3492          project = LegacyAsciiLoadProject(f, filePath);
3493
3494       delete f;
3495
3496       if(project)
3497       {
3498          if(!project.options) project.options = { };
3499          if(!project.config && project.configurations)
3500             project.config = project.configurations.firstIterator.data;
3501
3502          if(!project.resNode)
3503          {
3504             project.resNode = project.topNode.Add(project, "Resources", project.topNode.files.last, resources, archiveFile, false);
3505          }
3506          
3507          if(!project.moduleName)
3508             project.moduleName = CopyString(project.name);
3509          if(project.config && 
3510             (!project.options || !project.options.targetFileName || !project.options.targetFileName[0]) &&
3511             (!project.config.options.targetFileName || !project.config.options.targetFileName[0]))
3512          {
3513             //delete project.config.options.targetFileName;
3514             
3515             project.options.targetFileName = /*CopyString(*/project.moduleName/*)*/;
3516             project.config.options.optimization = none;
3517             project.config.options.debug = true;
3518             //project.config.options.warnings = unset;
3519             project.config.options.memoryGuard = false;
3520             project.config.compilingModified = true;
3521             project.config.linkingModified = true;
3522          }
3523          else if(!project.topNode.name && project.config)
3524          {
3525             project.topNode.name = CopyString(project.config.options.targetFileName);
3526          }
3527
3528          /* // THIS IS NOW AUTOMATED WITH A project CHECK IN ProjectNode
3529          project.topNode.configurations = project.configurations;
3530          project.topNode.platforms = project.platforms;
3531          project.topNode.options = project.options;*/
3532       }
3533    }
3534    return project;
3535 }