% Written by Daniel Shima, Vanderbilt Vision Research Center, 9 August 2002.
% Added fix to first for loop to check for necessary length(Zdouble) on 13 July 2004.

function [ViewPointdatamatrix] = ViewPointchar2double(Zserialreadstring)

% Convert serial data from char array to double array.
Zdouble = double(Zserialreadstring);

% Find all 86 values which is the double('V') and possibly the beginning of a ViewPoint serial data header.
Zdelim = find(Zdouble == 86);

% For each 86, check if it is in fact the beginning of a true (86)(80)(10)(16) ViewPoint header for serial eye data.
j = 1;
for i = 1:length(Zdelim)
	if (length(Zdouble) >= Zdelim(i) + 4)
		if (Zdouble(Zdelim(i) + 1) == 80 & Zdouble(Zdelim(i) + 2) == 10 & Zdouble(Zdelim(i) + 3) == 16)
			Zcoordindex(j) = Zdelim(i) + 4;
			j = j + 1;
		end
	end
end

% Check that a full 16 bytes follows last ViewPoint header found, otherwsie eliminate last header found.
if (length(Zdouble)-Zcoordindex(length(Zcoordindex)) < 16)
	Zcoordindex = Zcoordindex(1:length(Zcoordindex) - 1);
end

% Knowing that each is a 16-bit integer, calculate xpos, ypos, and dt and write values to three columns of output matrix.
for i = 1:length(Zcoordindex)
	ViewPointdatamatrix(i,1:3) = [Zdouble(Zcoordindex(i))*256+Zdouble(Zcoordindex(i)+1) Zdouble(Zcoordindex(i)+2)*256+Zdouble(Zcoordindex(i)+3) Zdouble(Zcoordindex(i)+4)*256+Zdouble(Zcoordindex(i)+5)];
end
