
function [data_raw, data_prep, fs] = read_ecg_id(data_dir, person, recording)

    % INPUT
    % data_dir  - path where 'ecg-id-database-1.0.0' folder is located (char)
    % person    - person folder (int/double)
    % recording - recording within the person folder (int/double)
    
    % OUTPUT
    % data_raw  - raw ECG
    % data_prep - preprocessed ECG
    % fs        - sampling rate
    
    fid = fopen(sprintf('%s/ecg-id-database-1.0.0/Person_%02d/rec_%d.dat', data_dir, person, recording), 'r');
    
    try
        data = fread(fid,[2 inf],'int16');
    catch
        error('File could not be read! Probably the path is incorrect or the recording does not exist')
    end
    
    data_raw = data(1, :);
    data_prep = data(2, :);

    % Reading the sampling rate from the README file 
    readme = importfile(sprintf('%s/ecg-id-database-1.0.0/README', data_dir), [15,15]);
    nums = regexp(readme,'\d*','Match');
    fs = str2double(nums(1));

    function README = importfile(filename, dataLines)

        %IMPORTFILE Import data from a text file
        %  README = IMPORTFILE(FILENAME) reads data from text file FILENAME for
        %  the default selection.  Returns the data as a string array.
        %
        %  README = IMPORTFILE(FILE, DATALINES) reads data for the specified row
        %  interval(s) of text file FILENAME. Specify DATALINES as a positive
        %  scalar integer or a N-by-2 array of positive scalar integers for
        %  dis-contiguous row intervals.
        %
        %  Example:
        %  README = importfile("/home/max/Downloads/ecg-id-database-1.0.0/README", [15, 15]);
        %
        %  See also READMATRIX.
        %
        % Auto-generated by MATLAB on 09-Apr-2021 12:53:57

        %% Input handling

        % If dataLines is not specified, define defaults
        if nargin < 2
            dataLines = [15, Inf];
        end

        %% Set up the Import Options and import the data
        opts = delimitedTextImportOptions("NumVariables", 1);

        % Specify range and delimiter
        opts.DataLines = dataLines;
        opts.Delimiter = ";";

        % Specify column names and types
        opts.VariableNames = "EachRecordingContain20secondIleadECGSignal";
        opts.VariableTypes = "string";

        % Specify file level properties
        opts.ExtraColumnsRule = "ignore";
        opts.EmptyLineRule = "read";

        % Specify variable properties
        opts = setvaropts(opts, "EachRecordingContain20secondIleadECGSignal", "WhitespaceRule", "preserve");
        opts = setvaropts(opts, "EachRecordingContain20secondIleadECGSignal", "EmptyFieldRule", "auto");

        % Import the data
        README = readmatrix(filename, opts);

    end

end