function timeline(fn, nproc)
% Draws a timeline with the activations of processes 
%  - Inputs:  
%     fn    : file having data in the form Process_Name, Process_Index, Evt_Type, Evt_Instant{secs, usecs} 
%     nproc : number of processes 
%  - Output: 
%       - Timeline chart 
% 
% Paulo Pedreiras 
% Fev/2007, for CAMABDA 
% 
 
MAX_X=500; 
clearplot; 

% Load trace data file 
ldata=load(fn);  
 
% Convert timespec to linear time 
ei = (ldata(:,2)*1000000+ldata(:,3))/1000; 
basetime=ei(1); 
ei=ei-basetime; 
pdata = [ ldata(:,1) ei ldata(:,4)]; 
 
ldata=pdata(pdata(:,3) ~= 2,:); 
 
s_evt_data=pdata(pdata(:,3) == 2,[1 2]); 
s_evt_data=[s_evt_data(:,:) ones(length(s_evt_data),1)]; 
 
% Separate data of each process 
for n=0:1:nproc-1 
  p = ldata(ldata(:,1) == n,:); 
  s = s_evt_data(s_evt_data(:,1) == n,:); 
  nevents=length(p); 
  q = zeros(2*nevents-2,3); 
 
  for pindex=1:1:nevents-1 
    qindex=2*pindex-1; 
    q(qindex,:)=p(pindex,:); 
    qindex=qindex+1; 
    q(qindex,:)=p(pindex+1,:); 
    q(qindex,3) = p(pindex,3); 
    q(qindex,2)=q(qindex,2)-1; 
  end  
  plot(q(:,2),q(:,3)+2*n,'-',s(:,2),s(:,3)+2*n,'*'); 
  hold on; 
end 
 
 
title('Process Timeline') 

xlabel('Time (ms)') 
offset=0; 
axis([0+offset MAX_X+offset 0 2*nproc]); 

%f=gcf 
__gnuplot_set__ nokey; 
 
[fid,msg]=fopen(fn,"r","native");
glab=fgets(fid);
glab=fgets(fid);
glab=fgets(fid);
glab=["Process status " glab ];
ylabel(glab);
fclose(fid);

disp("z/x : zoom   o/p : move window left/rigth")

while(true) 
   
  % Matlab 
  % itype=waitforbuttonpress 
  % if(itype == 1) % Keyboard input 
  %      k= get(f,'CurrentCharacter') 

      k=kbhit();
    
        if(k=='o') 
            offset=offset-100; 
        end 
        if(k=='p') 
            offset=offset+100; 
        end 
         
        if(k=='x') 
            MAX_X=MAX_X-100; 
        end 
        if(k=='z') 
            MAX_X=MAX_X+100; 
        end 
         
        if(k=='q') 
            clf; 
            return; 
        end 
         
        if(offset < 0) 
                offset=0 
        end 
        if(offset+MAX_X > max(q(:,2))) 
            offset=max(q(:,2))-MAX_X; 
        end 
                 
        if(MAX_X < 200) 
                MAX_X=200 
        end 
        if(MAX_X > 5000) 
            MAX_X=5000; 
        end 
             
    %end 
    %offset 
    axis([0+offset MAX_X+offset 0 2*nproc]); 
    replot;        
end 
 
    clearplot; 
return; 
 
 
