function T = ticks2time(t, tempo, tpqn)
   // Convert MIDI time in ticks to real time in seconds
   //
   // Usage:
   //       T = ticks2time(t, tempo)
   // where
   //       t:     Vector containing MIDI times in ticks
   //       tempo: Tempo matrix
   //       tpqn:  ticks per quarter note
   //       T:     Vector containing real times in seconds
   //
   // This function is useful to play a MIDI file. It 
   // allows either sporadic tempo information or denser
   // than note events, which could be necessary when
   // using some expression resources such as aftertouch.  
   //
   // Tempo matrix has at least two columns; the first
   // one contains delta-times in ticks and the second
   // one contains metronome information in microseconds
   // per quarter note
   // 
   // ------------------------------------------
   // Author: Federico Miyara
   // Date:   2012-01-05
   //         2024-09-12

   if argn(2)<2
      // If not specified, tempo is set to 120 quarter
      // notes per minute (which is equivalent to 500000
      // microseconds per quarter note
      tempo = [0, 500000];
   end

   // Convert delta-times to absolute times
   tempo(:,1) = cumsum(tempo(:,1));

   // Remove non-tempo events (i.e., time signature
   // changes) and reduce array to 2 columns 
   tempo1 = [];
   for h=1:size(tempo,1)
      if tempo(h,2)~=0
         tempo1 = [tempo1; tempo(h,1:2)];
      end
   end

   // Number of time events 
   Lt = length(t);

   // Number of tempo events
   Ltempo = size(tempo1,1);

   // A contains MIDI times of tempo events
   // If events go further from tempo events, add a 
   // last tempo event 
   A = tempo1(:,1);
   if A($)<t($)
      A = [A; t($)];
   end

   // B contains real time information for each tempo
   // event
   B(1) = 0;
   for k=2:length(A)
      B(k) = B(k-1) + tempo1(k-1,2)/tpqn/1e6 * (A(k) - A(k-1)); 
   end

   // Real time corresponding to MIDI time events are
   // computed by linear interpolation.
   if length(A)==1
      T = tempo1(1,2)/tpqn/1e6*t;
   else
      T = interp1(A,B,t);
   end

endfunction



