function [time segt seg ledt led ledlut]=procrawclk(segraw,ledraw,seglut)

if(~isempty(find(segraw(:)==0, 1)))
	time=-99;
	segt=-99;
	seg=-99;
	ledt=-99;
	led=-99;
	ledlut=-99;
	return;
end

[Nled Nf]=size(ledraw); %#ok<NASGU>
[Nseg Nc Nf]=size(segraw);

numled=(conv2(reshape(permute(reshape(repmat((-1:256)',10,1),256+2,10,1),[2 1]),(256+2)*10,1),ones(10,1),'valid'))/10;
ledlut=bitxor((0:255)',fix((0:255)'/2));
ledblut=double(dec2bin(ledlut))-48;
ledblutf=(conv2(reshape(permute(reshape(repmat(ledblut([end 1:end 1],:),10,1),256+2,10,8),[2 1 3]),(256+2)*10,8),ones(10,1),'valid'))/10;

[nn bb]=hist(reshape(ledraw,8,Nf)',100);
[mx ph]=max(nn(65:end,:)); %#ok<*ASGLU>
[mx pl]=max(nn(1:30,:));
lednorm=clip((reshape(ledraw,8,Nf)-repmat(bb(pl'),1,Nf))./repmat(bb(ph'+65)-bb(pl'),1,Nf),0,1);

ledp=zeros(1,Nf);
for nf=1:Nf
	chi=sum(ledblutf.^2,2)-2*ledblutf*lednorm(:,nf);
	chi=chi+repmat(sum(lednorm(:,nf).^2),2571,1);
	[mx ledp(nf)]=min(chi);
end
led=mod(numled(ledp),256);
ledt=led'/500;

numseg=(conv2(reshape(permute(reshape(repmat((-1:16)',10,1),18,10,1),[2 1]),180,1),ones(10,1),'valid'))/10;
seglutf=(conv2(reshape(permute(reshape(repmat(seglut([end 1:end 1],:),10,1),18,10,7),[2 1 3]),180,7),ones(10,1),'valid'))/10;

[nn bb]=hist(reshape(segraw,28,Nf)',100);
[mx pl]=max(nn(1:30,:));
[mx ph]=max(nn(60:end,:));
segnorm=clip((reshape(segraw,28,Nf)-repmat(bb(pl'),1,Nf))./repmat(bb(ph'+60)-bb(pl'),1,Nf),0,1);

chi=repmat(sum(seglutf.^2,2),1,4*Nf)-2*seglutf*reshape(segnorm,7,4*Nf)+repmat(sum(reshape(segnorm.^2,7,4*Nf)),171,1);
[mn segp]=min(chi);

seg=reshape(mod(round(numseg(segp)),16),4,Nf);
ii=diff(16.^(3:-1:0)*seg*256+led')<0 & led(1:end-1)'>255; % correct transitions
seg(4,ii)=seg(4,ii)-1;

segt=16.^(3:-1:0)*seg*256/500;

time=segt+ledt;
