%
%  this program selects a template
%
%  trigger is an array of trigger points, indices into an array
%  beat is the intial beat to use (starting from 2)
%  lefti is the number of samples from the trigger for the left edge of the
%  beat, righti is the number of sample from the trigger for the right edge
%
function [template lefti righti] = select_template(trigger,beat,name);
%
  s = load(name);
%
%  for now, format the data
%
  temp = s';
  data = s;
  N = length(data);
%
%  display the intial beat, over a window of about 500 ms
%
  fs = 125; % sample rate = 125 Hz
  fs = 1000; % sample rate = 1000 Hz;
  time = [0:N-1]/fs;
  left = 200;
  right = 200;
  original_low = trigger(beat)-floor(0.5*fs);
  original_high = trigger(beat)+floor(0.5*fs);
  figure
  if (original_low <= 0) 
      fprintf(1,'The time index is negative or zero, use a higher beat number \n');
      template = [];
      lefti = [];
      righti = [];
  else
    template = data(original_low:original_high);
    marker = [min(data) max(data)];
    marker_time = [time(trigger(beat)) time(trigger(beat))];
    hold on
    plot(time(original_low:original_high)*1000,data(original_low:original_high),'-','LineWidth',1);
    plot(marker_time*1000,marker,'-','LineWidth',3); axis('tight');
    grid; xlabel('Time (ms)'); 
    title(['Beat ' num2str(beat) ':  Extends to the left = ', num2str(floor(0.5*fs)) ' ms, to the right ' num2str(0.5*fs) ' ms ']);
    axis('tight');
    hold off
    %
    %  now determine a tempate
    %
    ans = input('\n Is the current tempate acceptable ?  (y/n) ' ,'s');
   % 
    while((ans == 'n') || (ans == 'n'))
        sleft = input('Enter extent of beat to left of centerline (in ms) ','s');
        sright = input('Enter extent of beat to right of centerline (in ms)','s');
        left = str2num(sleft);
        right = str2num(sright);  
        lefti = floor((left/1000)*fs);
        righti = floor((right/1000)*fs);
        index_low = trigger(beat)-lefti;
        index_high = trigger(beat)+righti;
        template = data(index_low:index_high);
        marker = [min(data) max(data)];
        marker_time = [time(trigger(beat)) time(trigger(beat))];
        cla reset
        hold on
        plot(time(original_low:original_high)*1000,data(original_low:original_high),'-','LineWidth',1);
        plot(time(index_low:index_high)*1000,data(index_low:index_high),'-','LineWidth',3);
        plot(marker_time*1000,marker,':','LineWidth',3); axis('tight');
        grid; xlabel('Time (ms)');
        title(['Beat ' num2str(beat) ':  Extends to the left = ', num2str(left) ' ms, to the right ' num2str(right) ' ms ']);
        hold off
        ans = input('\n Is the current tempate acceptable ?  (y/n) ' ,'s');
    end
  end