function edit_codes = read_edc(fname, fhdr, chdr)
% read_edc.m  -- reads an edit codes file
%
% Modification history:
% 7/7/95		Written by Petr Janata
%

ses_hdr_offsets_v;

fid = fopen(fname);

disp(['Reading edit codes file <' fname '>']);
done = 0; lines_read = 0; current_cell = 1; last_trial_done = 0;

edit_codes = ones(sum(chdr(:,NTrials)), fhdr(NChan));

while done == 0 
  theline = fgetl(fid);
  if theline == -1
    done = 1;
	disp(['Finished reading edit codes file (' int2str(lines_read) ' lines)']);
  else
    theline = sscanf(theline, '%d');
  	nelem = length(theline);
	thecell = theline(1); thetrial = theline(2);
	if (thecell <= 0) | (thecell > fhdr(NCells))
	  error(['Invalid cell (' int2str(thecell) ') specified']);
	elseif (thetrial > chdr(thecell, NTrials))
	  error(['Invalid trial number (' int2str(thetrial) ') for cell ' int2str(thecell) ]);
	else
	  trial_offset = sum(chdr(1:current_cell, NTrials)) - chdr(current_cell, NTrials) + thetrial;
	  if (theline(3) >= 2)
	    edit_codes(trial_offset, :) = zeros(1, size(edit_codes,2));
	  end
	  if (nelem > 3) & (theline(3) == 1)
	    for i = 4:nelem
		  if (theline(i) < 0) | (theline(i) > fhdr(NChan))
		    disp(['Abnormality in line ' int2str(lines_read + 1) ' of edit codes file']);
		  elseif theline(i) ~= 0
		    edit_codes(trial_offset, theline(i)) = 0;
	      end
		end
	  end
	end
	last_trial_done = last_trial_done + 1;
    if (last_trial_done >= chdr(current_cell, NTrials))
	  current_cell = current_cell + 1; last_trial_done = 0;
	end
    lines_read = lines_read + 1;
  end
end

fclose(fid);
