// File: /workspace/github_c_makefile_star2_O3/Matthias-Wandel[P]imgcomp/src/exposure.c
// Function: CalcExposureAdjust
int CalcExposureAdjust(MemImage_t * pic)
{
    Region_t Region = Regions.DetectReg;
    if (Region.y2 > pic->height) Region.y2 = pic->height;
    if (Region.x2 > pic->width) Region.x2 = pic->width;

    int BrHistogram[256] = {0}; // Brightness histogram, for red green and blue channels.
    int NumPix = 0;
    int width = pic->width;

    int rowbytes = pic->width*3;
    for (int row=Region.y1;row<Region.y2;row++){
        unsigned char *p1;
        p1 = pic->pixels+rowbytes*row;
        int * ExRow = NULL;
        if (WeightMap) ExRow = &WeightMap->values[width*row];
        for (int col=Region.x1;col<Region.x2;col++){
            if (ExRow && ExRow[col]){
                // Apply the colors to the histogram separately (saturating one is saturated enough)
                BrHistogram[p1[0]] += 2; // Red,   1/3 weight
                BrHistogram[p1[1]] += 3; // Green, 1/2 weight
                BrHistogram[p1[2]] += 1; // Blue,  1/6 weight
                NumPix += 1;
            }
            p1 += 3;
        }
    }
    NumPix *= 6;

    static int ShowPeriodic = 45;
    if (++ShowPeriodic >= 60) ShowPeriodic = 0;

    if (ShowPeriodic == 0){
        // Show histogram bargraph
        int maxv = 0;
        int skz = 1;
        for (int a=0;a<256;a+=2){
            int twobin = BrHistogram[a]+BrHistogram[a+1];
            if (twobin > maxv) maxv = twobin;
        }
        fprintf(Log,"Brighness histogram\n");
        for (int a=0;a<256;a+=2){
            if (a == 26){
                fprintf(Log,"...........\n");// Skip middle part of histogram, not that interesting.
                a = 210;
                skz = 1;
            }
            int twobin = BrHistogram[a]+BrHistogram[a+1];
            if (twobin == 0 && skz) continue;
            skz = 0;
            fprintf(Log,"%3d %6d %6d ",a,BrHistogram[a], BrHistogram[a+1]);
            static char * Bargraph = "#########################################################################";
            fprintf(Log,"%.*s\n", (50*twobin+maxv/2)/maxv, Bargraph);
        }
    }

    double ExposureMult = 1.0;

    // figure out what threshold value has no more than 0.4% of pixels above.
    int satpix = NumPix / 64;  // Allowable pixels near saturation
    int medpix = NumPix / 20;  // Don't make the image overall too bright.
    int sat, med;
    int SatVal;
    for (sat=255;sat>=0;sat--){
        satpix -= BrHistogram[sat];
        if (satpix <= 0) break;
    }
    for (med=255;med>=0;med--){
        medpix -= BrHistogram[med];
        if (medpix <= 0) break;
    }


    double SatFrac;
    if (ex.SatVal){
        SatVal = ex.SatVal;
    }else{
        SatVal = 253;
        if (memcmp(ImageInfo.CameraModel, "RP_ov5647",10) == 0){
            // 5 megapixel module saturates around pixel value of 245, not 255.
            // Newer modules pixel values saturate closer to 255
            SatVal = 240;
        }
    }
    int SatPix = 0;
    for (int a=SatVal;a<256;a++){
        SatPix += BrHistogram[a];
    }
    SatFrac = (double)SatPix/NumPix;


    // Adjust exposure upwards becauase very few pixels are near
    // maximum values, so there's exposure headroom.
    double Mult=10,Mult2=10;
    if (sat) Mult = 0.96*SatVal/sat;
    if (med) Mult2 = 0.93*SatVal/med;
    if (Mult2 < Mult) Mult = Mult2;
    if (Mult > 32) Mult = 32; // Do't try to adjust more than this!
    ExposureMult = Mult;

    // Adjsut exposure downward because too many pixels
    // have saturated.  It's impossible to calculate how far down
    // we really need to adjust cause it's saturating, so just guess.
    if (SatFrac > 0.03) ExposureMult = 0.8;
    if (SatFrac > 0.06) ExposureMult = 0.7;
    if (SatFrac > 0.12) ExposureMult = 0.6;
    if (SatFrac > 0.20) ExposureMult = 0.5;
    if (SatFrac > 0.40) ExposureMult = 0.4;

    double LightMult = pow(ExposureMult, 2.2); // assume camer gamma is 2.2 for light level calculation

    // LightMult indicates how much more the light should have been,
    // or how much to multiply exposure time or ISO or combination of both by.

    double ImgIsoTimesExp = ImageInfo.ExposureTime * ImageInfo.ISOequivalent;
    
    if (ShowPeriodic == 0){
        fprintf(Log, "Brightness: 3%%>%d  25%%>%d  Sat%%=%3.1f  Iso*Ex=%4.1f Adjust *%4.2f\n",sat,med, SatFrac*100, ImgIsoTimesExp, LightMult);
        ShowPeriodic = 0;
    }

    // Compute a measure of how steady the light is.  If it's really steady,
    // ten lower the threshold for making exposure adjustments.
    static double LightMult_ra = 1;
    static double LightMultVariance_ra = 1;
    const double newweight = 0.05;
    LightMult_ra = LightMult_ra*(1-newweight)+LightMult*newweight;
    double diff  = LightMult-LightMult_ra;
    LightMultVariance_ra = LightMultVariance_ra*(1-newweight) + diff*diff*newweight;
    if (ShowPeriodic == 0) fprintf(Log, "Mult:%5.2f mra:%5.2f stdev:%5.2f\n",LightMult, LightMult_ra, sqrt(LightMultVariance_ra));

    double ExposureThresholdRatio = 1.2;
    if (LightMultVariance_ra < (0.2*0.2)){
        // Light has been very steady for a while, so be willing to make fine adjustments to exposure.
        ExposureThresholdRatio = 1.06;
        //printf("fine ");
    }

    if ((LightMult >= ExposureThresholdRatio && ExMaxLimitHit == 0)
        || (LightMult <= 1/ExposureThresholdRatio && ExMinLimitHit == 0)){
        // If adjustment is called for, *and* we haven't hit an exposure limit:
        fprintf(Log, "Brightness: 1.5%%>%d  5%%>%d  Sat%%=%3.1f Adjust *%4.2f\n",sat,med, SatFrac*100, LightMult);
        ShowPeriodic = 0;

        fprintf(Log,"Adjust exposure.  Was: t=%0.5f",ImageInfo.ExposureTime);
        fprintf(Log," ISO=%d   ISO*Exp=%.0f\n",ImageInfo.ISOequivalent, ImgIsoTimesExp);

        ISOtimesExp = ImgIsoTimesExp * LightMult;
        GetRaspistillExpParms();

        // Reset exposure adjust running averages (avoid fine adjust too soon)
        LightMult_ra = 1;
        LightMultVariance_ra = 1;

        return 1; // And signal raspistill needs restarting.
    }
    return 0;
}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x428, %rsp            # imm = 0x428
movq %rdi, %rbx
leaq 0x858b(%rip), %rax      # 0x12db8
movslq (%rax), %r14
movl 0x4(%rax), %r15d
movl 0xc(%rax), %ecx
movslq 0x8(%rax), %r12
movl 0x4(%rdi), %ebp
cmpl %ebp, %ecx
cmovll %ecx, %ebp
movslq (%rdi), %r13
leaq 0x20(%rsp), %rdi
movl $0x400, %edx            # imm = 0x400
xorl %esi, %esi
callq 0x31b0
movl $0x0, %eax
cmpl %ebp, %r12d
jge 0xa900
cmpl %r13d, %r15d
cmovgel %r13d, %r15d
leal (%r13,%r13,2), %ecx
leaq 0x8b90(%rip), %rax      # 0x13408
movq (%rax), %rax
movslq %ecx, %rcx
movslq %ebp, %rdx
movslq %r15d, %rsi
movq %r12, %rdi
imulq %r13, %rdi
leaq (%rax,%rdi,4), %rdi
addq $0x8, %rdi
shlq $0x2, %r13
movq %r12, %r8
imulq %rcx, %r8
leaq (%r8,%rbx), %r9
addq $0xe, %r9
xorl %r8d, %r8d
movq %r9, %r10
movq %r14, %r11
cmpl %r15d, %r14d
jge 0xa8eb
testq %rax, %rax
je 0xa8df
cmpl $0x0, (%rdi,%r11,4)
je 0xa8df
movzbl -0x2(%r10), %ebx
addl $0x2, 0x20(%rsp,%rbx,4)
movzbl -0x1(%r10), %ebx
addl $0x3, 0x20(%rsp,%rbx,4)
movzbl (%r10), %ebx
incl 0x20(%rsp,%rbx,4)
incl %r8d
incq %r11
addq $0x3, %r10
cmpq %r11, %rsi
jne 0xa8b4
incq %r12
addq %r13, %rdi
addq %rcx, %r9
cmpq %rdx, %r12
jne 0xa8a9
addl %r8d, %r8d
leal (%r8,%r8,2), %eax
movq %rax, (%rsp)
movl 0x79ce(%rip), %eax      # 0x122d8
leal 0x1(%rax), %ecx
cmpl $0x3b, %eax
movl $0x0, %eax
cmovgel %eax, %ecx
movl %ecx, 0x79ba(%rip)      # 0x122d8
testl %ecx, %ecx
jne 0xaa68
pxor %xmm0, %xmm0
xorl %eax, %eax
movaps 0x20(%rsp,%rax,8), %xmm1
movaps 0x30(%rsp,%rax,8), %xmm2
movaps %xmm1, %xmm3
shufps $0x88, %xmm2, %xmm3     # xmm3 = xmm3[0,2],xmm2[0,2]
shufps $0xdd, %xmm2, %xmm1     # xmm1 = xmm1[1,3],xmm2[1,3]
paddd %xmm3, %xmm1
movdqa %xmm1, %xmm2
pcmpgtd %xmm0, %xmm2
pand %xmm2, %xmm1
pandn %xmm0, %xmm2
movdqa %xmm2, %xmm0
por %xmm1, %xmm0
addq $0x4, %rax
cmpq $0x80, %rax
jne 0xa92c
pshufd $0xee, %xmm0, %xmm1     # xmm1 = xmm0[2,3,2,3]
movdqa %xmm0, %xmm2
pcmpgtd %xmm1, %xmm2
pand %xmm2, %xmm0
pandn %xmm1, %xmm2
por %xmm0, %xmm2
pshufd $0x55, %xmm2, %xmm0     # xmm0 = xmm2[1,1,1,1]
movdqa %xmm2, %xmm1
pcmpgtd %xmm0, %xmm1
pand %xmm1, %xmm2
pandn %xmm0, %xmm1
por %xmm2, %xmm1
movd %xmm1, %r14d
leaq 0x8611(%rip), %rbx      # 0x12fb8
movq (%rbx), %rcx
leaq 0x3d06(%rip), %rdi      # 0xe6b7
movl $0x14, %esi
movl $0x1, %edx
callq 0x34a0
movl %r14d, %ebp
shrl %ebp
movl $0x1, %r15d
xorl %r13d, %r13d
cmpl $0x1a, %r13d
jne 0xa9f9
movq (%rbx), %rcx
movl $0xc, %esi
movl $0x1, %edx
leaq 0x3ce4(%rip), %rdi      # 0xe6cc
callq 0x34a0
movl $0xd2, %r13d
movl $0x1, %r15d
movslq %r13d, %rax
movl 0x20(%rsp,%rax,4), %ecx
movl 0x24(%rsp,%rax,4), %r8d
leal (%r8,%rcx), %r12d
testl %r15d, %r15d
je 0xaa19
movl $0x1, %r15d
testl %r12d, %r12d
je 0xaa54
movq (%rbx), %rdi
xorl %r15d, %r15d
leaq 0x3cb3(%rip), %rsi      # 0xe6d9
movl %r13d, %edx
xorl %eax, %eax
callq 0x32a0
movq (%rbx), %rdi
imull $0x32, %r12d, %eax
addl %ebp, %eax
cltd
idivl %r14d
leaq 0x3cec(%rip), %rsi      # 0xe730
movl %eax, %edx
leaq 0x3c99(%rip), %rcx      # 0xe6e6
xorl %eax, %eax
callq 0x32a0
leal 0x2(%r13), %eax
cmpl $0xfe, %r13d
movl %eax, %r13d
jl 0xa9ce
movq (%rsp), %rdi
leal 0x3f(%rdi), %ecx
testl %edi, %edi
cmovnsl %edi, %ecx
sarl $0x6, %ecx
movslq %edi, %rax
imulq $0x66666667, %rax, %rax # imm = 0x66666667
movq %rax, %rdx
shrq $0x3f, %rdx
sarq $0x23, %rax
addl %edx, %eax
movl $0xff, %ebx
movl %ebx, %edx
subl 0x20(%rsp,%rdx,4), %ecx
jle 0xaaa5
addl $-0x1, %ebx
jb 0xaa93
movl $0xffffffff, %ebx       # imm = 0xFFFFFFFF
movl $0xff, %ebp
movl %ebp, %ecx
subl 0x20(%rsp,%rcx,4), %eax
jle 0xaabc
addl $-0x1, %ebp
jb 0xaaaa
movl $0xffffffff, %ebp       # imm = 0xFFFFFFFF
movl 0xb05e(%rip), %eax      # 0x15b20
testl %eax, %eax
je 0xaad2
xorps %xmm3, %xmm3
cmpl $0xff, %eax
jle 0xab05
jmp 0xab29
leaq 0x897f(%rip), %rax      # 0x13458
movabsq $0x343635766f5f5052, %rcx # imm = 0x343635766F5F5052
xorq 0x1028(%rax), %rcx
movzwl 0x1030(%rax), %eax
xorq $0x37, %rax
orq %rcx, %rax
movl $0xf0, %ecx
movl $0xfd, %eax
cmovel %ecx, %eax
movslq %eax, %rcx
incq %rcx
xorl %edx, %edx
movq %rcx, %rsi
addl 0x1c(%rsp,%rcx,4), %edx
incq %rsi
cmpl $0x100, %ecx            # imm = 0x100
movq %rsi, %rcx
jne 0xab10
xorps %xmm3, %xmm3
cvtsi2sd %edx, %xmm3
xorps %xmm0, %xmm0
cvtsi2sd %edi, %xmm0
divsd %xmm0, %xmm3
movd %ebx, %xmm0
movd %ebp, %xmm1
punpckldq %xmm0, %xmm1    # xmm1 = xmm1[0],xmm0[0],xmm1[1],xmm0[1]
pshufd $0x50, %xmm1, %xmm0     # xmm0 = xmm1[0,0,1,1]
pxor %xmm2, %xmm2
pcmpeqd %xmm0, %xmm2
xorps %xmm0, %xmm0
cvtsi2sd %eax, %xmm0
cvtdq2pd %xmm1, %xmm1
unpcklpd %xmm0, %xmm0            # xmm0 = xmm0[0,0]
mulpd 0x3a8c(%rip), %xmm0     # 0xe5f0
divpd %xmm1, %xmm0
movdqa %xmm2, %xmm1
pandn %xmm0, %xmm1
pand 0x3a88(%rip), %xmm2     # 0xe600
por %xmm1, %xmm2
pshufd $0xee, %xmm2, %xmm0     # xmm0 = xmm2[2,3,2,3]
minsd %xmm0, %xmm2
movsd 0x39e3(%rip), %xmm0     # 0xe570
minsd %xmm2, %xmm0
movsd 0x39df(%rip), %xmm1     # 0xe578
cmpltsd %xmm3, %xmm1
movsd 0x39da(%rip), %xmm2     # 0xe580
andpd %xmm1, %xmm2
andnpd %xmm0, %xmm1
orpd %xmm1, %xmm2
movsd 0x39ce(%rip), %xmm0     # 0xe588
cmpltsd %xmm3, %xmm0
movsd 0x39c9(%rip), %xmm1     # 0xe590
andpd %xmm0, %xmm1
andnpd %xmm2, %xmm0
orpd %xmm0, %xmm1
movsd 0x39bd(%rip), %xmm0     # 0xe598
cmpltsd %xmm3, %xmm0
movsd 0x39b8(%rip), %xmm2     # 0xe5a0
andpd %xmm0, %xmm2
andnpd %xmm1, %xmm0
orpd %xmm0, %xmm2
movsd 0x39ac(%rip), %xmm0     # 0xe5a8
cmpltsd %xmm3, %xmm0
movsd 0x1aef(%rip), %xmm1     # 0xc6f8
andpd %xmm0, %xmm1
andnpd %xmm2, %xmm0
orpd %xmm0, %xmm1
movsd 0x3993(%rip), %xmm2     # 0xe5b0
movapd %xmm2, %xmm0
movsd %xmm3, 0x10(%rsp)
cmpltsd %xmm3, %xmm0
movapd %xmm0, %xmm3
andnpd %xmm1, %xmm3
andpd %xmm2, %xmm0
orpd %xmm3, %xmm0
movsd 0x3974(%rip), %xmm1     # 0xe5b8
callq 0x3100
leaq 0x8808(%rip), %r15      # 0x13458
xorps %xmm1, %xmm1
cvtsi2ssl 0x10a8(%r15), %xmm1
mulss 0x1080(%r15), %xmm1
movapd %xmm0, %xmm3
xorps %xmm0, %xmm0
cvtss2sd %xmm1, %xmm0
movsd %xmm0, (%rsp)
movl 0x765c(%rip), %r14d     # 0x122d8
testl %r14d, %r14d
movsd %xmm3, 0x8(%rsp)
jne 0xacca
leaq 0x832a(%rip), %rax      # 0x12fb8
movq (%rax), %rdi
movsd 0x3927(%rip), %xmm0     # 0xe5c0
mulsd 0x10(%rsp), %xmm0
leaq 0x3a90(%rip), %rsi      # 0xe736
movl %ebx, %edx
movl %ebp, %ecx
movsd (%rsp), %xmm1
movapd %xmm3, %xmm2
movb $0x3, %al
callq 0x32a0
movsd 0x8(%rsp), %xmm3
movl $0x0, 0x760e(%rip)      # 0x122d8
movsd 0x38f6(%rip), %xmm4     # 0xe5c8
movapd %xmm3, %xmm2
mulsd %xmm4, %xmm2
movsd 0x38ee(%rip), %xmm0     # 0xe5d0
movsd 0x75f6(%rip), %xmm1     # 0x122e0
mulsd %xmm0, %xmm1
addsd %xmm2, %xmm1
movsd %xmm1, 0x75e6(%rip)     # 0x122e0
movapd %xmm3, %xmm2
subsd %xmm1, %xmm2
mulsd %xmm2, %xmm2
mulsd 0x75da(%rip), %xmm0     # 0x122e8
mulsd %xmm4, %xmm2
addsd %xmm2, %xmm0
movsd %xmm0, 0x75ca(%rip)     # 0x122e8
testl %r14d, %r14d
jne 0xad7e
leaq 0x828e(%rip), %rax      # 0x12fb8
movq (%rax), %r14
xorpd %xmm2, %xmm2
ucomisd %xmm2, %xmm0
jb 0xad40
xorps %xmm2, %xmm2
sqrtsd %xmm0, %xmm2
jmp 0xad5b
movsd %xmm1, 0x18(%rsp)
callq 0x34b0
movsd 0x18(%rsp), %xmm1
movsd 0x8(%rsp), %xmm3
movapd %xmm0, %xmm2
leaq 0x3a1a(%rip), %rsi      # 0xe77c
movq %r14, %rdi
movapd %xmm3, %xmm0
movb $0x3, %al
callq 0x32a0
movsd 0x8(%rsp), %xmm3
movsd 0x756a(%rip), %xmm0     # 0x122e8
movsd 0x10(%rsp), %xmm2
movsd 0x384c(%rip), %xmm1     # 0xe5d8
xorl %eax, %eax
ucomisd %xmm0, %xmm1
seta %al
leaq 0x3874(%rip), %rcx      # 0xe610
movsd (%rcx,%rax,8), %xmm0
ucomisd %xmm0, %xmm3
jb 0xadb0
testb $0x1, 0xad7e(%rip)      # 0x15b2c
je 0xadd5
movsd 0x1950(%rip), %xmm1     # 0xc708
divsd %xmm0, %xmm1
xorl %eax, %eax
ucomisd %xmm3, %xmm1
jb 0xae7a
testb $0x1, 0xad59(%rip)      # 0x15b28
jne 0xae7a
leaq 0x81dc(%rip), %r14      # 0x12fb8
movq (%r14), %rdi
mulsd 0x37d9(%rip), %xmm2     # 0xe5c0
leaq 0x39b0(%rip), %rsi      # 0xe79e
movl %ebx, %edx
movl %ebp, %ecx
movapd %xmm2, %xmm0
movapd %xmm3, %xmm1
movb $0x2, %al
callq 0x32a0
movl $0x0, 0x74cd(%rip)      # 0x122d8
movq (%r14), %rdi
xorps %xmm0, %xmm0
cvtss2sd 0x1080(%r15), %xmm0
leaq 0x39b6(%rip), %rsi      # 0xe7d7
movb $0x1, %al
callq 0x32a0
movq (%r14), %rdi
movl 0x10a8(%r15), %edx
leaq 0x39bd(%rip), %rsi      # 0xe7f6
movsd (%rsp), %xmm0
movb $0x1, %al
callq 0x32a0
movsd 0x8(%rsp), %xmm0
mulsd (%rsp), %xmm0
movsd %xmm0, 0x7478(%rip)     # 0x122d0
callq 0xa53c
movabsq $0x3ff0000000000000, %rax # imm = 0x3FF0000000000000
movq %rax, 0x7472(%rip)      # 0x122e0
movq %rax, 0x7473(%rip)      # 0x122e8
movl $0x1, %eax
addq $0x428, %rsp            # imm = 0x428
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq