#!/bin/sh 
#
#  Little script to plot memory usage within ML. Normally, users should
#  compile ML with -DML_MEMORY_CHECK
#  To use it do the following:
#
#     memory_graph output_file > matscript.m
#
#  Then run matscript.m from within matlab.
#
#  Note: if you want some other field plotted, you can just
#        edit this file and change 'FIELD=used' to something
#        else like 'FIELD=time'.
#
FIELD=used
grep "  $FIELD  " $1 > afile

total=`wc afile | sed "s/^ *\([^ ]*\) .*$/\1/"`
grep "  total   " $1 | head -1 | sed "s/^ *total  *\([^ ]*\) *\([^ ]*\) *\([^ ]*\) *\(.*$\)/totalline = \1*ones($total,1);/" 

echo "memlabels = '  ';"
echo "memavg = zeros($total,1);"
echo "memmin = zeros($total,1);"
echo "memmax = zeros($total,1);"
echo "i = 1;"

cat afile | sed "s/^ *$FIELD  *\([^ ]*\) *\([^ ]*\) *\([^ ]*\) *\(.*$\)/memavg(i) = \1; memmin(i) = \2; memmax(i) = \3;\\ntemp = \'\4\'; memlabels(i,1:length(temp)) = temp; i= i + 1;/"


echo "newfigure = input('Is this a new figure (yes = 1, no != 1) ');"
echo "want_total = 0;"
echo "if (newfigure == 1)"
echo "   maxvalues = -1;"
echo "   want_total = input('Display total memory line (yes = 1, no != 1) ');"
echo "sss = sprintf('%s',memlabels(1,:));"
echo "for i=1:size(memlabels,1)-1"
echo "   sss = sprintf('%s | %s',sss,memlabels(i+1,:));"
echo "end;"
echo "y=(1:length(memavg));"
echo "h = axes;"
echo "set(h,'YTick',y);"
echo "set(h,'YTickLabel',sss);"
echo "set(h,'xTicklabel',[]);"
echo "set(h,'YDir','reverse');"
echo "set(h,'XAxisLocation','top');"
echo "set(h,'YGrid','on');"
echo "hold on"
echo "end"
echo "plot(memavg,y,'r-',memavg,y,'ro');"
echo "plot(memmax,y,'g-',memmax,y,'go');"
echo "plot(memmin,y,'-',memmin,y,'o');"
echo "tmax = max(memmax);"
echo "if (want_total == 1)"
echo "   plot(totalline,y, 'b');"
echo "   tmax = max(totalline);"
echo "end"
echo "if (tmax > maxvalues)"
echo "   maxvalues = tmax;"
echo "   axis([0 maxvalues 0 length(memavg)+1])"
echo "end"
echo "fprintf(1,'To print, do the following:\\n');"
echo "fprintf(1,'   1) run m-file\\n');"
echo "fprintf(1,'   2) select Print Preview\\n');"
echo "fprintf(1,'   3) now select Page Setup\\n');"
echo "fprintf(1,'   4) select color\\n');"
echo "fprintf(1,'   5) select landscape if plot is wider than shorter\\n');"
echo "fprintf(1,'   6) select fill page\\n');"
echo "%fprintf(1,'   4) select manual size with\\n');"
echo "%fprintf(1,'      top 1., left 1., width 10., height 7\\n');"
echo "fprintf(1,'   5) select landscape');"
