0a59d1c89e35dfba2920f5710b5f101303b2f54b
[ghc-hetmet.git] / utils / prof / cgprof / daVinci.c
1 /* ------------------------------------------------------------------------
2  * $Id: daVinci.c,v 1.5 2006/01/09 14:38:01 simonmar Exp $
3  *                                                                      
4  *      Copyright (C) 1995-2000 University of Oxford
5  *                                                                      
6  * Permission to use, copy, modify, and distribute this software,
7  * and to incorporate it, in whole or in part, into other software,
8  * is hereby granted without fee, provided that
9  *   (1) the above copyright notice and this permission notice appear in
10  *       all copies of the source code, and the above copyright notice
11  *       appear in clearly visible form on all supporting documentation
12  *       and distribution media;
13  *   (2) modified versions of this software be accompanied by a complete
14  *       change history describing author, date, and modifications made;
15  *       and
16  *   (3) any redistribution of the software, in original or modified
17  *       form, be without fee and subject to these same conditions.
18  * --------------------------------------------------------------------- */
19
20 #include "daVinci.h"
21 #include <stdarg.h>
22 #include <string.h>
23 #include <ctype.h>
24
25 static char* extra_space(int);
26 static void recur_graphToDaVinci(int,Matrix *, Matrix *,char*,int);
27 static char *parse_word(char**);
28 static char *parse_quoted(char**);
29 static char *dup_str(char*);
30 double this_total_time,
31        this_total_comp_max, this_total_comp_avg,
32        this_total_comm_max, this_total_comm_avg, 
33        this_total_comp_idle_max, this_total_comp_idle_avg;
34 long int this_hrel_max, this_hrel_avg;
35 int  this_syncs;
36
37 char *lastDavinciCmd;
38
39 /* -----------------------------------------------------------------------------
40  * Send a command with ok return value daVinci
41  * -------------------------------------------------------------------------- */
42
43 void cmdDaVinci(char* format,...) {
44   va_list args;
45
46   va_start(args, format);
47   vfprintf(stdout, format, args);
48   fprintf(stdout, "\n");
49   va_end(args);
50   fflush(stdout); 
51   lastDavinciCmd = format;
52 }
53
54 /* -----------------------------------------------------------------------------
55  * Initialise daVinci
56  * -------------------------------------------------------------------------- */
57
58 void initDaVinci() {
59   cmdDaVinci("window(title(\"GHC profiler: cost-centre-stack view\"))\n");
60   cmdDaVinci("set(font_size(8))");  
61   cmdDaVinci("set(animation_speed(0))");
62   cmdDaVinci("set(scrolling_on_selection(false))");
63   /* SAJ */
64   /* cmdDaVinci("set(no_cache(true)))"); */
65   cmdDaVinci("app_menu(create_icons(["
66                   "icon_entry(\"delete\","
67                              "\"delete.xbm\","
68                              "\"Delete node and its children\"),"
69                   "icon_entry(\"undo\","
70                              "\"undo.xbm\","
71                              "\"Undo delete\"),"
72                   "blank,"
73                   "icon_entry(\"time\","
74                              "\"time.xbm\","
75                              "\"Cost metric view\"),"
76                   "icon_entry(\"percent\","
77                              "\"percent.xbm\","
78                              "\"Percentage view\"),"
79                   "blank,"
80                   "icon_entry(\"compress\","
81                              "\"compress.xbm\","
82                              "\"Compressed node view\"),"
83                   "icon_entry(\"uncompress\","
84                              "\"uncompress.xbm\","
85                              "\"Uncompressed node view\"),"
86                   "blank,"
87                   "icon_entry(\"absolute\","
88                              "\"absolute.xbm\","
89                              "\"Display inherited profile results\"),"
90                   "icon_entry(\"absdelta\","
91                              "\"absdelta.xbm\","
92                              "\"Display flat profile results\"),"
93                   "icon_entry(\"reldelta\","
94                              "\"reldelta.xbm\","
95                              "\"Trim zero-cost sub-trees\"),"
96                   "icon_entry(\"weightdelta\","
97                              "\"weightdelta.xbm\","
98                              "\"Trim zero-cost nodes\"),"
99                   "blank,"
100                   "icon_entry(\"sync\","
101                              "\"sync.xbm\","
102                              "\"Graph view\"),"
103                   "icon_entry(\"comp\","
104                              "\"comp.xbm\","
105                              "\"SCCs critical path\"),"
106                   "icon_entry(\"comm\","
107                              "\"comm.xbm\","
108                              "\"Computation time critical path\"),"
109                   "icon_entry(\"wait\","
110                              "\"wait.xbm\","
111                              "\"Heap usage critical path\"),"
112                   "icon_entry(\"hrel\","
113                              "\"hrel.xbm\","
114                              "\"Node spy\"),"
115                   "blank,"
116                   "icon_entry(\"help\","
117                              "\"help.xbm\","
118                              "\"Help\"),"
119               "]))");
120
121   activateDaVinciMenu("default");     
122   cmdDaVinci("app_menu(create_menus([menu_entry_mne(\"jump\",\"Goto a node\",\"G\",control,\"G\")]))\n");
123   /* SAJ */
124   // cmdDaVinci("app_menu(activate_menus([\"jump\"]))"); 
125 }
126
127 /* -----------------------------------------------------------------------------
128  * Menu FSM
129  * -------------------------------------------------------------------------- */
130
131 void activateDaVinciMenu(char *pressed) {
132   static int compress=1,time=1,critical_type=0,critical=0,undo=1,delete=0;
133
134   if (strcmp(pressed,"absolute")==0)    critical_type=0;
135   if (strcmp(pressed,"absdelta")==0)    critical_type=1;
136   if (strcmp(pressed,"reldelta")==0)    critical_type=2;
137   if (strcmp(pressed,"weightdelta")==0) critical_type=3;
138
139   if (strcmp(pressed,"sync")==0)  critical=0;
140   if (strcmp(pressed,"comp")==0)  critical=1;
141   if (strcmp(pressed,"comm")==0)  critical=2;
142   if (strcmp(pressed,"wait")==0)  critical=3;
143   if (strcmp(pressed,"hrel")==0)  critical=4;
144
145   if (strcmp(pressed,"compress")==0 || strcmp(pressed,"uncompress")==0) 
146     compress=!compress;
147
148   if (strcmp(pressed,"time")==0 || strcmp(pressed,"percent")==0)
149     time=!time;
150
151   if (strcmp(pressed,"undo")==0)   {undo=!undo;}
152   if (strcmp(pressed,"delete")==0) {delete=!delete;}
153
154   printf("app_menu(activate_icons([");
155   if (critical_type!=0) printf("\"absolute\",");
156   if (critical_type!=1) printf("\"absdelta\",");
157   if (critical_type!=2) printf("\"reldelta\",");
158   if (critical_type!=3) printf("\"weightdelta\",");
159
160   if (critical!=0) printf("\"sync\",");
161   if (critical!=1) printf("\"comp\",");
162   if (critical!=2) printf("\"comm\",");
163   if (critical!=3) printf("\"wait\",");
164   if (critical!=4) printf("\"hrel\",");
165
166   if (!compress)   printf("\"compress\",");
167   if (compress)    printf("\"uncompress\",");
168   if (!time)       printf("\"time\",");
169   if (time)        printf("\"percent\",");
170   if (!delete)     printf("\"delete\",");
171   if (!undo)       printf("\"undo\",");
172   
173   cmdDaVinci("\"help\"]))");  
174 }
175
176 /* -----------------------------------------------------------------------------
177  * Graph to daVinci
178  * -------------------------------------------------------------------------- */
179
180 void graphToDaVinci(int root,Matrix *graph, Matrix *costs, int removezerocosts) {
181   int i,j;
182   object_cost *ptr;
183   char zeronodes[MAX_PROFILE_LINE_LENGTH*2];     // is this a sen. MAX
184   char TEMPzeronodes[MAX_PROFILE_LINE_LENGTH*2];
185   char* p_zeronodes = zeronodes;
186   char* TEMPp_zeronodes = TEMPzeronodes;
187  
188   printf("graph(new([");
189   if (PrintLogo) {
190     /* I have implemented some name changes here. They are purely for output and */
191     /* following the relation (comp = scc, comm = ticks, wait = bytes            */
192     printf("l(\"info\",n(\"\",["
193            "a(\"COLOR\",\"gold\"),"
194            "a(\"FONTFAMILY\",\"courier\"),"
195            //"a(\"_GO\",\"icon\"),"
196            //"a(\"ICONFILE\",\"oxpara.xbm\"),"
197            "a(\"OBJECT\",\""
198            "Program statistics\\n\\n"
199            "Time elapsed     =  %6.2f ticks\\n"
200            "Heap usage       =  %6.2f bytes\\n"
201            "Total scc count  =  %6.2f (scc)\\n"
202            "\")],[])),",
203            TotalComm,TotalCompIdle,
204            TotalComp
205            );
206   } 
207
208   if (root==-1) {
209     printf("]))\n");
210   } else {
211     ptr = &Mat(object_cost,*costs,root,0);
212     this_total_comp_max     = ptr->comp_max;
213     this_total_comp_avg     = ptr->comp_avg;
214     this_total_comm_max     = ptr->comm_max;
215     this_total_comm_avg     = ptr->comm_avg;
216     this_total_comp_idle_max= ptr->comp_idle_max;
217     this_total_comp_idle_avg= ptr->comp_idle_avg;
218     this_total_time         = 0.00001 + 
219                               this_total_comp_max+ this_total_comm_max;
220     this_hrel_max       = ptr->hrel_max;
221     this_hrel_avg       = ptr->hrel_avg;
222     this_syncs          = ptr->syncs;
223     recur_graphToDaVinci(root,graph,costs,p_zeronodes,removezerocosts);
224
225     printf("]))\n");
226     fflush(stdout);
227     cmdDaVinci("special(focus_node(\"%d\"))\n",root);
228
229     /* graph will have been altered so that visted elements are marked
230        by a negative value. These are reset */
231     for(i=0;i<graph->rows;i++) {
232       for(j=0;j<graph->cols;j++) {
233         if (Mat_dense(*graph,i,j))
234           if (Mat(int,*graph,i,j)<0) Mat(int,*graph,i,j)=1;
235       }
236     }
237
238     if (removezerocosts==1)
239     {
240       if (strlen(p_zeronodes)>0) 
241          { strncpy(TEMPp_zeronodes,p_zeronodes,strlen(p_zeronodes)-1);
242            printf("select_nodes_labels([%s])\n",TEMPp_zeronodes);
243          }
244       strcpy(TEMPp_zeronodes,"");
245       strcpy(p_zeronodes,"");
246     }
247   }
248 }
249
250 static char *printCompressNode(int node, object_cost *ptr) {
251   char name[MAX_FUNNAME+20];
252   char comp[MAX_FUNNAME+20];
253   char comm[MAX_FUNNAME+20];
254   static char res[(MAX_FUNNAME+20)*4];
255   char tempstring[MAX_FUNNAME+20];
256   char *padding;
257   int x;
258   char delimiter[] = "&";
259
260   if (symbol_table[node].type==CG_SSTEP) 
261     sprintf(name,"%d %s",
262             symbol_table[node].lineno,symbol_table[node].filename);
263   else
264   { 
265     strcpy(tempstring,symbol_table[node].filename);
266     sprintf(name,"%s",strtok(tempstring,delimiter));
267   }  
268
269   if (NodeviewTime) {
270     /* changed this for GHC stats */
271     sprintf(comp,"\\nTime  %6.2fticks\\n",ptr->comm_max);
272     sprintf(comm,"Bytes %6.2funits",ptr->comp_idle_max);
273   } else {
274     sprintf(comp,"\\nTime  %6.2f%%\\n",(ptr->comm_max/TotalComm)*100.0);
275     sprintf(comm,"Bytes %6.2f%%",(ptr->comp_idle_max/TotalCompIdle)*100.0);
276   }
277   /* Slightly arbitrary choice for max display length of CC string */
278   /* If it is larger than this the display nodes look bad */
279   if (strlen(name)>20) name[20]='\0';
280   x=strlen(name);
281   if (((20-(strlen(name)+3))/2)>19)
282      padding = extra_space(0);
283   else
284      padding = extra_space((20-(strlen(name)+3))/2); /* includes \\n */
285   strcpy(res,padding);
286   strcat(res,name);
287   strcat(res,comp);
288   strcat(res,comm);
289   return res;
290 }
291
292 static char *printUncompressNode(int node, object_cost *ptr) {
293   char name   [MAX_FUNNAME+40];
294   char module [MAX_FUNNAME+40];
295   char group  [MAX_FUNNAME+40];
296   char head [MAX_FUNNAME+40];
297   char comp [MAX_FUNNAME+40];
298   char comm [MAX_FUNNAME+40];
299   char wait [MAX_FUNNAME+40];
300   char hrel [MAX_FUNNAME+40];
301   char tempstring[MAX_FUNNAME+20];
302   char tempstring2[MAX_FUNNAME+20];
303   char *tempstring3;
304   char *tempstring5;
305   char tempstring4[MAX_FUNNAME+20];
306   char delimiter[] = "&";
307
308
309   static char res[(MAX_FUNNAME+40)*7];
310   char *padding;
311   int width=0,x;
312
313   if (symbol_table[node].type==CG_SSTEP) 
314     sprintf(name,"%s line %d\\n",
315             symbol_table[node].filename,symbol_table[node].lineno);
316   else
317   {
318     strcpy(tempstring,symbol_table[node].filename);
319     strcpy(tempstring2,symbol_table[node].filename);
320     sprintf(name,"%s",strtok(tempstring,delimiter));
321     strcpy(tempstring4,tempstring2);
322     tempstring5 = strpbrk(tempstring4,delimiter);
323     sprintf(module,"%s",strtok(tempstring5+1,delimiter));
324     tempstring3 = strrchr(tempstring2,'&');
325     sprintf(group,"%s",tempstring3+1);
326   }
327
328   if (NodeviewTime) {
329
330     sprintf(head, "Metric   Total  \\n");
331     sprintf(comp, " Time    %6.2ft \\n",ptr->comm_max);
332     sprintf(comm, " Bytes   %6.2fu \\n",ptr->comp_idle_max);
333     sprintf(wait, " SCC     %6.2fc \\n",ptr->comp_max);
334
335
336   } else {
337
338     sprintf(head, "Metric   Total  \\n");
339     sprintf(comp, " Time    %5.1f%% \\n",100.0*SAFEDIV(ptr->comm_max,TotalComm));
340     sprintf(comm, " Bytes   %5.1f%% \\n",100.0*SAFEDIV(ptr->comp_idle_max,TotalCompIdle));
341     sprintf(wait, " SCC     %5.1f%% \\n",100.0*SAFEDIV(ptr->comp_max,TotalComp));
342
343   }
344           
345   if ((x=strlen(name))>width)  width=x;
346   if ((x=strlen(hrel))>width)  width=x;
347   padding = extra_space((width-strlen(name)+3)/2); /* includes \\n */
348   /* strcpy(res,padding); */
349   strcpy(res,"Cost centre: ");
350   strcat(res,name);
351   strcat(res,"\\n");
352   strcat(res,"Module     : ");
353   strcat(res,module);
354   strcat(res,"\\n");
355   strcat(res,"Group      : ");
356   strcat(res,group);
357   strcat(res,"\\n\\n");
358  
359   strcat(res,head);
360   strcat(res,comp);
361   strcat(res,comm);
362   strcat(res,wait);
363   /* strcat(res,hrel); */
364   return res;
365 }
366
367
368 double nodeColour(object_cost *cost) {
369
370   switch (CriticalPath + CriticalType) {
371   case CRITTYPE_ABSOLUTE+CRITICAL_SYNCS:      
372   case CRITTYPE_ABSDELTA+CRITICAL_SYNCS:      
373   case CRITTYPE_RELDELTA+CRITICAL_SYNCS:      
374   case CRITTYPE_WEIGHTDELTA+CRITICAL_SYNCS:
375     return SAFEDIV(((double)cost->syncs),((double)this_syncs));
376
377   case CRITTYPE_ABSOLUTE+CRITICAL_COMP:       
378     return SAFEDIV(cost->comp_max,this_total_comp_max);
379
380   case CRITTYPE_ABSOLUTE+CRITICAL_COMM:       
381     return SAFEDIV(cost->comm_max,this_total_comm_max);
382
383   case CRITTYPE_ABSOLUTE+CRITICAL_WAIT:       
384     return SAFEDIV(cost->comp_idle_max,this_total_comp_idle_max);
385
386   case CRITTYPE_ABSOLUTE+CRITICAL_HREL:       
387     return SAFEDIV(((double) cost->hrel_max),((double)this_hrel_max));
388
389   case CRITTYPE_ABSDELTA+CRITICAL_COMP:
390     return SAFEDIV(cost->comp_max,TotalComp);
391
392   case CRITTYPE_ABSDELTA+CRITICAL_COMM:
393     return SAFEDIV(cost->comm_max,TotalComm);
394
395   case CRITTYPE_ABSDELTA+CRITICAL_WAIT:
396     return SAFEDIV(cost->comp_idle_max,TotalCompIdle);
397
398   case CRITTYPE_ABSDELTA+CRITICAL_HREL:
399     return SAFEDIV(((double) (cost->hrel_max - cost->hrel_avg)),
400                    ((double) (this_hrel_max-this_hrel_avg)));
401
402   case CRITTYPE_RELDELTA+CRITICAL_COMP:
403    return SAFEDIV((cost->comp_max-cost->comp_avg),
404                   (cost->comp_avg*DeltaNormalise));
405
406   case CRITTYPE_RELDELTA+CRITICAL_COMM:
407    return SAFEDIV((cost->comm_max-cost->comm_avg),
408            (cost->comm_avg*DeltaNormalise));
409
410   case CRITTYPE_RELDELTA+CRITICAL_WAIT:
411    return SAFEDIV((cost->comp_idle_max-cost->comp_idle_avg),
412                   (cost->comp_idle_avg*DeltaNormalise));
413
414   case CRITTYPE_RELDELTA+CRITICAL_HREL:
415     return SAFEDIV(((double) (cost->hrel_max - cost->hrel_avg)),
416                    ((double) (cost->hrel_avg*DeltaNormalise)));
417
418   case CRITTYPE_WEIGHTDELTA+CRITICAL_COMP:
419    return (SAFEDIV((cost->comp_max-cost->comp_avg),
420                    (cost->comp_avg*DeltaNormalise))*
421            SAFEDIV(cost->comp_max,this_total_comp_max));
422
423   case CRITTYPE_WEIGHTDELTA+CRITICAL_COMM:
424    return (SAFEDIV((cost->comm_max-cost->comm_avg),
425                    (cost->comm_avg*DeltaNormalise))*
426            SAFEDIV(cost->comm_max,this_total_comm_max));
427
428   case CRITTYPE_WEIGHTDELTA+CRITICAL_WAIT:
429    return (SAFEDIV((cost->comp_idle_max-cost->comp_idle_avg),
430                    (cost->comp_idle_avg*DeltaNormalise))*
431            SAFEDIV(cost->comp_idle_max,this_total_comp_idle_max));
432
433   case CRITTYPE_WEIGHTDELTA+CRITICAL_HREL:
434     return (SAFEDIV(((double) (cost->hrel_max - cost->hrel_avg)),
435                     ((double) (cost->hrel_avg*DeltaNormalise)))*
436             SAFEDIV(((double) cost->hrel_max),((double)this_hrel_max)));
437
438   }
439   return 0.0;
440 }
441
442 int percentToColour(double colour) {
443   int range=255,base=0;
444
445   if (!Colour) {
446     base =100;
447     range=155;
448   }
449   if      (colour>1.0) return (base+range);
450   else if (colour<0.0) return base;
451   else return (((int) (((double)range)*colour))+base);
452 }
453
454 /* -----------------------------------------------------------------------------
455  * Recursively draw the graph
456  * -------------------------------------------------------------------------- */
457
458 static void recur_graphToDaVinci(int node,Matrix *graph,Matrix *costs,char* p_zeronodes, int mode){
459   object_cost *ptr;
460   int i,j,no_children=0,*children=NULL,colour;
461   char *node_str;
462   char tempnode[MAX_FUNNAME];
463   if (Mat(int,*graph,node,node)<0) {
464     printf("r(\"%d\") ",node);
465   } else {
466     for(i=0;i<graph->cols;i++) 
467       if (node!=i && Mat_dense(*graph,node,i)) no_children++;
468   
469     if (no_children>0) {
470       children = calloc(no_children,sizeof(int));
471       if (children==NULL) {
472         fprintf(stderr,"{printDaVinci} unable to allocate %d ",no_children);
473         exit(1);
474       }
475       for((i=0,j=0);i<graph->cols;i++)
476         if (node!=i && Mat_dense(*graph,node,i)) children[j++]=i;
477
478       qsort(children,no_children,sizeof(int),
479             (int (*)(const void *,const void *)) cmp_symbol_entry);
480     }
481     ptr = &Mat(object_cost,*costs,node,0);
482     node_str=(NodeviewCompress)?
483                 printCompressNode(node,ptr):
484                 printUncompressNode(node,ptr);
485     printf("l(\"%d\",n(\"\",[a(\"OBJECT\",\"%s\"),",node,node_str);
486     printf("a(\"FONTFAMILY\",\"courier\"),");
487       
488
489       // hide the CAF:REPOSITORY as default
490       if (!strncmp(node_str,"Cost centre: CAF:REPOSITORY",26))
491          printf("a(\"HIDDEN\",\"true\"),"); // when uncompressed
492       if (!strncmp(node_str," CAF:REPOSITORY",12)) 
493          printf("a(\"HIDDEN\",\"true\"),"); // when compressed
494
495
496       if (mode==2)
497       {
498         if ((ptr->comm_max+ptr->comp_idle_max+ptr->comp_max) <= 0.0)
499             printf("a(\"HIDDEN\",\"true\"),");
500       }  
501       //for pruning all zero-cost nodes
502       if (mode==1)
503       {
504       if ((ptr->comm_max+ptr->comp_idle_max+ptr->comp_max) <= 0.0)
505           { fprintf(logFile,"Node %d %s is a candidate for deletion\n",node, node_str);
506             sprintf(tempnode,"\"%d\",",node);
507             strcat(p_zeronodes,tempnode);
508           }
509       } 
510
511     colour=percentToColour(1.0-nodeColour(ptr));
512        printf("a(\"COLOR\",\"#ff%.2x%.2x\")",colour,colour);
513     printf("],[");
514     Mat(int,*graph,node,node)=-1;
515     for(i=0;i<no_children;i++) {
516
517       printf("e(\"%d->%d\",[],",node,children[i]);
518  
519       recur_graphToDaVinci(children[i],graph,costs,p_zeronodes,mode);
520       printf(")");
521       if (i<(no_children-1)) {printf(",");}
522     } 
523     printf("]))");
524   } 
525 }
526
527
528
529 static void recur_graphToDaVinci_old(int node,Matrix *graph, Matrix *costs) {
530   object_cost *ptr;
531   int i,j,no_children=0,*children=NULL,colour;
532   char *node_str;
533   if (Mat(int,*graph,node,node)<0) {
534     fprintf(logFile,"r(\"%d\") ",node);
535     printf("r(\"%d\") ",node);
536   } else {
537     for(i=0;i<graph->cols;i++) 
538       if (node!=i && Mat_dense(*graph,node,i)) no_children++;
539   
540     if (no_children>0) {
541       children = calloc(no_children,sizeof(int));
542       if (children==NULL) {
543         fprintf(stderr,"{printDaVinci} unable to allocate %d ",no_children);
544         exit(1);
545       }
546       for((i=0,j=0);i<graph->cols;i++)
547         if (node!=i && Mat_dense(*graph,node,i)) children[j++]=i;
548
549       qsort(children,no_children,sizeof(int),
550             (int (*)(const void *,const void *)) cmp_symbol_entry);
551     }
552     ptr = &Mat(object_cost,*costs,node,0);
553     node_str=(NodeviewCompress)?
554                 printCompressNode(node,ptr):
555                 printUncompressNode(node,ptr);
556     fprintf(logFile,"l(\"%d\",n(\"\",[a(\"OBJECT\",\"%s\"),",node,node_str);
557     printf("l(\"%d\",n(\"\",[a(\"OBJECT\",\"%s\"),",node,node_str);
558     fprintf(logFile,"a(\"FONTFAMILY\",\"courier\"),");
559     printf("a(\"FONTFAMILY\",\"courier\"),");
560     if (symbol_table[node].type==CG_SSTEP)
561       printf("a(\"BORDER\",\"double\"),");
562     else 
563       //if (prune subgraphs of zero cost node)
564                                                             // minNodeSize hardwired
565       if ((ptr->comm_max+ptr->comp_idle_max+ptr->comp_max) < minNodeSize)
566           printf("a(\"HIDDEN\",\"true\"),");
567         
568       //if ((ptr->comm_max+ptr->comp_idle_max+ptr->comp_max) < 0.01) 
569       //    small=1; 
570       //else small=0;
571  
572
573     colour=percentToColour(1.0-nodeColour(ptr));
574     //if (!small) 
575        fprintf(logFile,"a(\"COLOR\",\"#ff%.2x%.2x\")",colour,colour);
576        printf("a(\"COLOR\",\"#ff%.2x%.2x\")",colour,colour);
577     //else 
578     //   printf("a(\"COLOR\",\"yellow\"),"); 
579     fprintf(logFile,"],[");
580     printf("],[");
581     Mat(int,*graph,node,node)=-1;
582     for(i=0;i<no_children;i++) {
583
584       //if (!small) 
585            fprintf(logFile,"e(\"%d->%d\",[],",node,children[i]);
586            printf("e(\"%d->%d\",[],",node,children[i]);
587       //else 
588       //     printf("e(\"%d->%d\",[a(\"EDGECOLOR\",\"yellow\")],",node,children[i]);
589  
590       recur_graphToDaVinci_old(children[i],graph,costs);
591       fprintf(logFile,")");
592       printf(")");
593       if (i<(no_children-1)) {fprintf(logFile,","); printf(",");}
594     } 
595     fprintf(logFile,"]))");
596     printf("]))");
597   } 
598 }
599
600
601 /* -----------------------------------------------------------------------------
602  * Update colour
603  * -------------------------------------------------------------------------- */
604
605 void updateColours(int root, Matrix *graph, Matrix *costs) {
606   int i,colour,last;
607
608   printf("graph(change_attr([");
609   for(last=costs->rows-1;last>=0;last--)
610     if (Mat_dense(*graph,last,last)) break;
611
612   for(i=0;i<costs->rows;i++) {
613     if (Mat_dense(*graph,i,i)) {
614       colour = percentToColour(1.0-nodeColour(&Mat(object_cost,*costs,i,0)));
615       printf("node(\"%d\",[a(\"COLOR\",\"#ff%.2x%.2x\")])",
616              i,colour,colour);
617       if (i<last) printf(",");    
618     }
619   }
620   printf("]))\n");
621 }
622
623 /* -----------------------------------------------------------------------------
624  * Parse answer from daVinci
625  * -------------------------------------------------------------------------- */
626
627 davinciCmd parseDaVinciCmd(char *input) {
628   davinciCmd result;
629   char *crp;
630   char *word;
631   int i;
632   
633   result.size=1;
634   result.list=NULL;
635   for(crp=input;*crp;crp++)
636     if (*crp==',') result.size++;
637
638   crp=input;
639   word = parse_word(&crp);
640   if (Verbose) fprintf(logFile,"{parseDaVinciCmd}=%s size=%d\n",word,result.size);
641   if        (strcmp(word,"node_selections_labels")==0) {
642     result.type=DAVINCI_NODE;
643     result.list =calloc(result.size,sizeof(char*));
644     if (result.list==NULL) {
645       fprintf(stderr,"{parseDaVinciCmd} failed to allocate storage");
646       exit(1);
647     }
648     crp+=2;
649     i=0;
650     word = parse_quoted(&crp);
651     result.list[i++] = dup_str(word);
652     while (*crp++==',') {
653       word = parse_quoted(&crp);
654       result.list[i++] = dup_str(word);
655     }
656   } else if (strcmp(word,"icon_selection")==0) {
657     result.type=DAVINCI_ICON;
658     result.list =calloc(result.size,sizeof(char*));
659     if (result.list==NULL) {
660       fprintf(stderr,"{parseDaVinciCmd} failed to allocate storage");
661       exit(1);
662     }
663     crp++;
664     i=0;
665     word = parse_quoted(&crp);
666     result.list[i++] = dup_str(word);
667   } else if (strcmp(word,"tcl_answer")==0) {
668     result.type=DAVINCI_TCL;
669     result.list =calloc(result.size,sizeof(char*));
670     if (result.list==NULL) {
671       fprintf(stderr,"{parseDaVinciCmd} failed to allocate storage");
672       exit(1);
673     }
674     crp++;
675     i=0;
676     word = parse_quoted(&crp);
677     result.list[i++] = dup_str(word);
678   } else if (strcmp(word,"menu_selection")==0) {
679     result.type=DAVINCI_MENU;
680     result.list =calloc(result.size,sizeof(char*));
681     if (result.list==NULL) {
682       fprintf(stderr,"{parseDaVinciCmd} failed to allocate storage");
683       exit(1);
684     }
685     crp++;
686     i=0;
687     word = parse_quoted(&crp);
688     result.list[i++] = dup_str(word);
689   }else if (strcmp(word,"node_double_click")==0) {
690     result.type=DAVINCI_OK;
691   } else if (strcmp(word,"edge_selection_labels")==0)  {
692     result.type=DAVINCI_OK;
693   } else if (strcmp(word,"ok")==0)  {
694     result.type=DAVINCI_OK;
695   } else if (strcmp(word,"quit")==0)  {
696     result.type=DAVINCI_QUIT;
697   } else {
698     result.type=DAVINCI_ERROR;
699   }
700   return result;  
701 }
702
703 /* -----------------------------------------------------------------------------
704  * Misc.
705  * -------------------------------------------------------------------------- */
706
707
708 /* Function that returns a string containing \texttt{x} spaces. */
709 static char* extra_space(int x) {
710   static char space[MAX_FUNNAME+1];
711   int i;
712
713   if (Verbose) fprintf(logFile,"Padding is %d\n",x);
714   for(i=0;(i<x)&&(i<MAX_FUNNAME);i++) space[i]=' ';
715   space[i]='\0';
716   return space;
717 }
718
719
720 static char *parse_word(char **crp) {
721   static char result[MAX_FUNNAME];
722   int i=0;
723
724   while(islower(**crp) || **crp=='_') {
725     result[i++]=**crp;
726     (*crp)++;
727   }
728   result[i]='\0';
729   return result;
730 }
731
732 static char *parse_quoted(char **crp) {
733   static char result[MAX_FUNNAME];
734   int i=0;
735   if (**crp=='\"') {
736     (*crp)++;
737     while (**crp != '\"') {
738       result[i++]=**crp;
739       (*crp)++;
740     }
741     (*crp)++;
742   }
743   result[i]='\0';
744   return result;
745 }
746
747 static char *dup_str(char *xs) {
748   char *result;
749
750   if (xs==NULL) return NULL;
751   else {
752     result = malloc(strlen(xs)+1);
753     if (result==NULL) {
754       fprintf(stderr,"{dup_str}: unable to allocate bytes");
755       exit(1);
756     }
757     strcpy(result,xs);
758     return result;
759   }
760 }