just to add, to account for the small variation in the max grayscale level, i have redefined maxval as the maxlevel plus 10%. I've also tried just adding counts from histogram, but Im making a mistake somewhere.
[maxval,idx]=max(IM(:));
maxval= double(maxval*1.1)
[counts,x] = imhist(IM,maxval)
Totalcounts=Totalcounts+counts;