clear all;
close all;

%dataset name
sam='fbrachinus_2__C001H001S0001';

%define range for background correction
backgrd_start=58;
backgrd_end=158;

%define range for enhancement
enhance_start=1;
enhance_end=1145;

%define cropping row parameters
crop_rstart=213;
crop_rsize=400;
crop_rend=crop_rstart+crop_rsize-1;

%define cropping column parameters
crop_cstart=312;
crop_csize=400;
crop_cend=crop_cstart+crop_csize-1;

%define filters
avger=fspecial('average',[50 50]);
gauss=fspecial('gaussian',[3 3],0.5);

%define directories and file name prefixes
indir=cat(2,'FilePathRedacted\',sam,'\');
inprefix=cat(2,indir,sam,'0');
outdir=cat(2,indir,'enhanced2');
outprefix=cat(2,outdir,'\',sam,'0');
if exist(outdir,'dir') == 0
    mkdir(outdir);
end

%calculate background
filenum=num2str(backgrd_start,'%05d');
file=cat(2,inprefix,filenum,'.tif');
x1=single(imread(file));
for n=backgrd_start+1:1:backgrd_end
    filenum=num2str(n,'%05d');
    infile=cat(2,inprefix,filenum,'.tif');
    x2=single(imread(file));
    x1=x1+x2;
end
bkg=x1./(backgrd_end-backgrd_start+1);
bkg=imfilter(bkg,avger);

%ready matlabpool
if matlabpool('size') == 0
    matlabpool open 8
end

%enhance images
parfor n=enhance_start:enhance_end
    filenum=num2str(n,'%05d');
    infile=cat(2,inprefix,filenum,'.tif');    
    x=single(imread(infile));
    im=x./bkg;
    im=im(crop_rstart:crop_rend,crop_cstart:crop_cend);
    maxim=max(max(im));
    minim=min(min(im));
    im=(im-minim)./(maxim-minim);
    im=imadjust(im);
    im=imfilter(im,gauss,'replicate');
    intim=im2uint8(im);
    outfile=cat(2,outprefix,filenum,'_enhanced2.tif');
    imwrite(intim,outfile);
end

matlabpool close
