function [pos,time,f,n,nmrk,mrk_names,file,inpath]=load_trc(infile,inpath)
%   [pos,time,f,n,nmrk,mrk_names]=load_trc(infile)
%   LOAD_TRC is used to open a data file from Motion Analysis Realtime
%   output (*.trc).
%   
%   Inputs:
%       infile - trc file to be loaded
%                If infile is unspecified, the user is prompted to select the input file
%       inpath - directory of location where data file is located
%               when no path is specified, it defaults to current directory
%
%   Outputs:
%       pos     contains - the meaured marker positions in order of the markers
%               that is columns 1-3 are the x,y,z components of marker 1
%                       columns 4-6 are the x,y,z components of marker 2
%                          ....
%       time - column vector of time
%       f - sample frequency
%       n - number of data frames
%       nmrk - number of markers
%       mrk_names - marker names
%
%   Updated: Feb. 15, 2005 (JWF)
%   Updated: Oct. 12, 2006 (David Remy, remy@wisc.edu)
%   -> Initialized data fields for better performance
%   -> Enable handling of missing markers (position values are set to [NaN,
%      NaN, NaN] if a marker is missing).
%   -> Cleaned up structure
%   Updated: Jan, 17, 2008 (Anne Schmitz, ambaus@wisc.edu)
%   -> fixed mishandling of missing data points, the tab index was incorrect
%
%   MATLAB Version 7.1

n = nargin;
%  NARGIN Number of function input arguments.
%     Inside the body of a user-defined function, NARGIN returns
%     the number of input arguments that were used to call the
%     function.
if (n==0);
    [infile, inpath]=uigetfile('*.trc','Select input file');
    if infile==0;
        disp('No file selected');
        f = 0;
        n = 0;
        nmrk = 0;
        mrk_names = {};
        pos = [];
        time = [];
        return;
    end
    fid = fopen([inpath infile],'r');
%   FOPEN  Open file.
%     FID = FOPEN(FILENAME) opens the file FILENAME for read access.
%     FILENAME is a string containing the name of the file to be opened.  
%     (On PC systems, FOPEN opens files for binary read access.)
    file = infile(1:length(infile)-4);
elseif (n==1);
    file = infile(1:length(infile)-4);
    fid=fopen(infile,'r');
    inpath='';
else (n==1);
    file = infile(1:length(infile)-4);
    fid=fopen([inpath infile],'r');
end

if (fid==-1);
    disp('File not found');
    f = 0';
    n = 0;
    nmrk = 0;
    mrk_names = {};
    pos = [];
    time = [];
    return;
end

disp(['Loading file...' infile] );

%disregard header info (first two lines)
line=fgetl(fid);
line=fgetl(fid);

%  FGETL Read line from file, discard newline character.
%     TLINE = FGETL(FID) returns the next line of a file associated with file
%     identifier FID as a MATLAB string. The line terminator is NOT
%     included. Use FGETS to get the next line with the line terminator
%     INCLUDED. If just an end-of-file is encountered, -1 is returned.

% scan the next line for the file info:
line=fgetl(fid);
file_info=sscanf(line,'%f');
f   = file_info(1);     % data rate
n   = file_info(3);     % nr frames
nmrk= file_info(4);     % nr markers

% the next line contains the marker names:
line=fgetl(fid);
for i=1:nmrk
    name = sscanf(line,[repmat('%*s',1,i+1),' %s'],1);
    mrk_names(i,1) = cellstr(name);
end

% disregard the next two lines
line=fgetl(fid);
line=fgetl(fid);

% initialize the data variables
pos = zeros(n,3*nmrk);
time = zeros(n,1);
i=0;

while feof(fid)==0
    i=i+1;
    line=fgetl(fid);
    data=sscanf(line,'%f');
    % read time from the second column
    time(i,1)=data(2);      
    % check if the full set of markers is given
    if size(data,1)==3*nmrk+2
        % in this case, just shift and copy the data from the string to the
        % marker positions:
        pos(i,:) = data(3:end)';
    else
        % if a line misses some markers, the values of these markers are set to NaN:
        % Find the tabs (we have to do this manually)
        tabIndex = find(line==9);
        % scan the line, tab by tab
        % there are 3*mrk + 3 tabs total
        for k=1:3*nmrk
            % The first piece of data is between the third and fourth tab,
            % the second is between the fourth and fifth...
            dataPiece = sscanf(line(tabIndex(k+2):tabIndex(k+3)),'%f');
%   SSCANF Read string under format control.
%     [A,COUNT,ERRMSG,NEXTINDEX] = SSCANF(S,FORMAT,SIZE) reads data from
%     MATLAB string variable S, converts it according to the specified
%     FORMAT string, and returns it in matrix A. COUNT is an optional output
%     argument that returns the number of elements successfully read.
%     ERRMSG is an optional output argument that returns an error message
%     string if an error occurred or an empty string if an error did not
%     occur. NEXTINDEX is an optional output argument specifying one more
%     than the number of characters scanned in S.
            if isempty(dataPiece)
                % No data between these two tabs -> marker is missing.
                pos(i,k) = NaN;
            else 
                pos(i,k) = dataPiece;
            end
        end
    end
end

% Return the position data in m
pos = pos/1000;