function cd2hr(fileuse)
%CD2HR(fileuse)
%
%  fileuse ('choosenew'): whether to choose a new file set or use an old one
%
%Examples:
%  cd2hr
%  cd2hr('useold');

if (nargin==0)
  fileuse = 'choosenew';
end %if

[ecgfilename, cdfilename, rrfilename, hrfilename, ecgfilenameonly] = chooser(fileuse);
hrdt = 500; INVTIMEBASIS = 1000;
%used to read the checked data
cdread = 0; cdtims = 0; cdbeat = 0;
%used to calculate rr intervals
recentrt = 0; rrcount = -1;
%used to analyze rr intervals
avgrrint = 0;
%used to calculate the heart rate
i = 0; prevrr = 0; rtoffset = hrdt;
%file ids
cdfid = fopen(cdfilename,'r');
rrfid = fopen(rrfilename,'w');
hrfid = fopen(hrfilename,'w');
fs = fscanf(cdfid,'%f',[1 1]);
fprintf(rrfid, '%5g\n', fs);
fprintf(hrfid, '%5g\n', fs);
while (~feof(cdfid))
  %reading and analyzing the ecg
  cdread = fscanf(cdfid,'%f %f',[1 2]);
  if (isempty(cdread)) break; end %if
  cdtims = (round(cdread(1)*fs)/fs)*INVTIMEBASIS; cdbeat = cdread(2);
  temprrint = cdtims - recentrt;
  if (cdbeat ~= 0)
   %a new heartbeat has been found
    rrcount = rrcount + 1;
    if (rrcount == 1) prevrr = temprrint; end %if
    if (rrcount > 0)
      avgrrint = avgrrint + (temprrint-avgrrint)/rrcount;
      fprintf(rrfid, '%10g %10g\n', cdtims, temprrint);
      for i=(recentrt-rtoffset+hrdt:hrdt:cdtims)
        fprintf(hrfid, '%10g %10g\n', i, INVTIMEBASIS/temprrint+...
          (i<=recentrt+hrdt)*(INVTIMEBASIS/prevrr-INVTIMEBASIS/temprrint)/2);
      end %for
      rtoffset = mod(cdtims-recentrt+rtoffset-hrdt,hrdt);
    end %if
    prevrr = temprrint;
    recentrt = cdtims;
  end %if
end %while

fclose(cdfid);
fclose(hrfid);
fclose(rrfid);