#! /usr/bin/octave -qf
#      ITGPlot
# 
#      copyright       : (C) 2004-2006 by Stefano Avallone, Alessio Botta, Alberto Dainotti
#                                          Donato Emma, Antonio Pescape'
#      email:          : stavallo@unina.it , a.botta@unina.it , alberto@unina.it
#                        doemma@unina.it , pescape@unina.it
# 
#      This program is free software; you can redistribute it and/or modify
#      it under the terms of the GNU General Public License as published by
#      the Free Software Foundation; either version 2 of the License, or
#      (at your option) any later version.

# Check the octave version
ver=version;
octave3 = str2num(ver(1))>=3;

graphicformat="epsc2";
extension="eps";

arg_list = argv ();

if nargin>0
   inputf=arg_list{1};
else
   printf("%s\n","Input file name missing, exiting...");
   return;
endif

if (f=fopen(inputf,"r"))<0
   printf("%s%s%s\n","File ",inputf," does not exist, exiting...");
   return;
endif

if size(s=getenv("DITG_PLOT_TITLE"))
   title(s);
endif

# read labels
labels=blanks(0);
fscanf(f,"%s",1);    # we do not need the first string (Time)
while !strcmp(s=fscanf(f,"%s",1),"Aggregate-Flow")
labels=[labels; strcat("-@;",s,";") ];
endwhile
labels=[labels; strcat("-@;",s,";") ];    # add the last string (Aggregate-Flow)

if nargin>1
   mask=intersection(str2num(arg_list{2}),1:size(labels,1));
else
   mask=1:size(labels,1);
endif

if !size(mask)
   printf("%s\n","No flow selected to be plotted");
   return;
endif

# read data 
data=fscanf(f,"%f",[size(labels,1)+1,Inf])';

temp=split(strrep(inputf,"\\","/"),"/");
outputf=split(deblank(temp(size(temp,1),:)),".");
ylbl=outputf(1,:);

ylbl(1,1)=toupper(ylbl(1,1));
ylabel(ylbl);
xlabel("Time (s)");

plot(data(:,1), data(:,mask+1), labels(mask,:));

# Only for Octave 3.0
if octave3
   nlabels=blanks(0);
   for i=1:size(labels,1)
      nlabels=[nlabels; labels(i,:)(strfind(labels(i,:),";")(1)+1:strfind(labels(i,:),";")(2)-1)];
   endfor
   legend(nlabels(mask,:),"location","southoutside");
   legend("boxon");
endif

eval(strcat("print -d",graphicformat," ",ylbl,".",extension));

printf("%s\n","Done!");
