ADAPTIVETHRESHOLD An adaptive thresholding algorithm that seperates the foreground from the background with nonuniform illumination.
bw=adaptivethreshold(IM,ws,C) outputs a binary image bw with the local threshold mean-C or median-C to the image IM.

ws is the local window size.

tm is 0 or 1, a switch between mean and median. tm=0 mean(default); tm=1 median.

this works quite well for my application but can anyone explain to me what the algorithm is doing exactly?
I understand that the algorithm generates a local mean filtered image by iterating over each pixel for user window size but what is line:

sIM=mIM-IM-C

this subtracts the original image and a constant, C, from the local mean filtered image. What is C and why do this?

I did apply this algorithm on my images but it didn't work out completely. There is a research paper by Q.Huang et.al. which speaks about Otsu's thresholding using adaptive window. I would like to know if somebody has implemented that.

The 2 lines near the end should be changed from:
sIM=mIM-IM;
bw=im2bw(sIM,C);
to:
sIM=mIM-IM-C;
bw=im2bw(sIM,0);
This change allows C to be +ve and negative. In the old code bw=im2bw(sIM,C) causes error when C is -ve.