%% User input
idir='ImageRepository';
fns='*.JPG'; % filenames to process
bd=50;       % boundary of cell must be even
Nb=100;      % number of frames to get background
froff=100;   % frame offset to get background

timesavlist={'time','segt','seg','ledt','led','segraw','ledraw','base'};

%% Setup
dr=dir([idir '/' fns]);
Nf=length(dr);
info=imfinfo([idir '/' dr(1).name]);
base=info.DateTime([3 4 6 7 9 10 12 13 15 16 18 19]);

aimg=0;
colormap(jet(256));

%%

load([base '_pre']);

ss=15;
[xx yy]=ndgrid(-ss:ss,-ss:ss);
rr=xx+i*yy; %#ok<*IJCL>
[Nl lx ly]=findpeaks(1./chiimg(aimg(:,box(4):end)/3/140,ipf(abs(rr),6,1.2),[]),1,10,0);
[lx ii]=sort(lx);
ly=ly(ii);

ledii=zeros((2*5+1)^2,8);
[xx yy]=ndgrid(-5:5,-5:5);
for n=1:Nl
	ledii(:,n)=flat(sub2ind(size(aimg),xx+lx(n)-ss,box(4)+ly(n)+yy-ss-1));
end

nf=100;
im=double(imread([idir '/' dr(nf).name]));
simage(im(reshape(ledii,11,11*8)))

pause(5);

%% 7-segment

segx1=lx(end)+find(diff(mean(aimg(lx(end):end,box(4)+3*bd:end),2)>15)==1,1);
segx2=lx(end)+find(diff(mean(aimg(lx(end):end,box(4)+3*bd:end),2)>15)==-1,1,'last');
segx=fix(mean([segx1 segx2],2));
segdx=fix(abs(segx1-segx2)/4*1.11)*4;

segy1=box(4)+3*bd+find(diff(mean(aimg(lx(end):end,box(4)+3*bd:end))>20)==1);
segy2=box(4)+3*bd+find(diff(mean(aimg(lx(end):end,box(4)+3*bd:end))>20)==-1);
segy=fix(mean([segy1 segy2],2));
segdy=fix(abs(segy1-segy2)/4*1.2)*4;

ry=fix(segdy*[...
	    .35*[1 1 1 1];...   % A
	  .35/2*[1 1 1 1];...   % B
	 -.35/2*[1 1 1 1];...   % C
	   -.35*[1 1 1 1];...   % D
	 -.35/2*[1 1 1 1];...   % E
	  .35/2*[1 1 1 1];...   % F
	        [0 0 0 0]]);    % G

rx=fix(segdx*[...
	[-3/8 -1/8 1/8 3/8]+1/64;...
	[-3/8 -1/8 1/8 3/8]+1/128+1/18;...
	[-3/8 -1/8 1/8 3/8]-1/128+1/18;...				
	[-3/8 -1/8 1/8 3/8]-1/64;...
	[-3/8 -1/8 1/8 3/8]-1/128-1/18;...
	[-3/8 -1/8 1/8 3/8]+1/128-1/18;...				
	[-3/8 -1/8 1/8 3/8]]);

segii=zeros((2*4+1)*(2*8+1),7,4);
[xx yy]=ndgrid(-8:8,-4:4);
for m=[1 4 7]
	for n=1:4
		segii(:,m,n)=...
			flat(sub2ind(size(aimg),xx+rx(m,n)+segx,yy+ry(m,n)+segy));
	end
end
[xx yy]=ndgrid(-4:4,-8:8);
for m=[2 3 5 6]
	for n=1:4
		segii(:,m,n)=...
			flat(sub2ind(size(aimg),xx+rx(m,n)+segx,yy+ry(m,n)+segy));
	end
end

seglut=[...
	[1 0 0 0 0 0 0];...
	[1 1 1 1 0 0 1];...
	[0 1 0 0 1 0 0];...
	[0 1 1 0 0 0 0];...
	[0 0 1 1 0 0 1];...
  [0 0 1 0 0 1 0];...
  [0 0 0 0 0 1 0];...
  [1 1 1 1 0 0 0];...
  [0 0 0 0 0 0 0];...
  [0 0 1 0 0 0 0];...
	[0 0 0 1 0 0 0];...
	[0 0 0 0 0 1 1];...
	[1 0 0 0 1 1 0];...
	[0 1 0 0 0 0 1];...
	[0 0 0 0 1 1 0];...
	[0 0 0 1 1 1 0]];

seglut=fliplr(1-seglut);


simage(im(:,:,1)); 
axis([segy+segdy/2*[-1 1],segx+segdx/2*[-1 1]])
hold on;
plot(segy+ry,segx+rx,'*');
hold off;
pause(5);

%% Process images

segraw=zeros(7,4,Nf);
ledraw=zeros(8,Nf);

fprintf(1,'Processing...');
Nc=length(sprintf('%d',Nf+1));
fmt=sprintf('[%%0%dd/%%0%dd]',Nc,Nc);
fprintf(1,fmt,0,Nf+1);

tog=true;
for nf=1:Nf
	im=double(imread([idir '/' dr(nf).name]));
	segraw(:,:,nf)=squeeze(sum(im(segii)));
	ledraw(:,nf)=sum(im(ledii));
	if(mod(nf,10)==0)
		tog=~tog;
		if(tog)
			simage(segraw(:,:,nf));
		else
			simage(im(reshape(ledii,11,11*8)));
		end
		drawnow;
	end
	backspace(1,fmt,nf,Nf+1);
	fprintf(1,fmt,nf,Nf+1);
end
fprintf(1,'Done.\n');
%%

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);

chi=repmat(sum(ledblutf.^2,2),1,Nf);
chi=chi-2*ledblutf*lednorm;
chi=chi+repmat(sum(lednorm.^2),2571,1);

[mx ledp]=min(chi);
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;

[nn bb]=hist(diff(ledt+segt),.007+(-1:.0002:1));
plot(bb,nn,'.-'); axis([.007+.002*[-1 1] 0 5000])

time=segt+ledt;

fprintf('Saving...');
save([base '_time'],timesavlist{:});
fprintf('Done.\n');


