%
%  select a template from an eeg signal
%
function template = select_eeg_template(name);
%
%  the sampling rate is 100 Hz
%
  fs = 100;
%
%  load the data file
%
  s = load(name);
%
%  for now, format the data
%
  temp = s';
  data = temp(:);
%
%  get the entire data segment
%
  N = length(data);
  time = [0:N-1]/fs;
%
%
  lefti = floor(N/2-100);
  righti = floor(N/2+100);
  template = data(lefti:righti);
  left = lefti*1000/fs;
  right = righti*1000/fs;
%  
  subplot(2,1,1);  
  hold on 
  plot(time*1000,data,'-');
  plot(time(lefti:righti)*1000,data(lefti:righti),'Linewidth',3);
  hold off
  grid; xlabel('Time (ms)'); axis('tight');
  title(['Using File ' name '      Template :  from ', num2str(left) ' ms, to  ' num2str(right) ' ms ']);
  subplot(2,1,2); plot(time(lefti:righti)*1000,data(lefti:righti),'Linewidth',3);
  grid; xlabel('Time (ms)'); axis('tight');
  title(['Template :  from ', num2str(left) ' ms, to  ' num2str(right) ' ms ']);
%
%  now determine a tempate
%
  ans = input('\n Is the current tempate acceptable ?  (y/n) ' ,'s');
% 
  while((ans == 'n') || (ans == 'n'))
    sleft = input('Left edge of template(in ms) ','s');
    sright = input('Right edge of template (in ms)','s');
    left = str2num(sleft);
    right = str2num(sright);  
    lefti = floor((left/1000)*fs);
    righti = floor((right/1000)*fs);
    template = data(lefti:righti);
 %
    cla reset
    subplot(2,1,1); 
    cla reset
    hold on
    plot(time*1000,data,'-');
    plot(time(lefti:righti)*1000,data(lefti:righti),'Linewidth',3);
    hold off
    axis('tight');
    grid; xlabel('Time (ms)');
    title(['Using File ' name '      Template :  from ', num2str(left) ' ms, to  ' num2str(right) ' ms ']);
    subplot(2,1,2); plot(time(lefti:righti)*1000,data(lefti:righti),'Linewidth',3);
    grid; xlabel('Time (ms)'); axis('tight');
    title(['Template :  from ', num2str(left) ' ms, to  ' num2str(right) ' ms ']);
 %
    ans = input('\n Is the current tempate acceptable ?  (y/n) ' ,'s');
  end
