// File: /workspace/github_c_makefile_star2_O2/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, (%rsp)
leaq 0x8f0e(%rip), %rax      # 0x12dc8
movslq (%rax), %r14
movslq 0x8(%rax), %r15
movl 0x4(%rax), %r13d
movl 0xc(%rax), %eax
movl 0x4(%rdi), %ebx
cmpl %ebx, %eax
cmovll %eax, %ebx
movslq (%rdi), %r12
cmpl %r12d, %r13d
cmovgel %r12d, %r13d
leaq 0x20(%rsp), %rdi
xorl %ebp, %ebp
movl $0x400, %edx            # imm = 0x400
xorl %esi, %esi
callq 0x31b0
leal (%r12,%r12,2), %esi
leaq 0x9520(%rip), %rax      # 0x13418
movq (%rax), %rax
movslq %r13d, %rcx
movslq %ebx, %rdx
movslq %esi, %rsi
movq %r15, %rdi
imulq %r12, %rdi
leaq (%rax,%rdi,4), %rdi
addq $0x8, %rdi
shlq $0x2, %r12
movq %r15, %r8
imulq %rsi, %r8
movq (%rsp), %r9
addq %r9, %r8
addq $0xe, %r8
cmpq %rdx, %r15
jge 0x9f7a
movq %r8, %r9
movq %r14, %r10
cmpq %rcx, %r10
jge 0x9f6f
testq %rax, %rax
je 0x9f66
cmpl $0x0, (%rdi,%r10,4)
je 0x9f66
movzbl -0x2(%r9), %r11d
addl $0x2, 0x20(%rsp,%r11,4)
movzbl -0x1(%r9), %r11d
addl $0x3, 0x20(%rsp,%r11,4)
movzbl (%r9), %r11d
incl 0x20(%rsp,%r11,4)
incl %ebp
incq %r10
addq $0x3, %r9
jmp 0x9f34
incq %r15
addq %r12, %rdi
addq %rsi, %r8
jmp 0x9f29
imull $0x6, %ebp, %eax
movl %eax, 0x8(%rsp)
movl 0x8359(%rip), %eax      # 0x122e0
leal 0x1(%rax), %ecx
xorl %r15d, %r15d
cmpl $0x3b, %eax
cmovgel %r15d, %ecx
movl %ecx, 0x8346(%rip)      # 0x122e0
testl %ecx, %ecx
je 0xa252
pushq $0x1
popq %r15
pushq $0x40
popq %rcx
movl 0x8(%rsp), %r14d
movl %r14d, %eax
cltd
idivl %ecx
movl %eax, %ecx
pushq $0x14
popq %rsi
movl %r14d, %eax
cltd
idivl %esi
movl $0xff, %ebx
pushq $-0x1
popq %rbp
testl %ebx, %ebx
js 0x9fd7
movl %ebx, %edx
subl 0x20(%rsp,%rdx,4), %ecx
jle 0x9fd9
decl %ebx
jmp 0x9fc7
movl %ebp, %ebx
movl $0xff, %ecx
testl %ecx, %ecx
js 0x9ff0
movl %ecx, %edx
subl 0x20(%rsp,%rdx,4), %eax
jle 0x9fee
decl %ecx
jmp 0x9fde
movl %ecx, %ebp
movl 0xbb3a(%rip), %eax      # 0x15b30
testl %eax, %eax
jne 0xa024
movl $0x1028, %edi           # imm = 0x1028
addq 0x7fd2(%rip), %rdi      # 0x11fd8
leaq 0x45e3(%rip), %rsi      # 0xe5f0
pushq $0xa
popq %rdx
callq 0x33a0
testl %eax, %eax
movl $0xf0, %ecx
movl $0xfd, %eax
cmovel %ecx, %eax
movslq %eax, %rdx
xorl %ecx, %ecx
cmpq $0x100, %rdx            # imm = 0x100
jge 0xa03b
addl 0x20(%rsp,%rdx,4), %ecx
incq %rdx
jmp 0xa029
cvtsi2sd %ecx, %xmm3
cvtsi2sd %r14d, %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
cvtsi2sd %eax, %xmm0
cvtdq2pd %xmm1, %xmm1
unpcklpd %xmm0, %xmm0            # xmm0 = xmm0[0,0]
mulpd 0x454b(%rip), %xmm0     # 0xe5c0
divpd %xmm1, %xmm0
movdqa %xmm2, %xmm1
pandn %xmm0, %xmm1
pand 0x4547(%rip), %xmm2     # 0xe5d0
por %xmm1, %xmm2
pshufd $0xee, %xmm2, %xmm0     # xmm0 = xmm2[2,3,2,3]
minsd %xmm0, %xmm2
movsd 0x44a2(%rip), %xmm0     # 0xe540
minsd %xmm2, %xmm0
movsd 0x449e(%rip), %xmm1     # 0xe548
cmpltsd %xmm3, %xmm1
movsd 0x4499(%rip), %xmm2     # 0xe550
andpd %xmm1, %xmm2
andnpd %xmm0, %xmm1
orpd %xmm1, %xmm2
movsd 0x448d(%rip), %xmm0     # 0xe558
cmpltsd %xmm3, %xmm0
movsd 0x4488(%rip), %xmm1     # 0xe560
andpd %xmm0, %xmm1
andnpd %xmm2, %xmm0
orpd %xmm0, %xmm1
movsd 0x447c(%rip), %xmm0     # 0xe568
cmpltsd %xmm3, %xmm0
movsd 0x4477(%rip), %xmm2     # 0xe570
andpd %xmm0, %xmm2
andnpd %xmm1, %xmm0
orpd %xmm0, %xmm2
movsd 0x446b(%rip), %xmm0     # 0xe578
cmpltsd %xmm3, %xmm0
movsd 0x25de(%rip), %xmm1     # 0xc6f8
andpd %xmm0, %xmm1
andnpd %xmm2, %xmm0
orpd %xmm0, %xmm1
movsd 0x4452(%rip), %xmm2     # 0xe580
movapd %xmm2, %xmm0
movsd %xmm3, 0x10(%rsp)
cmpltsd %xmm3, %xmm0
movapd %xmm0, %xmm3
andnpd %xmm1, %xmm3
andpd %xmm2, %xmm0
orpd %xmm3, %xmm0
movsd 0x4433(%rip), %xmm1     # 0xe588
callq 0x3100
leaq 0x9307(%rip), %r12      # 0x13468
cvtsi2ssl 0x10a8(%r12), %xmm1
mulss 0x1080(%r12), %xmm1
movapd %xmm0, %xmm3
cvtss2sd %xmm1, %xmm0
movsd %xmm0, (%rsp)
movl 0x8157(%rip), %r14d     # 0x122e0
testl %r14d, %r14d
movsd %xmm3, 0x8(%rsp)
jne 0xa1d4
leaq 0x8e2d(%rip), %rax      # 0x12fc8
movq (%rax), %rdi
movsd 0x43ea(%rip), %xmm0     # 0xe590
mulsd 0x10(%rsp), %xmm0
leaq 0x4553(%rip), %rsi      # 0xe706
movl %ebx, %edx
movl %ebp, %ecx
movsd (%rsp), %xmm1
movapd %xmm3, %xmm2
movb $0x3, %al
callq 0x32a0
movsd 0x8(%rsp), %xmm3
andl $0x0, 0x810c(%rip)      # 0x122e0
movsd 0x43bc(%rip), %xmm4     # 0xe598
movapd %xmm3, %xmm2
mulsd %xmm4, %xmm2
movsd 0x43b4(%rip), %xmm0     # 0xe5a0
movsd 0x80f4(%rip), %xmm1     # 0x122e8
mulsd %xmm0, %xmm1
addsd %xmm2, %xmm1
movsd %xmm1, 0x80e4(%rip)     # 0x122e8
movapd %xmm3, %xmm2
subsd %xmm1, %xmm2
mulsd %xmm2, %xmm2
mulsd 0x80d8(%rip), %xmm0     # 0x122f0
mulsd %xmm4, %xmm2
addsd %xmm2, %xmm0
movsd %xmm0, 0x80c8(%rip)     # 0x122f0
testl %r14d, %r14d
jne 0xa36c
leaq 0x8d90(%rip), %rax      # 0x12fc8
movq (%rax), %r14
xorpd %xmm2, %xmm2
ucomisd %xmm2, %xmm0
jb 0xa32e
sqrtsd %xmm0, %xmm2
jmp 0xa349
xorl %eax, %eax
cmpq $0x100, %rax            # imm = 0x100
jae 0xa271
movl 0x24(%rsp,%rax,4), %ecx
addl 0x20(%rsp,%rax,4), %ecx
cmpl %r15d, %ecx
cmovgl %ecx, %r15d
addq $0x2, %rax
jmp 0xa254
leaq 0x8d50(%rip), %r12      # 0x12fc8
movq (%r12), %rcx
leaq 0x4404(%rip), %rdi      # 0xe687
pushq $0x14
popq %rsi
pushq $0x1
popq %rdx
callq 0x34b0
movl %r15d, %eax
shrl %eax
movl %eax, (%rsp)
xorl %ebx, %ebx
pushq $0x1
popq %r14
movl %r14d, %ebp
cmpl $0xff, %ebx
jg 0x9fa2
cmpl $0x1a, %ebx
jne 0xa2ce
movq (%r12), %rcx
leaq 0x43e1(%rip), %rdi      # 0xe69c
pushq $0xc
popq %rsi
pushq $0x1
popq %rdx
callq 0x34b0
movl $0xd2, %ebx
movl %r14d, %ebp
movslq %ebx, %rax
movl 0x20(%rsp,%rax,4), %ecx
movl 0x24(%rsp,%rax,4), %r8d
leal (%r8,%rcx), %r13d
testl %ebp, %ebp
je 0xa2ea
movl %r14d, %ebp
testl %r13d, %r13d
je 0xa326
movq (%r12), %rdi
xorl %ebp, %ebp
leaq 0x43b2(%rip), %rsi      # 0xe6a9
movl %ebx, %edx
xorl %eax, %eax
callq 0x32a0
movq (%r12), %rdi
imull $0x32, %r13d, %eax
addl (%rsp), %eax
cltd
idivl %r15d
leaq 0x43ea(%rip), %rsi      # 0xe700
movl %eax, %edx
leaq 0x4397(%rip), %rcx      # 0xe6b6
xorl %eax, %eax
callq 0x32a0
addl $0x2, %ebx
jmp 0xa29f
movsd %xmm1, 0x18(%rsp)
callq 0x34c0
movsd 0x18(%rsp), %xmm1
movsd 0x8(%rsp), %xmm3
movapd %xmm0, %xmm2
leaq 0x43fc(%rip), %rsi      # 0xe74c
movq %r14, %rdi
movapd %xmm3, %xmm0
movb $0x3, %al
callq 0x32a0
movsd 0x8(%rsp), %xmm3
movsd 0x7f84(%rip), %xmm0     # 0x122f0
movsd 0x4234(%rip), %xmm1     # 0xe5a8
xorl %eax, %eax
ucomisd %xmm0, %xmm1
seta %al
leaq 0x425c(%rip), %rcx      # 0xe5e0
movsd (%rcx,%rax,8), %xmm0
ucomisd %xmm0, %xmm3
jb 0xa398
testb $0x1, 0xb7a6(%rip)      # 0x15b3c
je 0xa3bd
movsd 0x2368(%rip), %xmm1     # 0xc708
divsd %xmm0, %xmm1
xorl %eax, %eax
ucomisd %xmm3, %xmm1
jb 0xa45e
testb $0x1, 0xb781(%rip)      # 0x15b38
jne 0xa45e
leaq 0x8c04(%rip), %r14      # 0x12fc8
movq (%r14), %rdi
movsd 0x10(%rsp), %xmm0
mulsd 0x41bb(%rip), %xmm0     # 0xe590
leaq 0x4392(%rip), %rsi      # 0xe76e
movl %ebx, %edx
movl %ebp, %ecx
movapd %xmm3, %xmm1
movb $0x2, %al
callq 0x32a0
andl $0x0, 0x7eee(%rip)      # 0x122e0
movq (%r14), %rdi
cvtss2sd 0x1080(%r12), %xmm0
leaq 0x43a1(%rip), %rsi      # 0xe7a7
movb $0x1, %al
callq 0x32a0
movq (%r14), %rdi
movl 0x10a8(%r12), %edx
leaq 0x43a7(%rip), %rsi      # 0xe7c6
movsd (%rsp), %xmm0
movb $0x1, %al
callq 0x32a0
movsd 0x8(%rsp), %xmm0
mulsd (%rsp), %xmm0
movsd %xmm0, 0x7e9a(%rip)     # 0x122d8
callq 0x9bf8
movabsq $0x3ff0000000000000, %rax # imm = 0x3FF0000000000000
movq %rax, 0x7e94(%rip)      # 0x122e8
movq %rax, 0x7e95(%rip)      # 0x122f0
movl %r15d, %eax
addq $0x428, %rsp            # imm = 0x428
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq