function varargout=rdmat(varargin)
%
% [tm,signal,Fs,siginfo]=rdmat(recordName)
%
%    Function based on plotATM for reading files generated by WFDB2MAT:
%         http://physionet.org/physiotools/matlab/plotATM.m
%
%
% Import a signal in physical units from *.mat file generated by WFDB2MAT.
%
% The original plotATM.m was written by O. Abdala and James Hislop.
% This script modifies that code for the purposes of only loading the
% signals into MATLAB's workspace (ie, no plotting is done).
%
%
% Required Parameters:
%
% recorName
%       String specifying the name of the *.mat file.
%
% Outputs are:
%
% tm
%       A Nx1 array of doubles specifying the time in seconds.
% signal
%       A NxM matrix of doubles contain the signals in physical units.
% Fs
%       A 1x1 integer specifying the sampling frequency in Hz.
%
%siginfo
%       A LxN cell array specify the signal siginfo.
%
% NOTE:
%       You can use the WFDB2MAT command in order to convert the record data into a *.mat file,
%       which can then be loaded into MATLAB/Octave's workspace using the LOAD command.
%       This sequence of procedures is quicker (by several orders of magnitude) than calling RDSAMP.
%       This will load the signal data in raw units (use RDMAT to load the signal in physical units).
%
%
% Modified by Ikaro Silva, 2014
% Last Modified: September 15, 2014
% Version 0.1
%
% Since 0.9.7
%
% %Example:
% wfdb2mat('mitdb/200')
%tic;[tm,signal,Fs,siginfo]=rdmat('200m');toc
%tic;[tm2,signal2]=rdsamp('200m');toc
% sum(abs(signal-signal2))
%
%
% See also RDSAMP, RDMAT

%endOfHelp

%Set default pararameter values
inputs={'recordName'};
for n=1:nargin
    if(~isempty(varargin{n}))
        eval([inputs{n} '=varargin{n};'])
    end
end

outputs={'tm','val','Fs','siginfo'};
matName = strcat(recordName, '.mat');
load(matName);
[siginfo,Fs]=wfdbdesc(recordName);

val(val==-32768) = NaN;
for i = 1:size(val, 1)
    %Parse siginfo assuming signal gain is the first number and ignore Physical unit strings 
    %following the gain
    gain=regexp(siginfo(i).Gain,' ', 'split');
    val(i, :) = (val(i, :) - siginfo(i).Baseline ) / str2num(gain{1});
end

val=val'; %Reshape to the Toolbox's standard format
tm = (1:size(val, 2))./Fs(1);


for n=1:nargout
    eval(['varargout{n}=' outputs{n} ';'])
end


end
