function [header2] = readcortex_header(filename) % READCORTEX_HEADER reads a Cortex data file and returns the header (if % present) written by the write_header() function in the timing file % % NOTE: Only checks the first trial for header information - does not check % any other trials! % % [header] = READCORTEX_HEADER(filename) % Matthew A. Smith % Revised: 20050720 MAXNUMTRIALS = 1000; fid = fopen(filename, 'r','ieee-le'); if (fid == -1) error(['Cannot open file: ',filename]); end time_arr = zeros(1, MAXNUMTRIALS); % array of time_code arrays event_arr = zeros(1, MAXNUMTRIALS); % array of event_code arrays header2 = []; hd=zeros(1,13); % a single header (read every trial) flength = fread(fid, 1, 'unsigned short'); if (isempty(flength)~=1) hd(1,1:8)= (fread(fid, 8, 'unsigned short'))'; hd(1,9:10) = (fread(fid, 2, 'unsigned char'))'; hd(1,11:13)= (fread(fid, 3, 'unsigned short'))'; hd(1,5)=hd(1,5)/4; % reduce the size of the time_code array hd(1,6)=hd(1,6)/2; % idem for event_code array if (sum(floor(hd) - hd) ~= 0) error('READCORTEX: Header data contains non-integers, endian needs to be changed'); end % read the time codes and event_codes for this trial time_arr(1:(hd(1,5)),1) = (fread (fid,(hd(1,5)) , 'unsigned long')); event_arr(1:(hd(1,6)),1) = (fread (fid,(hd(1,6)), 'unsigned short')); end fclose(fid); %%%%% decode the special write_header() info %%%%% first_trial = event_arr(:,1); i = find (first_trial < 256); if (~isempty(i) && (first_trial(1) == 65535)) % If the first code sent is 65535, that's a marker % to indicate there is write_header() data t = first_trial(1:min(i)-1); for I=1:length(t) t2(2*I) = floor(t(I)/256); t2(2*I-1) = mod(t(I),256); end % add a trailing 255 if necessary to help with parsing the header if (t2(length(t2)) ~= 255) t2(length(t2)+1) = 255; end % 255 is used to space out the data in the header j = find(t2 == 255); % if the header starts with 3 255's, cut it down to 2. if (sum(t2(1:3)) == 765) j(1) = []; end % Get the required header data header2.data_file = char(t2(j(2)+1:j(3)-1)); header2.cnd_file = char(t2(j(3)+1:j(4)-1)); header2.ext_file = char(t2(j(4)+1:j(5)-1)); header2.item_file = char(t2(j(5)+1:j(6)-1)); header2.css_file = char(t2(j(6)+1:j(7)-1)); header2.xdim = char(t2(j(7)+1:j(8)-1)); header2.ydim = char(t2(j(8)+1:j(9)-1)); header2.fps = char(t2(j(9)+1:j(10)-1)); header2.hpix = char(t2(j(10)+1:j(11)-1)); header2.vpix = char(t2(j(11)+1:j(12)-1)); header2.bpp = char(t2(j(12)+1:j(13)-1)); % Get the extern header data (if it's present) num_externs = ceil((length(j) - 13 - 1)/2); if (num_externs > 0) header2.ext_name = cell(num_externs,1); header2.ext_val = cell(num_externs,1); for I=1:(num_externs*2) if (mod(I,2) == 1) namestart = j(13+I-1)+1; namestop = j(13+I)-1; header2.ext_name{floor(I/2)+1} = char(t2(namestart:namestop)); end if (mod(I,2) == 0) valstart = j(13+I-1)+1; valstop = j(13+I)-1; header2.ext_val{I/2} = char(t2(valstart:valstop)); end end end end