function [signal t]= ReadECG(filename)
%   [signal t] = ReadECG(filename)
%   
%   This function reads an ECG record from the DICARDIA database. It opens
%   the desired file and stores the 8 ECG derivations in the independent
%   variable 'signal'. The function also returns a time vector 't' that is
%   used to plot the signals.
%
%   Input:
%
%   'filename' is a sring containing the full path to the ECG record that
%   will be read
%
%   Output:
%
%   'signal' is an array of doubles containing 8 rows that correspond to
%   the ECG derivations contained in the file. The rows contain the DI,
%   DII, V1, V2, V3, V4, V5 and V6 derivations respectively. These signals
%   have a 500Hz sampling frequency
%
%   't' is a time axis that is coherent with the signals. It may be used to
%   plot the signals having a time reference.
%
%   This routine was developed by the Simon Bolivar University's Applied
%   Biophysics and Bioengineering Group (GBBA-USB) for free and public use. 
%   It is protected under the terms of the Creative Commons Attribution-Non
%   Commercial 4.0 International License, no profit may come from any 
%   application that uses this function and proper credit must be given to 
%   the GBBA-USB. For further information consult 
%   http://creativecommons.org/licenses/by-nc/4.0/

freq = 500;
ConversionResolution = 3.06e-3;
NumberBits = 12;

ders= 1:8;
fid = fopen(filename,'r');
A = fread(fid,'short');

for i=1:8
    x = [A(i:8:end)];
    signal(i,:) = x(5000:end);
end

t = 0:1/freq:(length(signal)-1)/freq;