Source

Magic Lantern / src / shoot.c

Full commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
/** \file
 * Shooting experiments: intervalometer, LCD RemoteShot. More to come.
 * 
 * (C) 2010 Alex Dumitrache, broscutamaker@gmail.com
 */
/*
 * Magic Lantern is Copyright (C) 2009 Trammell Hudson <hudson+ml@osresearch.net>
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

#include "dryos.h"
#include "bmp.h"
#include "version.h"
#include "config.h"
#include "menu.h"
#include "property.h"
#include "lens.h"
#include "gui.h"
#include "math.h"

#if defined(CONFIG_MODULES)
#include "module.h"
#endif

static CONFIG_INT( "shoot.num", pics_to_take_at_once, 0);
static CONFIG_INT( "shoot.af",  shoot_use_af, 0 );
static int snap_sim = 0;

void move_lv_afframe(int dx, int dy);
void movie_start();
void movie_end();
void display_trap_focus_info();
void display_lcd_remote_icon(int x0, int y0);
void intervalometer_stop();
void get_out_of_play_mode(int extra_wait);
void wait_till_next_second();
void zoom_sharpen_step();
void zoom_auto_exposure_step();
static void ensure_play_or_qr_mode_after_shot();
void take_fast_pictures( int number );

static void bulb_ramping_showinfo();
static int is_bulb_mode_or_bulb_ramping();
int bulb_ramp_calibration_running = 0;

#if  !defined(AUDIO_REM_SHOT_POS_X) && !defined(AUDIO_REM_SHOT_POS_Y)
    #define AUDIO_REM_SHOT_POS_X 20
    #define AUDIO_REM_SHOT_POS_Y 40
#endif

int display_idle()
{
    extern thunk ShootOlcApp_handler;
    if (lv) return liveview_display_idle();
    else return gui_state == GUISTATE_IDLE && !gui_menu_shown() &&
        ((!DISPLAY_IS_ON && CURRENT_DIALOG_MAYBE == 0) || (intptr_t)get_current_dialog_handler() == (intptr_t)&ShootOlcApp_handler);
}

#ifndef CONFIG_5D3
static char dcim_dir_suffix[6];
static char dcim_dir[100];
PROP_HANDLER(PROP_DCIM_DIR_SUFFIX)
{
    snprintf(dcim_dir_suffix, sizeof(dcim_dir_suffix), (const char *)buf);
}
const char* get_dcim_dir()
{
    snprintf(dcim_dir, sizeof(dcim_dir), CARD_DRIVE "DCIM/%03d%s", folder_number, dcim_dir_suffix);
    return dcim_dir;
}
#endif

static float bulb_shutter_valuef = 1.0;
#define BULB_SHUTTER_VALUE_MS (int)roundf(bulb_shutter_valuef * 1000.0f)
#define BULB_SHUTTER_VALUE_S (int)roundf(bulb_shutter_valuef)

int get_bulb_shutter_raw_equiv()
{
    return shutterf_to_raw(bulb_shutter_valuef);
}

int uniwb_is_active() 
{
    return 
        lens_info.wb_mode == WB_CUSTOM &&
        ABS((int)lens_info.WBGain_R - 1024) < 100 &&
        ABS((int)lens_info.WBGain_G - 1024) < 100 &&
        ABS((int)lens_info.WBGain_B - 1024) < 100;
}

/*
static CONFIG_INT("uniwb.mode", uniwb_mode, 0);
static CONFIG_INT("uniwb.old.wb_mode", uniwb_old_wb_mode, 0);
static CONFIG_INT("uniwb.old.gain_R", uniwb_old_gain_R, 0);
static CONFIG_INT("uniwb.old.gain_G", uniwb_old_gain_G, 0);
static CONFIG_INT("uniwb.old.gain_B", uniwb_old_gain_B, 0);

int uniwb_is_active() 
{
    return 
        uniwb_mode &&
        uniwb_is_active_check_lensinfo_only();
}*/

//~ CONFIG_INT("iso_selection", iso_selection, 0);

CONFIG_INT("hdr.enabled", hdr_enabled, 0);

static PROP_INT(PROP_AEB, aeb_setting);
#ifdef FEATURE_HDR_BRACKETING
#define HDR_ENABLED (hdr_enabled && !aeb_setting) // when Canon bracketing is active, ML bracketing should not run
#else
#define HDR_ENABLED 0
#endif

static CONFIG_INT("hdr.type", hdr_type, 0); // exposure, aperture, flash
CONFIG_INT("hdr.frames", hdr_steps, 1);
CONFIG_INT("hdr.ev_spacing", hdr_stepsize, 16);
static CONFIG_INT("hdr.delay", hdr_delay, 1);
static CONFIG_INT("hdr.seq", hdr_sequence, 1);
static CONFIG_INT("hdr.iso", hdr_iso, 0);
static CONFIG_INT("hdr.scripts", hdr_scripts, 0); //1 enfuse, 2 align+enfuse, 3 only list images

static CONFIG_INT( "interval.timer.index", interval_timer_index, 10 );
static CONFIG_INT( "interval.start.timer.index", interval_start_timer_index, 3 );
static CONFIG_INT( "interval.stop.after", interval_stop_after, 0 );
//~ static CONFIG_INT( "interval.stop.after", interval_stop_after, 0 );

static int intervalometer_pictures_taken = 0;
static int intervalometer_next_shot_time = 0;


#define TRAP_NONE    0
#define TRAP_ERR_CFN 1
#define TRAP_IDLE    2
#define TRAP_ACTIVE  3
static uint32_t trap_focus_continuous_state = 0;
static uint32_t trap_focus_msg = 0;

CONFIG_INT( "focus.trap", trap_focus, 0);
//~ CONFIG_INT( "focus.trap.numpics", trap_focus_shoot_numpics, 1);
static CONFIG_INT( "audio.release-level", audio_release_level, 10);
static CONFIG_INT( "flash_and_no_flash", flash_and_no_flash, 0);
static CONFIG_INT( "lv_3rd_party_flash", lv_3rd_party_flash, 0);

static CONFIG_INT( "silent.pic", silent_pic_enabled, 0 );
static CONFIG_INT( "silent.pic.jpeg", silent_pic_jpeg, 0 );
static CONFIG_INT( "silent.pic.mode", silent_pic_mode, 0 );    // 0 = normal, 1 = burst, 2 = continuous, 3 = hi-res
static CONFIG_INT( "silent.pic.highres", silent_pic_highres, 0);   // index of matrix size (2x1 .. 5x5)
static CONFIG_INT( "silent.pic.sweepdelay", silent_pic_sweepdelay, 350);

//~ static CONFIG_INT( "zoom.enable.face", zoom_enable_face, 0);
static CONFIG_INT( "zoom.disable.x5", zoom_disable_x5, 0);
static CONFIG_INT( "zoom.disable.x10", zoom_disable_x10, 0);
static CONFIG_INT( "zoom.sharpen", zoom_sharpen, 0);
static CONFIG_INT( "zoom.halfshutter", zoom_halfshutter, 0);
static CONFIG_INT( "zoom.focus_ring", zoom_focus_ring, 0);
       CONFIG_INT( "zoom.auto.exposure", zoom_auto_exposure, 0);
static CONFIG_INT( "bulb.timer", bulb_timer, 0);
static CONFIG_INT( "bulb.duration.index", bulb_duration_index, 5);
static CONFIG_INT( "mlu.auto", mlu_auto, 0);
static CONFIG_INT( "mlu.mode", mlu_mode, 1);

#define MLU_ALWAYS_ON (mlu_auto && mlu_mode == 0)
#define MLU_SELF_TIMER (mlu_auto && mlu_mode == 1)
#define MLU_HANDHELD (mlu_auto && mlu_mode == 2)
static int mlu_handled_debug = 0;

#ifndef CONFIG_5DC
static CONFIG_INT("mlu.handheld.delay", mlu_handheld_delay, 4);
static CONFIG_INT("mlu.handheld.shutter", mlu_handheld_shutter, 1); // restrict it to shutter speeds where the improvement is noticeable
#else
#define mlu_handheld_shutter 0
#endif

extern int lcd_release_running;
extern int lens_mlu_delay;

//New option for the sensitivty of the motion release
static CONFIG_INT( "motion.release-level", motion_detect_level, 8);
static CONFIG_INT( "motion.delay", motion_detect_delay, 0);
static CONFIG_INT( "motion.trigger", motion_detect_trigger, 0);
static CONFIG_INT( "motion.dsize", motion_detect_size, 1);
static CONFIG_INT( "motion.position", motion_detect_position, 0);

int get_silent_pic() { return silent_pic_enabled; } // silent pic will disable trap focus

//~ static CONFIG_INT("bulb.ramping", bulb_ramping_enabled, 0);
static CONFIG_INT("bulb.ramping.mode", bramp_auto_exposure, 0);
//~ static CONFIG_INT("bulb.ramping.auto.speed", bramp_auto_ramp_speed, 100); // max 0.1 EV/shot
//~ static CONFIG_INT("bulb.ramping.smooth", bramp_auto_smooth, 50);
static CONFIG_INT("bulb.ramping.percentile", bramp_percentile, 50);
static CONFIG_INT("bulb.ramping.man.expo", bramp_manual_speed_evx1000_per_shot, 0);
static CONFIG_INT("bulb.ramping.man.focus", bramp_manual_speed_focus_steps_per_shot, 0);


#define BRAMP_FEEDBACK_LOOP     (bramp_auto_exposure == 1) // smooth exposure changes
#define BRAMP_LRT_HOLY_GRAIL    (bramp_auto_exposure == 2) // only apply integer EV correction
#define BRAMP_LRT_HOLY_GRAIL_STOPS 1


#define BULB_EXPOSURE_CONTROL_ACTIVE (intervalometer_running && (bramp_auto_exposure || bramp_manual_speed_evx1000_per_shot))

static int intervalometer_running = 0;
int is_intervalometer_running() { return intervalometer_running; }
int motion_detect = 0; //int motion_detect_level = 8;
#ifdef FEATURE_AUDIO_REMOTE_SHOT
static int audio_release_running = 0;
#endif

static int timer_values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 25, 26, 27, 28, 29, 30, 35, 40, 45, 50, 55, 60, 70, 80, 90, 100, 110, 120, 135, 150, 165, 180, 195, 210, 225, 240, 270, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900, 1200, 1800, 2700, 3600, 5400, 7200, 9000, 10800, 14400, 18000, 21600, 25200, 28800};

static const char* format_time_hours_minutes_seconds(int seconds)
{
    static char msg[50];
    
    msg[0] = '\0';
    if (seconds >= 3600) 
    { 
        STR_APPEND(msg, "%dh", seconds / 3600); 
        seconds = seconds % 3600;
    }

    if (seconds >= 60) 
    { 
        STR_APPEND(msg, "%dm", seconds / 60); 
        seconds = seconds % 60;
    }

    if (seconds || !msg[0])
    {
        STR_APPEND(msg, "%ds", seconds);
    }
    
    return msg;
}

static void seconds_clock_update();

static volatile int seconds_clock = 0;
int get_seconds_clock() { return seconds_clock; } 

static volatile int ms100_clock = 0;
int get_ms_clock_value() { seconds_clock_update(); return ms100_clock; }

int get_ms_clock_value_fast() { return ms100_clock; } // fast, but less accurate

/**
 * useful for things that shouldn't be done more often than X ms
 * 
 * for example:

   int aux;
   for (int i = 0; i < 1000; i++)
   {
       process(i);
       if (should_run_polling_action(500, &aux)) 
           NotifyBox(1000, "Progress: %d/%d ", i, 1000);
   }

   or:

   void process_step() // called periodically
   {
       do_one_iteration();
       
       static int aux = 0;
       if (should_run_polling_action(500, &aux)) 
           NotifyBox(1000, "some progress update");
   }

 */
int should_run_polling_action(int period_ms, int* last_updated_time)
{
    if (ms100_clock >= (*last_updated_time) + period_ms)
    {
        *last_updated_time = ms100_clock;
        return 1;
    }
    return 0;
}

static void do_this_every_second() // called every second
{
    #ifdef FEATURE_BULB_RAMPING
    if (BULB_EXPOSURE_CONTROL_ACTIVE && !gui_menu_shown())
        bulb_ramping_showinfo();
    #endif

    #ifdef FEATURE_INTERVALOMETER
    if (intervalometer_running && lens_info.job_state == 0 && !gui_menu_shown() && !get_halfshutter_pressed())
        info_led_blink(1, 50, 0);
    #endif

    #ifdef CONFIG_BATTERY_INFO
    RefreshBatteryLevel_1Hz();
    #endif
    
    reset_pre_shutdown_flag_step();
    
    #ifdef FEATURE_SHOW_CPU_USAGE
    task_update_loads();
    #endif

    #ifdef CONFIG_TSKMON
    tskmon_stack_check_all();
    #endif
    
    #ifdef FEATURE_SHOW_OVERLAY_FPS
    static int k = 0; k++;
    if (k%10 == 0) update_lv_fps();
    #endif
}

static struct semaphore * seconds_clock_sem;
// called every 200ms or on request
static void
seconds_clock_update()
{
    take_semaphore(seconds_clock_sem, 0);
    
    static int rollovers = 0;
    static int prev_t = 0;
    int t = *(volatile uint32_t*)0xC0242014;
    // this timer rolls over every 1048576 ticks
    // and 1000000 ticks = 1 second
    // so 1 rollover is done every 1.05 seconds roughly
    
    if (t < prev_t)
        rollovers++;
    prev_t = t;
    
    // float s_clock_f = rollovers * 1048576.0 / 1000000.0 + t / 1048576.0;
    // not very precise but... should be OK (1.11 seconds error in 24 hours)
    ms100_clock = rollovers * 16777 / 16 + t * 1000 / 1048576;
    seconds_clock = ms100_clock / 1000;
    
    give_semaphore(seconds_clock_sem);
}

static void
seconds_clock_task( void* unused )
{
    TASK_LOOP 
    {
        seconds_clock_update();
        
        static int prev_s_clock = 0;
        if (prev_s_clock != seconds_clock)
        {
#if defined(CONFIG_MODULES)
            module_exec_cbr(CBR_SECONDS_CLOCK);
#endif
            do_this_every_second();
            prev_s_clock = seconds_clock;
        }

        msleep(200);
    }
}
TASK_CREATE( "clock_task", seconds_clock_task, 0, 0x19, 0x2000 );


typedef int (*CritFunc)(int);
// crit returns negative if the tested value is too high, positive if too low, 0 if perfect
int bin_search(int lo, int hi, CritFunc crit)
{
    ASSERT(crit);
    if (lo >= hi-1) return lo;
    int m = (lo+hi)/2;
    int c = crit(m);
    if (c == 0) return m;
    if (c > 0) return bin_search(m, hi, crit);
    return bin_search(lo, m, crit);
}

static int get_exposure_time_ms()
{
    if (is_bulb_mode_or_bulb_ramping()) return BULB_SHUTTER_VALUE_MS;
    else return raw2shutter_ms(lens_info.raw_shutter);
}

int get_exposure_time_raw()
{
    if (is_bulb_mode_or_bulb_ramping()) return shutterf_to_raw(bulb_shutter_valuef);
    return lens_info.raw_shutter;
}

static PROP_INT(PROP_VIDEO_SYSTEM, pal);

#ifdef FEATURE_INTERVALOMETER

static PROP_INT(PROP_AUTO_POWEROFF_TIME, auto_power_off_time)

static MENU_UPDATE_FUNC(timelapse_calc_display)
{
    int d = timer_values[interval_timer_index];
    d = MAX(d, get_exposure_time_ms()/1000);
    int total_shots = interval_stop_after ? (int)MIN((int)interval_stop_after, (int)avail_shot) : (int)avail_shot;
    int total_time_s = d * total_shots;
    int total_time_m = total_time_s / 60;
    int fps = video_mode_fps;
    if (!fps) fps = pal ? 25 : 30;
    MENU_SET_WARNING(MENU_WARN_INFO, 
        "Timelapse: %dh%02dm, %d shots, %d fps => %02dm%02ds.", 
        total_time_m / 60, 
        total_time_m % 60, 
        total_shots, fps, 
        (total_shots / fps) / 60, 
        (total_shots / fps) % 60
    );
}

static MENU_UPDATE_FUNC(interval_timer_display)
{
    int d = timer_values[CURRENT_VALUE];
    if (!d)
    {
        MENU_SET_NAME("Take pics...");
        MENU_SET_VALUE("like crazy");
    }
    else
    {
        MENU_SET_VALUE(
            format_time_hours_minutes_seconds(d)
        );
    }
    MENU_SET_ICON(MNI_PERCENT, CURRENT_VALUE * 100 / COUNT(timer_values));
    MENU_SET_ENABLED(1);

    if (auto_power_off_time && auto_power_off_time <= d)
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Check auto power off setting (currently %ds).", auto_power_off_time);

    timelapse_calc_display(entry, info);
}

static MENU_UPDATE_FUNC(interval_start_after_display)
{
    int d = timer_values[CURRENT_VALUE];
    MENU_SET_VALUE(
        format_time_hours_minutes_seconds(d)
    );

    MENU_SET_ICON(MNI_PERCENT, CURRENT_VALUE * 100 / COUNT(timer_values));
}

static MENU_UPDATE_FUNC(interval_stop_after_display)
{
    int d = CURRENT_VALUE;
    MENU_SET_VALUE(
        d ? "%d shots"
          : "%s",
        d ? d : (intptr_t) "Disabled"
    );
    MENU_SET_ENABLED(d);
    if (d > avail_shot)
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Not enough space for %d shots (only for %d).", d, avail_shot);
    timelapse_calc_display(entry, info);
}

static MENU_SELECT_FUNC(interval_timer_toggle)
{
    int * ptr = priv;

    if (priv == &interval_start_timer_index)
        *ptr = mod(*ptr + delta - 1, COUNT(timer_values) - 1) + 1;
    else
        *ptr = mod(*ptr + delta, COUNT(timer_values));
}

static MENU_UPDATE_FUNC(intervalometer_display)
{
    int p = CURRENT_VALUE;
    if (p)
    {
        int d = timer_values[interval_timer_index];
        MENU_SET_VALUE("ON, %s%s",
            format_time_hours_minutes_seconds(d),
            BULB_EXPOSURE_CONTROL_ACTIVE ? ", BRamp" : ""
        );
        
        if (auto_power_off_time && auto_power_off_time <= d)
            MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Check auto power off setting (currently %ds).", auto_power_off_time);
    }
    else
    {
        MENU_SET_VALUE("OFF");
    }

    if (shooting_mode != SHOOTMODE_M && !is_bulb_mode())
        MENU_SET_WARNING(MENU_WARN_ADVICE, "Use M mode to avoid exposure flicker.");
    else if (lens_info.raw_aperture != lens_info.raw_aperture_min)
        MENU_SET_WARNING(MENU_WARN_ADVICE, "Shoot wide-open or unscrew lens to avoid aperture flicker.");
    else if (get_exposure_time_ms() < 10)
        MENU_SET_WARNING(MENU_WARN_ADVICE, "Use slow shutter speeds to avoid shutter flicker.");
    else if (lens_info.wb_mode == 0)
        MENU_SET_WARNING(MENU_WARN_ADVICE, "Use manual white balance to avoid WB flicker.");
    else if (shoot_use_af && !is_manual_focus())
        MENU_SET_WARNING(MENU_WARN_ADVICE, "Disable autofocus.");
    else if (lens_info.IS && lens_info.IS != 8)
        MENU_SET_WARNING(MENU_WARN_ADVICE, "Disable image stabilization.");

    if (entry->selected) timelapse_calc_display(entry, info);
}
#endif

#ifdef FEATURE_BULB_RAMPING
static int get_smooth_factor_from_max_ev_speed(int speed_x1000)
{
    float ev = COERCE((float)speed_x1000 / 1000.0f, 0.001f, 0.98f);
    float f = -(ev-1) / (ev+1);
    int fi = (int)roundf(f * 100);
    return COERCE(fi, 1, 99);
}

static MENU_UPDATE_FUNC(manual_expo_ramp_print)
{
    int evx1000 = bramp_manual_speed_evx1000_per_shot;
    if (!evx1000)
    {
        MENU_SET_VALUE("OFF");
        MENU_SET_ENABLED(0);
    }
    else
    {
        MENU_SET_VALUE(
            "%s%d.%03d EV/shot",
            FMT_FIXEDPOINT3S(evx1000)
        );
        int max = log_length(1000);
        MENU_SET_ICON(MNI_PERCENT_ALLOW_OFF, 50 + log_length(ABS(evx1000)) * 50 / max * SGN(evx1000));
        
        int n = 1000 / evx1000;
        int d = timer_values[interval_timer_index];
        int total_time_s = d * n;
        int total_time_m = total_time_s / 60;
        MENU_SET_WARNING(MENU_WARN_INFO, 
            "Exposure will change by 1EV after %d shots, %02dh%02dm.", 
            n, total_time_m / 60, total_time_m % 60
        );
    }
}

static MENU_UPDATE_FUNC(manual_focus_ramp_print)
{
    int steps = bramp_manual_speed_focus_steps_per_shot;
    if (!steps)
    {
        MENU_SET_VALUE("OFF");
        MENU_SET_ENABLED(0);
    }
    else
    {
        MENU_SET_VALUE(
            "%s%d steps/shot",
            steps > 0 ? "+" : "",
            steps
        );
        int max = log_length(100);
        MENU_SET_ICON(MNI_PERCENT_ALLOW_OFF, 50 + log_length(ABS(steps)) * 50 / max * SGN(steps));
    }
}

/*
static MENU_UPDATE_FUNC(bulb_ramping_print)
{
    int evx1000 = bramp_manual_speed_evx1000_per_shot;
    int steps = bramp_manual_speed_focus_steps_per_shot;

    static char msg[100];
    msg[0] = 0;

    // try to write this as compact as possible, there's very little space in the menu
    if (!bulb_ramping_enabled)
    {
        STR_APPEND(msg, "OFF");
    }
    else
    {
        if (bramp_auto_exposure)
        {
            STR_APPEND(msg, 
                bramp_auto_exposure == 1 ? "Smooth" :
                bramp_auto_exposure == 2 ? "LRT" : "err"
            );
        }
        if (evx1000)
        {
            STR_APPEND(msg, "%s.", evx1000 >= 1000 ? "+1" : evx1000 <= -1000 ? "-1" : evx1000 > 0 ? "+" : "-");
            int r = ABS(evx1000) % 1000;
            if (r % 100 == 0)       { STR_APPEND(msg, "%01d", r / 100); }
            else if (r % 10 == 0)   { STR_APPEND(msg, "%02d", r / 10 ); }
            else                    { STR_APPEND(msg, "%03d", r      ); }
            STR_APPEND(msg, "EV/p");
        }
        if (steps)
        {
            STR_APPEND(msg, "%s%dFS", steps > 0 ? "+" : "", steps);
        }
    }
    
    MENU_SET_VALUE(msg);

    if (!bramp_auto_exposure && !evx1000 && !steps)
    {
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Nothing enabled from the submenu.");
    }

    if (!intervalometer_running)
    {
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "You also need to enable the intervalometer.");
    }
}
*/

static int ev_values[] = {-1000, -750, -500, -200, -100, -50, -20, -10, -5, -2, -1, 0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 750, 1000};

static void bramp_manual_evx1000_toggle(void* priv, int delta)
{
    int value = (int)bramp_manual_speed_evx1000_per_shot;
    int i = 0;
    for (i = 0; i < COUNT(ev_values); i++)
        if (ev_values[i] >= value) break;
    i = mod(i + delta, COUNT(ev_values));
    bramp_manual_speed_evx1000_per_shot = ev_values[i];
}

#endif

#ifdef FEATURE_AUDIO_REMOTE_SHOT
static MENU_UPDATE_FUNC(audio_release_display)
{
    if (audio_release_running)
    {
        MENU_SET_VALUE("ON, level=%d", audio_release_level);
        MENU_SET_SHORT_VALUE("%d", audio_release_level);
    }
}
#endif

#ifdef FEATURE_MOTION_DETECT
//GUI Functions for the motion detect sensitivity.  
static MENU_UPDATE_FUNC(motion_detect_display)
{
    if (motion_detect) 
    {
        MENU_SET_VALUE(
            "%s, level=%d",
            motion_detect_trigger == 0 ? "EXP" : motion_detect_trigger == 1 ? "DIF" : "STDY",
            motion_detect_level
        );
        MENU_SET_SHORT_VALUE(
            "%s,%d",
            motion_detect_trigger == 0 ? "EXP" : motion_detect_trigger == 1 ? "DIF" : "STDY",
            motion_detect_level
        );
    }
    
    if (motion_detect_trigger == 2) 
        MENU_SET_WARNING(MENU_WARN_ADVICE, "Press shutter halfway and be careful (tricky feature).");

    if (motion_detect_trigger < 2 && !lv)
        MENU_SET_WARNING(MENU_WARN_ADVICE, "With current settings, motion detect only works in LiveView.");
}
#endif

int get_trap_focus() { return trap_focus; }

#if defined(CONFIG_PHOTO_MODE_INFO_DISPLAY)
static void double_buffering_start(int ytop, int height)
{
    // use double buffering to avoid flicker
    bmp_vram(); // make sure parameters are up to date
    ytop = MIN(ytop, BMP_H_PLUS - height);
    memcpy(bmp_vram_idle() + BM(0,ytop), bmp_vram_real() + BM(0,ytop), height * BMPPITCH);
    bmp_draw_to_idle(1);
}

static void double_buffering_end(int ytop, int height)
{
    // done drawing, copy image to main BMP buffer
    bmp_draw_to_idle(0);
    bmp_vram(); // make sure parameters are up to date
    ytop = MIN(ytop, BMP_H_PLUS - height);
    memcpy(bmp_vram_real() + BM(0,ytop), bmp_vram_idle() + BM(0,ytop), height * BMPPITCH);
    bzero32(bmp_vram_idle() + BM(0,ytop), height * BMPPITCH);
}
#endif

void set_flash_firing(int mode)
{
    lens_wait_readytotakepic(64);
    mode = COERCE(mode, 0, 2);
    prop_request_change(PROP_STROBO_FIRING, &mode, 4);
}

#ifdef FEATURE_FLASH_TWEAKS
static MENU_UPDATE_FUNC(flash_and_no_flash_display)
{
    if (strobo_firing == 2)
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Flash is automatic, can't adjust.");
}

#endif

#ifdef FEATURE_SILENT_PIC
                                                 //2  4  6  9 12 16 20 25
static const int16_t silent_pic_sweep_modes_l[] = {2, 2, 2, 3, 3, 4, 4, 5};
static const int16_t silent_pic_sweep_modes_c[] = {1, 2, 3, 3, 4, 4, 5, 5};
#define SILENTPIC_NL COERCE(silent_pic_sweep_modes_l[COERCE(silent_pic_highres,0,COUNT(silent_pic_sweep_modes_l)-1)], 0, 5)
#define SILENTPIC_NC COERCE(silent_pic_sweep_modes_c[COERCE(silent_pic_highres,0,COUNT(silent_pic_sweep_modes_c)-1)], 0, 5)

#ifdef FEATURE_SILENT_PIC_HIRES
static int silent_pic_hires_check() // should match the warnings below
{
    if (
            (is_movie_mode() && video_mode_crop) ||
            ((SILENTPIC_NL > 4 || SILENTPIC_NC > 4) && !is_manual_focus()) ||
        0)
            return 0;
    return 1;
}
static MENU_UPDATE_FUNC(silent_pic_check_highres_warnings)
{
    if (silent_pic_mode != 3)
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Hi-res mode disabled.");
    else if (is_movie_mode() && video_mode_crop)
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Hi-res silent pictures won't work in crop mode.");
    else if ((SILENTPIC_NL > 4 || SILENTPIC_NC > 4) && !is_manual_focus())
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Matrices higher than 4x4 require manual focus."); 
    else if (!is_movie_mode())
        MENU_SET_WARNING(MENU_WARN_ADVICE, "Hi-res works best in movie mode (not photo mode).");
    else
        MENU_SET_WARNING(MENU_WARN_INFO, "Resolution: %dx%d", SILENTPIC_NC*(1024-8), SILENTPIC_NL*(680-8));
}
#endif

static MENU_UPDATE_FUNC(silent_pic_display)
{
    #ifdef FEATURE_SILENT_PIC_HIRES
    if (silent_pic_mode == 3)
        silent_pic_check_highres_warnings(entry, info); // show warnings, if any
    #endif
    
    if (!silent_pic_enabled)
        return;
    
    switch(silent_pic_mode)
    {
        case 0:
            MENU_SET_VALUE("Simple" );
            break;
            
        case 1:
            MENU_SET_VALUE("Burst" );
            break;
            
        case 2:
            MENU_SET_VALUE("Continuous" );
            break;
            
        case 3:
            MENU_SET_VALUE("HiRes, %dx%d",
                SILENTPIC_NL,
                SILENTPIC_NC
            );
            break;
    }
}

#endif //#ifdef FEATURE_SILENT_PIC

static volatile int afframe_ack = 0;
#ifdef CONFIG_LIVEVIEW
static int afframe[128];
PROP_HANDLER( PROP_LV_AFFRAME ) {
    ASSERT(len <= sizeof(afframe));

    #ifdef FEATURE_SPOTMETER
    spotmeter_erase();
    #endif

    crop_set_dirty(10);
    afframe_set_dirty();
    
    memcpy(afframe, buf, len);
    afframe_ack = 1;
}
#else
static int afframe[100]; // dummy
#endif

void get_afframe_pos(int W, int H, int* x, int* y)
{
    *x = (afframe[2] + afframe[4]/2) * W / afframe[0];
    *y = (afframe[3] + afframe[5]/2) * H / afframe[1];
}

#ifdef FEATURE_LV_ZOOM_SETTINGS
PROP_HANDLER( PROP_HALF_SHUTTER ) {
    zoom_sharpen_step();
    zoom_auto_exposure_step();
}

static int zoom_was_triggered_by_halfshutter = 0;

PROP_HANDLER(PROP_LV_DISPSIZE)
{
#if defined(CONFIG_6D) 
ASSERT(buf[0] == 1 || buf[0]==129 || buf[0] == 5 || buf[0] == 10);
   
#else
   ASSERT(buf[0] == 1 || buf[0] == 5 || buf[0] == 10);
#endif    
    zoom_sharpen_step();
    zoom_auto_exposure_step();
    
    if (buf[0] == 1) zoom_was_triggered_by_halfshutter = 0;
}
#endif // FEATURE_LV_ZOOM_SETTINGS

void set_lv_zoom(int zoom)
{
    if (!lv) return;
    if (recording) return;
    if (is_movie_mode() && video_mode_crop) return;
    zoom = COERCE(zoom, 1, 10);
    if (zoom > 1 && zoom < 10) zoom = 5;
    prop_request_change(PROP_LV_DISPSIZE, &zoom, 4);
}

int get_mlu_delay(int raw)
{
    return 
        raw == 6 ? 750 : 
        raw >= 7 ? (raw - 6) * 1000 : 
                   raw * 100;
}

#ifdef FEATURE_MLU_HANDHELD
static void mlu_take_pic()
{
    #if defined(CONFIG_5D2) || defined(CONFIG_50D) // not sure about 7D
    SW1(1,00);
    SW2(1,250);
    SW2(0,50);
    SW1(0,50);
    #elif defined(CONFIG_40D)
    call("FA_Release");
    #else
    call("Release"); // new cameras (including 500D)
    #endif
}

static int mlu_shake_running = 0;
static void mlu_shake_task()
{
    #ifdef FEATURE_MLU_HANDHELD_DEBUG
    if (mlu_handled_debug) { msleep(1000); NotifyBox(5000, "Taking pic..."); msleep(1000); }
    #endif

    //~ beep();
    msleep(get_mlu_delay(mlu_handheld_delay));
    SW1(0,0); SW2(0,0);
    mlu_take_pic();
    mlu_shake_running = 0;
}

#ifdef FEATURE_MLU_HANDHELD_DEBUG
static char mlu_msg[1000] = "";
#endif

int handle_mlu_handheld(struct event * event)
{
    if (MLU_HANDHELD && !lv)
    {
        extern int ml_taking_pic;
        if (ml_taking_pic) return 1; // do not use this feature for pictures initiated by ML code
        if (HDR_ENABLED) return 1; // may interfere with HDR bracketing
        if (trap_focus) return 1; // may not play nice with trap focus
        if (is_bulb_mode()) return 1; // not good in bulb mode
        if (aeb_setting) return 1; // not working with Canon bracketing

        #ifdef FEATURE_MLU_HANDHELD_DEBUG
        if (mlu_handled_debug && event->param == GMT_OLC_INFO_CHANGED)
        {
            STR_APPEND(mlu_msg, "%8x ", MEM(event->obj));
            static int k = 0; k++;
            if (k % 5 == 0) { STR_APPEND(mlu_msg, "\n"); }
        }
        #endif
        
        if (event->param == GMT_OLC_INFO_CHANGED 
            && ((MEM(event->obj) & 0x00FFF001) == 0x80001) // OK on 5D3, 5D2, 550D, 600D, 500D, maybe others
            && !mlu_shake_running)
        {
            mlu_shake_running = 1;
            task_create("mlu_pic", 0x1a, 0x1000, mlu_shake_task, 0);
            return 1;
        }
        
        static int mlu_should_be_cleared = 0;
        if (event->param == BGMT_PRESS_HALFSHUTTER)
        {
            if (mlu_handheld_shutter && (lens_info.raw_shutter < 64 || lens_info.raw_shutter > 112)) // 1/2 ... 1/125
                return 1;
            
            if (!get_mlu()) 
            { 
                info_led_on();
                mlu_should_be_cleared = 1; 
                set_mlu(1);
            }
        }

        if (event->param == BGMT_UNPRESS_HALFSHUTTER && mlu_should_be_cleared)
        {
            if (get_mlu()) set_mlu(0);
            mlu_should_be_cleared = 0;
            info_led_off();
        }
    }
    return 1;
}
#endif // FEATURE_MLU_HANDHELD

#ifdef FEATURE_LV_FOCUS_BOX_SNAP
extern int focus_box_lv_jump;

static int center_lv_aff = 0;
void center_lv_afframe()
{
    center_lv_aff = 1;
}
void center_lv_afframe_do()
{
#ifdef CONFIG_LIVEVIEW
    if (!lv || gui_menu_shown() || gui_state != GUISTATE_IDLE) return;

    int pos_x[9];
    int pos_y[9];
    
    int n = 
        focus_box_lv_jump == 0 ? 1 :
        focus_box_lv_jump == 1 ? 3 :
        focus_box_lv_jump == 2 ? 5 :
        focus_box_lv_jump == 3 ? 5 :
                             9 ;

    int W = afframe[0];
    int H = afframe[1];
    int Xtl = afframe[2];
    int Ytl = afframe[3];
    int w = afframe[4];
    int h = afframe[5];

    // center position
    pos_x[0] = W/2;
    pos_y[0] = H/2;
    
    if (focus_box_lv_jump == 1)
    {
        // top
        pos_x[1] = W / 2;
        pos_y[1] = H*2/8;
        // right
        pos_x[2] = W*6/8;
        pos_y[2] = H / 2;
    }
    else if (focus_box_lv_jump == 2)
    {
        // top
        pos_x[1] = W / 2;
        pos_y[1] = H*2/8;
        // right
        pos_x[2] = W*6/8;
        pos_y[2] = H / 2;
        // bottom
        pos_x[3] = W / 2;
        pos_y[3] = H*6/8;
        // left
        pos_x[4] = W*2/8;
        pos_y[4] = H / 2;
    }
    else if (focus_box_lv_jump == 3)
    {
        // top left
        pos_x[1] = W*2/6;
        pos_y[1] = H*2/6;
        // top right
        pos_x[2] = W*4/6;
        pos_y[2] = H*2/6;
        // bottom right
        pos_x[3] = W*4/6;
        pos_y[3] = H*4/6;
        // bottom left
        pos_x[4] = W*2/6;
        pos_y[4] = H*4/6;
    }
    else if (focus_box_lv_jump == 4)
    {
        // top left
        pos_x[1] = W*2/6;
        pos_y[1] = H*2/6;
        // top
        pos_x[2] = W / 2;
        pos_y[2] = H*2/8;
        // top right
        pos_x[3] = W*4/6;
        pos_y[3] = H*2/6;
        // right
        pos_x[4] = W*6/8;
        pos_y[4] = H / 2;
        // bottom right
        pos_x[5] = W*4/6;
        pos_y[5] = H*4/6;
        // bottom
        pos_x[6] = W / 2;
        pos_y[6] = H*6/8;
        // bottom left
        pos_x[7] = W*2/6;
        pos_y[7] = H*4/6;
        // left
        pos_x[8] = W*2/8;
        pos_y[8] = H / 2;
    }
    
    // now let's see where we are
    int current = -1;
    int Xc = Xtl + w/2;
    int Yc = Ytl + h/2;
    for (int i = 0; i < n; i++)
    {
        if (ABS(pos_x[i] - Xc) < 200 && ABS(pos_y[i] - Yc) < 200)
            current = i;
    }
    int next = mod(current + 1, n);
    
    //~ bmp_printf(FONT_MED, 50, 50, "%d %d %d %d ", Xc, Yc, pos_x[0], pos_y[0]);
    move_lv_afframe(pos_x[next] - Xc, pos_y[next] - Yc);
#endif
}
#endif

void move_lv_afframe(int dx, int dy)
{
#ifdef CONFIG_LIVEVIEW
    if (!liveview_display_idle()) return;
    if (is_movie_mode() && video_mode_crop) return;
    if (recording && is_manual_focus()) // prop handler won't trigger, clear spotmeter 
        clear_lv_afframe();
    
    static int aff[128];
    memcpy(aff, afframe, sizeof(aff));

    aff[2] = COERCE(aff[2] + dx, 500, aff[0] - aff[4]);
    aff[3] = COERCE(aff[3] + dy, 500, aff[1] - aff[5]);

    // some cameras apply an offset to X position, when AF is on (not quite predictable)
    // e.g. 60D and 5D2 apply the offset in AF mode, 550D doesn't seem to apply any
    // so... we'll try to guess this offset and compensate for this quirk
    int af = !is_manual_focus();
    static int off_x = 0;

    int x1 = aff[2];
    if (af) aff[2] -= off_x;
    afframe_ack = 0;
    prop_request_change(PROP_LV_AFFRAME, aff, 0);
    if (af)
    {
        for (int i = 0; i < 15; i++)
        {
            msleep(20);
            if (afframe_ack) break;
        }
        int x2 = afframe[2];
        if (afframe_ack && ABS(x2 - x1) > 160) // the focus box didn't quite end up where we wanted, so... adjust the offset and try again
        {
            int delta = (x2 - x1);
            off_x += delta;
            aff[2] = x1 - off_x;
            prop_request_change(PROP_LV_AFFRAME, aff, 0);
        }
    }
    
#endif
}

#ifdef FEATURE_SILENT_PIC
static char* silent_pic_get_name()
{
    static char imgname[100];
    static int silent_number = 1; // cache this number for speed (so it won't check all files until 10000 to find the next free number)
    
    static int prev_file_number = -1;
    static int prev_folder_number = -1;
    
    char *extension = "422";
#ifdef FEATURE_SILENT_PIC_RAW
    extension = "DNG";
#endif
    
#ifdef FEATURE_SILENT_PIC_JPG
    if(silent_pic_jpeg)
    {
        extension = "jpg";
    }
#endif
    
    if (prev_file_number != file_number) silent_number = 1;
    if (prev_folder_number != folder_number) silent_number = 1;
    
    prev_file_number = file_number;
    prev_folder_number = folder_number;
    
    if (intervalometer_running)
    {
        for ( ; silent_number < 100000000; silent_number++)
        {
            snprintf(imgname, sizeof(imgname), "%s/%08d.%s", get_dcim_dir(), silent_number, extension);
            uint32_t size;
            if( FIO_GetFileSize( imgname, &size ) != 0 ) break;
            if (size == 0) break;
        }
    }
    else
    {
        for ( ; silent_number < 10000; silent_number++)
        {
            snprintf(imgname, sizeof(imgname), "%s/%04d%04d.%s", get_dcim_dir(), file_number, silent_number, extension);
            uint32_t size;
            if( FIO_GetFileSize( imgname, &size ) != 0 ) break;
            if (size == 0) break;
        }
    }
    bmp_printf(FONT_MED, 0, 35, "%s    ", imgname);
    return imgname;
}
#endif

int compute_signature(int* start, int num)
{
    int c = 0;
    int* p;
    for (p = start; p < start + num; p++)
    {
        c += *p;
    }
    return c;
}

static struct semaphore * set_maindial_sem = 0;

#ifdef FEATURE_PLAY_EXPOSURE_FUSION

int expfuse_running = 0;
static int expfuse_num_images = 0;

/*
static void add_yuv_acc16bit_src8bit(void* acc, void* src, int numpix)
{
    ASSERT(acc);
    ASSERT(src);
    int16_t* accs = acc;
    uint16_t* accu = acc;
    int8_t* srcs = src;
    uint8_t* srcu = src;
    int i;
    for (i = 0; i < numpix; i++)
    {
        accs[i*2] += srcs[i*2]; // chroma, signed
        accu[i*2+1] += srcu[i*2+1]; // luma, unsigned
    }
}*/

/*static void div_yuv_by_const_dst8bit_src16bit(void* dst, void* src, int numpix, int den)
{
    ASSERT(dst);
    ASSERT(src);
    int8_t* dsts = dst;
    uint8_t* dstu = dst;
    int16_t* srcs = src;
    uint16_t* srcu = src;
    int i;
    for (i = 0; i < numpix; i++)
    {
        dsts[i*2] = srcs[i*2] / den; // chroma, signed
        dstu[i*2+1] = srcu[i*2+1] / den; // luma, unsigned
    }
}*/

// octave:
// x = linspace(0,1,256);
// f = @(x) exp(-(x-0.5).^2 ./ 0.32) # mean=0.5, sigma=0.4
// sprintf("0x%02x, ",f(x) * 100)
static uint8_t gauss_lut[] = {0x2d, 0x2e, 0x2e, 0x2f, 0x30, 0x30, 0x31, 0x31, 0x32, 0x32, 0x33, 0x34, 0x34, 0x35, 0x35, 0x36, 0x37, 0x37, 0x38, 0x38, 0x39, 0x39, 0x3a, 0x3b, 0x3b, 0x3c, 0x3c, 0x3d, 0x3e, 0x3e, 0x3f, 0x3f, 0x40, 0x41, 0x41, 0x42, 0x42, 0x43, 0x44, 0x44, 0x45, 0x45, 0x46, 0x46, 0x47, 0x48, 0x48, 0x49, 0x49, 0x4a, 0x4a, 0x4b, 0x4c, 0x4c, 0x4d, 0x4d, 0x4e, 0x4e, 0x4f, 0x4f, 0x50, 0x50, 0x51, 0x51, 0x52, 0x52, 0x53, 0x53, 0x54, 0x54, 0x55, 0x55, 0x56, 0x56, 0x57, 0x57, 0x58, 0x58, 0x58, 0x59, 0x59, 0x5a, 0x5a, 0x5a, 0x5b, 0x5b, 0x5c, 0x5c, 0x5c, 0x5d, 0x5d, 0x5d, 0x5e, 0x5e, 0x5e, 0x5f, 0x5f, 0x5f, 0x5f, 0x60, 0x60, 0x60, 0x60, 0x61, 0x61, 0x61, 0x61, 0x62, 0x62, 0x62, 0x62, 0x62, 0x62, 0x62, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x62, 0x62, 0x62, 0x62, 0x62, 0x62, 0x62, 0x61, 0x61, 0x61, 0x61, 0x60, 0x60, 0x60, 0x60, 0x5f, 0x5f, 0x5f, 0x5f, 0x5e, 0x5e, 0x5e, 0x5d, 0x5d, 0x5d, 0x5c, 0x5c, 0x5c, 0x5b, 0x5b, 0x5a, 0x5a, 0x5a, 0x59, 0x59, 0x58, 0x58, 0x58, 0x57, 0x57, 0x56, 0x56, 0x55, 0x55, 0x54, 0x54, 0x53, 0x53, 0x52, 0x52, 0x51, 0x51, 0x50, 0x50, 0x4f, 0x4f, 0x4e, 0x4e, 0x4d, 0x4d, 0x4c, 0x4c, 0x4b, 0x4a, 0x4a, 0x49, 0x49, 0x48, 0x48, 0x47, 0x46, 0x46, 0x45, 0x45, 0x44, 0x44, 0x43, 0x42, 0x42, 0x41, 0x41, 0x40, 0x3f, 0x3f, 0x3e, 0x3e, 0x3d, 0x3c, 0x3c, 0x3b, 0x3b, 0x3a, 0x39, 0x39, 0x38, 0x38, 0x37, 0x37, 0x36, 0x35, 0x35, 0x34, 0x34, 0x33, 0x32, 0x32, 0x31, 0x31, 0x30, 0x30, 0x2f, 0x2e, 0x2e, 0x2d};

static void weighted_mean_yuv_init_acc32bit_ws16bit(void* acc, void* weightsum, int numpix)
{
    bzero32(acc, numpix*8);
    bzero32(weightsum, numpix*4);
}

static void weighted_mean_yuv_add_acc32bit_src8bit_ws16bit(void* acc, void* src, void* weightsum, int numpix)
{
    int32_t* accs = acc;
    uint32_t* accu = acc;
    int8_t* srcs = src;
    uint8_t* srcu = src;
    uint16_t* ws = weightsum;
    int i;
    for (i = 0; i < numpix; i++)
    {
        int w = gauss_lut[srcu[i*2+1]];
        accs[i*2] += srcs[i*2] * w; // chroma, signed
        accu[i*2+1] += srcu[i*2+1] * w; // luma, unsigned
        ws[i] += w;
    }
}

static void weighted_mean_yuv_div_dst8bit_src32bit_ws16bit(void* dst, void* src, void* weightsum, int numpix)
{
    int8_t* dsts = dst;
    uint8_t* dstu = dst;
    int32_t* srcs = src;
    uint32_t* srcu = src;
    uint16_t* ws = weightsum;
    int i;
    for (i = 0; i < numpix; i++)
    {
        int wt = ws[i];
        dsts[i*2] = srcs[i*2] / wt; // chroma, signed
        dstu[i*2+1] = COERCE(srcu[i*2+1] / wt, 0, 255); // luma, unsigned
    }
}
#endif

void next_image_in_play_mode(int dir)
{
    if (!PLAY_MODE) return;
    void* buf_lv = get_yuv422_vram()->vram;
    // ask for next image
    fake_simple_button(dir > 0 ? BGMT_WHEEL_DOWN : BGMT_WHEEL_UP);
    int k = 0;
    // wait for image buffer location to be flipped => next image was loaded
    while (get_yuv422_vram()->vram == buf_lv && k < 50) 
    {
        msleep(100);
        k++;
    }
}

#ifdef FEATURE_PLAY_COMPARE_IMAGES

void playback_compare_images_task(int dir)
{
    ASSERT(set_maindial_sem);
    take_semaphore(set_maindial_sem, 0);

    if (!PLAY_MODE) { fake_simple_button(BGMT_PLAY); msleep(500); }
    if (!PLAY_MODE) { NotifyBox(1000, "CompareImages: Not in PLAY mode"); return; }

    if (dir == 0) // reserved for intervalometer
    {
        next_image_in_play_mode(-1);
        dir = 1;
    }
    
    void* aux_buf = (void*)YUV422_HD_BUFFER_2;
    void* current_buf;
    int w = get_yuv422_vram()->width;
    int h = get_yuv422_vram()->height;
    int buf_size = w * h * 2;
    current_buf = get_yuv422_vram()->vram;
    yuv_halfcopy(aux_buf, current_buf, w, h, 1);
    next_image_in_play_mode(dir);
    current_buf = get_yuv422_vram()->vram;
    yuv_halfcopy(aux_buf, current_buf, w, h, 0);
    current_buf = get_yuv422_vram()->vram;
    memcpy(current_buf, aux_buf, buf_size);
    give_semaphore(set_maindial_sem);
}

void playback_compare_images(int dir)
{
    task_create("playcompare_task", 0x1c, 0, playback_compare_images_task, (void*)dir);
}
#endif

#ifdef FEATURE_PLAY_EXPOSURE_FUSION
void expfuse_preview_update_task(int dir)
{
    ASSERT(set_maindial_sem);
    take_semaphore(set_maindial_sem, 0);
    void* buf_acc = (void*)YUV422_HD_BUFFER_1;
    void* buf_ws  = (void*)YUV422_HD_BUFFER_2;
    void* buf_lv  = get_yuv422_vram()->vram;
    int numpix    = get_yuv422_vram()->width * get_yuv422_vram()->height;
    if (!expfuse_running)
    {
        // first image 
        weighted_mean_yuv_init_acc32bit_ws16bit(buf_acc, buf_ws, numpix);
        weighted_mean_yuv_add_acc32bit_src8bit_ws16bit(buf_acc, buf_lv, buf_ws, numpix);
        expfuse_num_images = 1;
        expfuse_running = 1;
    }
    next_image_in_play_mode(dir);
    buf_lv = get_yuv422_vram()->vram; // refresh
    // add new image

    weighted_mean_yuv_add_acc32bit_src8bit_ws16bit(buf_acc, buf_lv, buf_ws, numpix);
    weighted_mean_yuv_div_dst8bit_src32bit_ws16bit(buf_lv, buf_acc, buf_ws, numpix);
    expfuse_num_images++;
    bmp_printf(FONT_MED, 0, 0, "%d images  ", expfuse_num_images);
    //~ bmp_printf(FONT_LARGE, 0, 480 - font_large.height, "Do not press Delete!");

    give_semaphore(set_maindial_sem);
}

void expfuse_preview_update(int dir)
{
    task_create("expfuse_task", 0x1c, 0, expfuse_preview_update_task, (void*)dir);
}
#endif

#ifdef FEATURE_PLAY_EXPOSURE_ADJUST
// increase exposure: f = @(x) (1-((255-x)/255).^2)*255
// decrease exposure: g = @(x) (1-((255-x)/255).^(1/2))*255
// one iteration = roughly one stop of exposure change
//~ static const uint8_t exp_inc[256] = {0x0,0x1,0x3,0x5,0x7,0x9,0xB,0xD,0xF,0x11,0x13,0x15,0x17,0x19,0x1B,0x1D,0x1E,0x20,0x22,0x24,0x26,0x28,0x2A,0x2B,0x2D,0x2F,0x31,0x33,0x34,0x36,0x38,0x3A,0x3B,0x3D,0x3F,0x41,0x42,0x44,0x46,0x48,0x49,0x4B,0x4D,0x4E,0x50,0x52,0x53,0x55,0x56,0x58,0x5A,0x5B,0x5D,0x5E,0x60,0x62,0x63,0x65,0x66,0x68,0x69,0x6B,0x6C,0x6E,0x6F,0x71,0x72,0x74,0x75,0x77,0x78,0x7A,0x7B,0x7D,0x7E,0x7F,0x81,0x82,0x84,0x85,0x86,0x88,0x89,0x8A,0x8C,0x8D,0x8E,0x90,0x91,0x92,0x94,0x95,0x96,0x98,0x99,0x9A,0x9B,0x9D,0x9E,0x9F,0xA0,0xA1,0xA3,0xA4,0xA5,0xA6,0xA7,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF,0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD2,0xD3,0xD4,0xD5,0xD6,0xD6,0xD7,0xD8,0xD9,0xDA,0xDA,0xDB,0xDC,0xDD,0xDD,0xDE,0xDF,0xDF,0xE0,0xE1,0xE1,0xE2,0xE3,0xE3,0xE4,0xE5,0xE5,0xE6,0xE7,0xE7,0xE8,0xE8,0xE9,0xEA,0xEA,0xEB,0xEB,0xEC,0xEC,0xED,0xED,0xEE,0xEE,0xEF,0xEF,0xF0,0xF0,0xF1,0xF1,0xF2,0xF2,0xF3,0xF3,0xF3,0xF4,0xF4,0xF5,0xF5,0xF5,0xF6,0xF6,0xF7,0xF7,0xF7,0xF8,0xF8,0xF8,0xF9,0xF9,0xF9,0xF9,0xFA,0xFA,0xFA,0xFA,0xFB,0xFB,0xFB,0xFB,0xFC,0xFC,0xFC,0xFC,0xFC,0xFD,0xFD,0xFD,0xFD,0xFD,0xFD,0xFD,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFF};
//~ static const uint8_t exp_dec[256] = {0x0,0x0,0x1,0x1,0x2,0x2,0x3,0x3,0x4,0x4,0x5,0x5,0x6,0x6,0x7,0x7,0x8,0x8,0x9,0x9,0xA,0xA,0xB,0xB,0xC,0xC,0xD,0xD,0xE,0xE,0xF,0x10,0x10,0x11,0x11,0x12,0x12,0x13,0x13,0x14,0x14,0x15,0x15,0x16,0x17,0x17,0x18,0x18,0x19,0x19,0x1A,0x1A,0x1B,0x1C,0x1C,0x1D,0x1D,0x1E,0x1E,0x1F,0x20,0x20,0x21,0x21,0x22,0x22,0x23,0x24,0x24,0x25,0x25,0x26,0x26,0x27,0x28,0x28,0x29,0x29,0x2A,0x2B,0x2B,0x2C,0x2C,0x2D,0x2E,0x2E,0x2F,0x30,0x30,0x31,0x31,0x32,0x33,0x33,0x34,0x35,0x35,0x36,0x36,0x37,0x38,0x38,0x39,0x3A,0x3A,0x3B,0x3C,0x3C,0x3D,0x3E,0x3E,0x3F,0x40,0x40,0x41,0x42,0x42,0x43,0x44,0x44,0x45,0x46,0x46,0x47,0x48,0x48,0x49,0x4A,0x4B,0x4B,0x4C,0x4D,0x4D,0x4E,0x4F,0x50,0x50,0x51,0x52,0x53,0x53,0x54,0x55,0x56,0x56,0x57,0x58,0x59,0x59,0x5A,0x5B,0x5C,0x5C,0x5D,0x5E,0x5F,0x60,0x60,0x61,0x62,0x63,0x64,0x65,0x65,0x66,0x67,0x68,0x69,0x6A,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8E,0x8F,0x90,0x91,0x92,0x93,0x95,0x96,0x97,0x98,0x9A,0x9B,0x9C,0x9D,0x9F,0xA0,0xA1,0xA3,0xA4,0xA6,0xA7,0xA9,0xAA,0xAC,0xAD,0xAF,0xB0,0xB2,0xB4,0xB5,0xB7,0xB9,0xBB,0xBD,0xBF,0xC1,0xC3,0xC5,0xC7,0xCA,0xCC,0xCF,0xD1,0xD4,0xD7,0xDB,0xDF,0xE3,0xE8,0xEF,0xFF};

// determined experimentally from ufraw, from an image developed at 0EV and +1EV, with clip=film
static const uint8_t exp_inc[256] = {0x0,0x2,0x4,0x6,0x8,0xA,0xC,0xE,0x10,0x12,0x14,0x16,0x18,0x1A,0x1C,0x1E,0x20,0x21,0x23,0x25,0x27,0x29,0x2B,0x2D,0x2F,0x31,0x33,0x35,0x36,0x38,0x3A,0x3C,0x3E,0x40,0x42,0x43,0x45,0x47,0x49,0x4A,0x4C,0x4D,0x4F,0x50,0x52,0x53,0x54,0x56,0x57,0x58,0x5A,0x5B,0x5C,0x5D,0x5E,0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xA0,0xA1,0xA2,0xA3,0xA4,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAB,0xAC,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF,0xBF,0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD0,0xD1,0xD2,0xD3,0xD4,0xD4,0xD5,0xD6,0xD7,0xD7,0xD8,0xD9,0xDA,0xDA,0xDB,0xDC,0xDD,0xDD,0xDE,0xDF,0xDF,0xE0,0xE1,0xE1,0xE2,0xE3,0xE3,0xE4,0xE5,0xE5,0xE6,0xE7,0xE7,0xE8,0xE9,0xE9,0xEA,0xEA,0xEB,0xEC,0xEC,0xED,0xED,0xEE,0xEE,0xEF,0xF0,0xF0,0xF1,0xF1,0xF2,0xF2,0xF3,0xF3,0xF4,0xF4,0xF5,0xF5,0xF6,0xF6,0xF7,0xF7,0xF8,0xF8,0xF9,0xF9,0xF9,0xFA,0xFA,0xFB,0xFB,0xFB,0xFC,0xFC,0xFD,0xFD,0xFD,0xFD,0xFE,0xFE,0xFE,0xFE,0xFF};
static const uint8_t exp_dec[256] = {0x0,0x1,0x1,0x2,0x2,0x3,0x3,0x4,0x4,0x5,0x5,0x6,0x6,0x7,0x7,0x8,0x8,0x9,0x9,0xA,0xA,0xB,0xB,0xC,0xC,0xD,0xD,0xE,0xE,0xF,0xF,0x10,0x10,0x11,0x12,0x12,0x13,0x13,0x14,0x14,0x15,0x15,0x16,0x16,0x17,0x17,0x18,0x18,0x19,0x19,0x1A,0x1A,0x1B,0x1B,0x1C,0x1D,0x1D,0x1E,0x1E,0x1F,0x1F,0x20,0x20,0x21,0x21,0x22,0x22,0x23,0x24,0x24,0x25,0x25,0x26,0x26,0x27,0x28,0x28,0x29,0x2A,0x2A,0x2B,0x2C,0x2C,0x2D,0x2E,0x2F,0x2F,0x30,0x31,0x32,0x32,0x33,0x34,0x35,0x36,0x37,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F,0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7C,0x7D,0x7E,0x7F,0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xA0,0xA2,0xA3,0xA4,0xA5,0xA7,0xA8,0xA9,0xAA,0xAB,0xAD,0xAE,0xAF,0xB0,0xB2,0xB3,0xB4,0xB6,0xB7,0xB8,0xBA,0xBB,0xBC,0xBE,0xBF,0xC1,0xC2,0xC4,0xC5,0xC7,0xC8,0xCA,0xCB,0xCD,0xCE,0xD0,0xD2,0xD3,0xD5,0xD7,0xD9,0xDA,0xDC,0xDE,0xE0,0xE2,0xE4,0xE6,0xE8,0xEA,0xEC,0xEF,0xF1,0xF4,0xF6,0xFA,0xFE,0xFF};


// when overexposing, chroma should drop to 0
static const uint8_t chroma_cor[256] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFD,0xFD,0xFD,0xFD,0xFD,0xFD,0xFD,0xFD,0xFD,0xFC,0xFC,0xFC,0xFC,0xFB,0xFB,0xFA,0xFA,0xF9,0xF8,0xF7,0xF5,0xF3,0xEE,0xE6,0xCC,0x70,0x0};

void expo_adjust_playback(int dir)
{
#ifdef CONFIG_5DC
    static int expo_value = 0;
    if (dir == 0) 
    { 
        if (expo_value) EngDrvOut(0xC0F140c0, 0x80);
        expo_value = 0; return; 
    }
    expo_value = COERCE(expo_value + dir, -3, 1);
    //~ expo_value = expo_value + dir;
    NotifyBox(1000, "%s%d", expo_value > 0 ? "+" : "", expo_value);
    BmpDDev_take_semaphore();
    if (expo_value > 0) 
    {
        EngDrvOut(0xC0F14080, 0xfc0000);
        EngDrvOut(0xC0F140c0, 0xFF);
    }   
    else if (expo_value < 0) 
    {
        EngDrvOut(0xC0F14080, 0x1000000 * (-expo_value-1));
        EngDrvOut(0xC0F140c0, 0x80);
    }
    else 
    {
        EngDrvOut(0xC0F14080, 0xfc0000);
        EngDrvOut(0xC0F140c0, 0x80);
    }
    EngDrvOut(0xC0F14078, 1);
    BmpDDev_give_semaphore();

#else
    ASSERT(set_maindial_sem);
    take_semaphore(set_maindial_sem, 0);

    uint8_t* current_buf = get_yuv422_vram()->vram;
    int w = get_yuv422_vram()->width;
    int h = get_yuv422_vram()->height;
    int buf_size = w * h * 2;

    for (int i = 0; i < buf_size; i += 4)
    {
        if (dir > 0)
        {
            uint8_t* luma1 = &current_buf[i+1];
            uint8_t* luma2 = &current_buf[i+3];
            int luma_avg = (*luma1 + *luma2) / 2;
            int chroma_scaling = (int)exp_inc[luma_avg] * 1024 / (luma_avg);
            
            // scale luma values individually with the curve LUT
            *luma1 = exp_inc[*luma1];
            *luma2 = exp_inc[*luma2];

            // when overexposing, chroma should drop to 0
            luma_avg = (*luma1 + *luma2) / 2;
            chroma_scaling = chroma_scaling * (int)chroma_cor[luma_avg] / 256;
            
            int8_t* chroma1 = (int8_t*)&current_buf[i];
            int8_t* chroma2 = (int8_t*)&current_buf[i+2];
            
            // scale both chroma values with the same factor, to keep the hue unchanged
            int chroma1_ex = (int)*chroma1 * chroma_scaling / 1024;
            int chroma2_ex = (int)*chroma2 * chroma_scaling / 1024;
            
            // gracefully handle overflow in one chroma channel - if any of them exceeds 127, reduce both of them and keep the ratio unchanged
            if (ABS(chroma1_ex) > 127 || ABS(chroma2_ex) > 127)
            {
                int chroma_max = MAX(ABS(chroma1_ex), ABS(chroma2_ex));
                chroma1_ex = chroma1_ex * 127 / chroma_max;
                chroma2_ex = chroma2_ex * 127 / chroma_max;
            }
            
            *chroma1 = chroma1_ex;
            *chroma2 = chroma2_ex;
        }
        else
        {
            uint8_t* luma1 = &current_buf[i+1];
            uint8_t* luma2 = &current_buf[i+3];
            int luma_avg = (*luma1 + *luma2) / 2;
            int chroma_scaling = (int)exp_dec[luma_avg] * 1024 / (luma_avg);
            
            *luma1 = exp_dec[*luma1];
            *luma2 = exp_dec[*luma2];
            
            // chroma scaling for underexposing is simpler - no more overflows to deal with
            // but the process is not 100% reversible, although the approximation is pretty good
            
            int8_t* chroma1 = (int8_t*)&current_buf[i];
            int8_t* chroma2 = (int8_t*)&current_buf[i+2];
            
            *chroma1 = (int)*chroma1 * chroma_scaling / 1024;
            *chroma2 = (int)*chroma2 * chroma_scaling / 1024;
        }
    }

    give_semaphore(set_maindial_sem);
#endif
}

#endif

#ifdef FEATURE_PLAY_422

// that's extremely inefficient
static int find_422(int * index, char* fn)
{
    struct fio_file file;
    struct fio_dirent * dirent = 0;
    int N = 0;
    
    dirent = FIO_FindFirstEx( get_dcim_dir(), &file );
    if( IS_ERROR(dirent) )
    {
        bmp_printf( FONT_LARGE, 40, 40, "find_422: dir err" );
        return 0;
    }

    do {
        if (file.mode & 0x10) continue; // is a directory
        int n = strlen(file.name);
        if ((n > 4) && (streq(file.name + n - 4, ".422")))
            N++;
    } while( FIO_FindNextEx( dirent, &file ) == 0);
    FIO_CleanupAfterFindNext_maybe(dirent);

    static int old_N = 0;
    if (N != old_N) // number of pictures was changed, display the last one
    {
        old_N = N;
        *index = N-1;
    }
    
    *index = mod(*index, N);

    dirent = FIO_FindFirstEx( get_dcim_dir(), &file );
    if( IS_ERROR(dirent) )
    {
        bmp_printf( FONT_LARGE, 40, 40, "find_422: dir err" );
        return 0;
    }

    int k = 0;
    int found = 0;
    do {
        if (file.mode & 0x10) continue; // is a directory
        int n = strlen(file.name);
        if ((n > 4) && (streq(file.name + n - 4, ".422")))
        {
            if (k == *index)
            {
                snprintf(fn, 100, "%s/%s", get_dcim_dir(), file.name);
                found = 1;
            }
            k++;
        }
    } while( FIO_FindNextEx( dirent, &file ) == 0);
    FIO_CleanupAfterFindNext_maybe(dirent);
    return found;
}

void play_next_422_task(int dir)
{
    ASSERT(set_maindial_sem);
    take_semaphore(set_maindial_sem, 0);
    
    static int index = -1;
    static char ffn[100];
    
    index += dir;
    
    if (find_422(&index, ffn))
    {
        play_422(ffn);
        //~ bmp_printf(FONT_LARGE, 0, 0, ffn);
    }
    else
    {
        bmp_printf(FONT_LARGE, 0, 0, "No 422 files found");
    }

    give_semaphore(set_maindial_sem);
}


void play_next_422(int dir)
{
    task_create("422_task", 0x1c, 0, play_next_422_task, (void*)dir);
}
#endif


void ensure_movie_mode()
{
#ifdef CONFIG_MOVIE
    if (!is_movie_mode())
    {
        #ifdef CONFIG_50D
        GUI_SetLvMode(2);
        GUI_SetMovieSize_b(1);
        #elif defined(CONFIG_5D2)
        GUI_SetLvMode(2);
        #else
        while (!is_movie_mode())
        {
            NotifyBox(2000, "Please switch to Movie mode.");
            msleep(500);
        }
        #endif
        msleep(500); 
    }
    if (!lv) force_liveview();
#endif
}

#ifdef FEATURE_SILENT_PIC
// this buffer will contain the HD image (saved to card) and a LV preview (for display)
static void * silent_pic_buf = 0;


#ifdef CONFIG_DISPLAY_FILTERS
int silent_pic_preview()
{
#ifndef CONFIG_VXWORKS
    if (silent_pic_buf && silent_pic_mode == 0) // only preview single silent pics (not burst etc)
    {
        int size = vram_hd.pitch * vram_hd.height;
        YUV422_LV_BUFFER_DISPLAY_ADDR = (intptr_t)silent_pic_buf + size;
        return 1;
    }
#endif
    return 0;
}
#endif

// uses busy waiting
// it can be refactored without busy wait, similar to lv_vsync (with another MQ maybe)
// returns: 1=success, 0=failure
int busy_vsync(int hd, int timeout_ms)
{
#ifdef REG_EDMAC_WRITE_LV_ADDR
    int timeout_us = timeout_ms * 1000;
    void* old = (void*)shamem_read(hd ? REG_EDMAC_WRITE_HD_ADDR : REG_EDMAC_WRITE_LV_ADDR);
    int t0 = *(uint32_t*)0xC0242014;
    while(1)
    {
        int t1 = *(uint32_t*)0xC0242014;
        int dt = mod(t1 - t0, 1048576);
        void* new = (void*)shamem_read(hd ? REG_EDMAC_WRITE_HD_ADDR : REG_EDMAC_WRITE_LV_ADDR);
        if (old != new) break;
        if (dt > timeout_us)
            return 0;
        for (int i = 0; i < 100; i++) asm("nop"); // don't stress the digic too much
    }
    return 1;
#else
    return 0;
#endif
}

#ifdef FEATURE_SILENT_PIC_RAW
static void
silent_pic_take_raw()
{
    /* this enables a LiveView debug flag that gives us 14-bit RAW data. Cool! */
    call("lv_save_raw", 1);
    msleep(50);
    
    /* after filling one frame, disable the flag so we can dump the data without tearing */
    call("lv_save_raw", 0);
    msleep(50);

    /* try to autodetect image size */
    uint32_t lv_raw_size = MEMX(RAW_LV_EDMAC+8);
    int lv_raw_pitch = lv_raw_size & 0xFFFF;
    int lv_raw_width = lv_raw_pitch * 8 / 14;
    //~ int lv_raw_height = (lv_raw_size >> 16) & 0xFFFF; // it's zero...
    int lv_raw_height = lv_raw_width * 21/30; // dumb one-size-fits-all
    uint32_t lv_raw_addr = MEMX(RAW_LV_EDMAC);

    /* save it to card */
    char* fn = silent_pic_get_name();
    bmp_printf(FONT_MED, 0, 60, "Saving %d x %d...", lv_raw_width, lv_raw_height);
    save_dng(fn, lv_raw_addr, lv_raw_width, lv_raw_height);
    redraw();
}

#else // who needs 422 when we have raw?

static void
silent_pic_take_simple(int interactive)
{
    get_yuv422_hd_vram();
    int size = vram_hd.pitch * vram_hd.height;
    int lv_size = vram_lv.pitch * vram_lv.height;
    
    // start with black preview 
    silent_pic_buf = (void*)shoot_malloc(size + lv_size);
    bzero32(silent_pic_buf + size, lv_size);
    
    /* when in continuous mode, wait for halfshutter being released before starting */
    if(silent_pic_mode == 2)
    {
        while(get_halfshutter_pressed())
        {
            msleep(10);
        }
    }
    
    if (silent_pic_buf)
    {
        do
        {
            char* imgname = silent_pic_get_name();
            // copy the HD picture into the temporary buffer
            
#ifdef FEATURE_SILENT_PIC_JPG
            if(silent_pic_jpeg)
            {
                uint32_t loopcount = 0;
                uint8_t *oldBuf = (uint8_t*) GetJpegBufForLV();
                uint32_t oldLen = GetJpegSizeForLV();
                
                /* wait until size or buffer changed, then its likely that it is a new frame */
                while((uint32_t)GetJpegSizeForLV() == oldLen || (uint8_t*)GetJpegBufForLV() == oldBuf)
                {
                    msleep(MIN_MSLEEP);
                    if(++loopcount > 500)
                    {
                        NotifyBox(2000, "Failed to wait until\nJPEG buffer updates"); 
                        msleep(5000);
                        return;
                    }
                }
                uint8_t *srcBuf = (uint8_t*) GetJpegBufForLV();
                uint32_t srcLen = GetJpegSizeForLV();
                
                /* buffer is for sure larger than the jpeg will ever get */
                dma_memcpy(silent_pic_buf, srcBuf, srcLen);
                
                dump_seg(silent_pic_buf, srcLen, imgname);
            }
            else
#endif
            {
                // first we will copy the picture in a temporary buffer, to avoid horizontal cuts
                void* buf = (void*)YUV422_HD_BUFFER_DMA_ADDR;

                // wait until EDMAC HD buffer changes; at that point, 'buf' will contain a complete picture (and EDMAC starts filling the new one)
                busy_vsync(1, 100);
                
                #ifdef CONFIG_DMA_MEMCPY
                dma_memcpy(silent_pic_buf, buf, size);
                #else
                memcpy(silent_pic_buf, buf, size);
                #endif
                
                /* we can take our time and resize it for preview purposes, only do that for single pics */
                if(silent_pic_mode == 0)
                {
                    yuv_resize(silent_pic_buf, vram_hd.width, vram_hd.height, silent_pic_buf + size, vram_lv.width, vram_lv.height);
                }
                dump_seg(silent_pic_buf, size, imgname);
            }

            /* in burst mode abort when halfshutter isnt pressed anymore */
            if(silent_pic_mode == 1)
            {
                if(!get_halfshutter_pressed())
                {
                    break;
                }
            }
            else if(silent_pic_mode == 2)
            {
                /* cancel continuous mode with halfshutter press */
                if(get_halfshutter_pressed())
                {
                    /* wait until button is released to prevent from firing again */
                    while(get_halfshutter_pressed())
                    {
                        msleep(10);
                    }
                    break;
                }
            }
            else
            {
                break;
            }
            
            /* repeat process if half-shutter is still pressed and burst mode was enabled */
        } while (1);
        
        shoot_free(silent_pic_buf);
        silent_pic_buf = NULL;
    }

    /* if not in burst mode, wait until half-shutter was released */
    if (interactive && silent_pic_mode == 0) // single mode
    {
        while (get_halfshutter_pressed()) msleep(100);
    }
}
#endif

#else // no silent pics, need some dummy stubs
int silent_pic_preview(){ return 0; }
#endif

#ifdef FEATURE_SCREENSHOT_422
void
silent_pic_take_lv_dbg()
{
    struct vram_info * vram = get_yuv422_vram();
    int silent_number;
    char imgname[100];
    for (silent_number = 0 ; silent_number < 1000; silent_number++) // may be slow after many pics
    {
        snprintf(imgname, sizeof(imgname), CARD_DRIVE "VRAM%d.422", silent_number); // should be in root, because Canon's "dispcheck" saves screenshots there too
        uint32_t size;
        if( FIO_GetFileSize( imgname, &size ) != 0 ) break;
        if (size == 0) break;
    }
    dump_seg(vram->vram, vram->pitch * vram->height, imgname);
}
#endif

#ifdef FEATURE_SILENT_PIC

int silent_pic_matrix_running = 0;

#ifdef FEATURE_SILENT_PIC_HIRES

#if defined(CONFIG_6D)
#define ZoomBoxOffsetX 24
#define ZoomBoxOffsetY 301
#endif

void
silent_pic_take_sweep(int interactive)
{
#ifdef CONFIG_LIVEVIEW
    if (recording) return;
    if (!lv) return;
    if (!silent_pic_hires_check()) return;

    bmp_printf(FONT_MED, 100, 100, "Psst! Preparing for high-res pic   ");
    while (get_halfshutter_pressed()) msleep(100);
    gui_stop_menu();

    bmp_draw_rect(COLOR_WHITE, (5-SILENTPIC_NC) * 360/5, (5-SILENTPIC_NL)*240/5, SILENTPIC_NC*720/5-1, SILENTPIC_NL*480/5-1);
    msleep(200);
    if (interactive) msleep(2000);
    redraw(); msleep(100);
    
    int afx0 = afframe[2];
    int afy0 = afframe[3];

    set_lv_zoom(10);
    msleep(1000);

    struct vram_info * vram = get_yuv422_hd_vram();

    char* imgname = silent_pic_get_name();

    FILE* f = FIO_CreateFileEx(imgname);
    if (f == INVALID_PTR)
    {
        bmp_printf(FONT_SMALL, 120, 40, "FCreate: Err %s", imgname);
        return;
    }
    int i,j;
    int NL = SILENTPIC_NL;
    int NC = SILENTPIC_NC;


    #if defined(CONFIG_6D)
    int x0 = ( (SENSOR_RES_X - NC * 536) / 2) - 536; //612
    int y0 = ( (SENSOR_RES_Y - NL * ((SENSOR_RES_Y - ZoomBoxOffsetY*2)/NL)  ) / 2 );
    #else 
    int x0 = (SENSOR_RES_X - NC * vram_hd.width)  / 2;
    int y0 = (SENSOR_RES_Y - NL * vram_hd.height) / 2;
    #endif

    for (i = 0; i < NL; i++)
    {
        for (j = 0; j < NC; j++)
        {
            // afframe[2,3]: x,y
            // range obtained by moving the zoom window: 250 ... 3922, 434 ... 2394 => upper left corner
            // full-res: 5202x3465
            // buffer size: 1024x680
            bmp_printf(FONT_MED, 100, 100, "Psst! Taking a high-res pic [%d,%d]      ", i, j);

            afframe[2] = x0 + vram_hd.width * j;
            afframe[3] = y0 + vram_hd.height * i;

            prop_request_change(PROP_LV_AFFRAME, afframe, 0);
            //~ msleep(500);
            msleep(silent_pic_sweepdelay);
            FIO_WriteFile(f, vram->vram, vram_hd.width * vram_hd.height * 2);
            //~ bmp_printf(FONT_MED, 20, 150, "=> %d", ans);
            msleep(50);
        }
    }
    FIO_CloseFile(f);
    
    // restore
    set_lv_zoom(1);
    msleep(1000);
    afframe[2] = afx0;
    afframe[3] = afy0;
    prop_request_change(PROP_LV_AFFRAME, afframe, 0);

    bmp_printf(FONT_MED, 100, 100, "Psst! Just took a high-res pic   ");
#endif
}
#endif


static void
silent_pic_take(int interactive) // for remote release, set interactive=0
{
    if (!silent_pic_enabled) return;

    if (!lv) force_liveview();
    
#ifdef FEATURE_SILENT_PIC_RAW
    silent_pic_take_raw();
#else

    switch(silent_pic_mode)
    {
        /* normal, burst, continuous */
        case 0:
        case 1:
        case 2:
            silent_pic_take_simple(interactive);
            break;
        #ifdef FEATURE_SILENT_PIC_HIRES
        case 3:
            silent_pic_matrix_running = 1;
            silent_pic_take_sweep(interactive);
            break;
        #endif
    }

    silent_pic_matrix_running = 0;
#endif
}
#endif

#ifdef FEATURE_EXPO_ISO

static MENU_UPDATE_FUNC(iso_icon_update)
{
    if (lens_info.iso)
        MENU_SET_ICON(MNI_PERCENT, (lens_info.raw_iso - codes_iso[1]) * 100 / (codes_iso[COUNT(codes_iso)-1] - codes_iso[1]));
    else 
        MENU_SET_ICON(MNI_AUTO, 0);
}

static MENU_UPDATE_FUNC(iso_display)
{
    MENU_SET_VALUE(
        "%s", 
        lens_info.iso ? "" : "Auto"
    );

    if (lens_info.iso)
    {
        if (lens_info.raw_iso == lens_info.iso_equiv_raw)
        {
            MENU_SET_VALUE(
                "%d", raw2iso(lens_info.iso_equiv_raw)
            );

            if (!menu_active_but_hidden())
            {
                int Sv = APEX_SV(lens_info.iso_equiv_raw) * 10/8;
                MENU_SET_RINFO(
                    "Sv%s%d.%d",
                    FMT_FIXEDPOINT1(Sv)
                );
            }

        }
        else
        {
            int dg = lens_info.iso_equiv_raw - lens_info.raw_iso;
            dg = dg * 10/8;
            MENU_SET_VALUE(
                "%d", 
                raw2iso(lens_info.iso_equiv_raw)
            );
            MENU_SET_RINFO(
                "%d,%s%d.%dEV", 
                raw2iso(lens_info.raw_iso),
                FMT_FIXEDPOINT1S(dg)
            );
        }
    }
    
    iso_icon_update(entry, info);
    
    MENU_SET_SHORT_NAME(" "); // obvious from value
}
#endif

int is_native_iso(int iso)
{
    switch(iso)
    {
        case 100:
        case 200:
        case 400:
        case 800:
        case 1600:
        case 3200:
        #if defined(CONFIG_5D3) || defined(CONFIG_EOSM) || defined(CONFIG_650D) || defined(CONFIG_6D)
        case 6400: // on digic 4, those are digital gains applied to 3200 ISO
        case 12800:
        case 25600:
        #endif
            return 1;
    }
    return 0;
}

int is_lowgain_iso(int iso)
{
    switch(iso)
    {
        case 160:  // ISO 200 - 1/3EV
        case 320:  // ISO 400 - 1/3EV
        case 640:  // ISO 800 - 1/3EV
        case 1250: // ISO 1600 - 1/3EV
        case 2500: // ISO 3200 - 1/3EV
        #if defined(CONFIG_5D3) || defined(CONFIG_EOSM) || defined(CONFIG_650D) || defined(CONFIG_6D)
        case 5000:
        case 10000:
        #endif
        return 1;
    }
    return 0;
}

int is_round_iso(int iso)
{
    return is_native_iso(iso) || is_lowgain_iso(iso) || iso == 0
        || iso == 6400 || iso == 12800 || iso == 25600;
}

#ifdef FEATURE_EXPO_ISO
// fixme: these don't work well
static void
analog_iso_toggle( void * priv, int sign )
{
    int r = lens_info.raw_iso;
    int a, d;
    split_iso(r, &a, &d);
    a = COERCE(a + sign * 8, MIN_ISO, MAX_ANALOG_ISO);
    lens_set_rawiso(a + d);
}

static void
digital_iso_toggle( void * priv, int sign )
{
    int r = lens_info.raw_iso;
    int a, d;
    split_iso(r, &a, &d);
    d = COERCE(d + sign, -3, (a == MAX_ANALOG_ISO ? 16 : 4));
    while (d > 8 && d < 16) d += sign;
    lens_set_rawiso(a + d);
}


void
iso_toggle( void * priv, int sign )
{
    int (*iso_checker)(int) = is_round_iso;
    
    if (is_movie_mode())
    {
        extern int bv_auto;
        if (lens_info.raw_iso && priv != (void*)-1)
        if ((lens_info.raw_iso <= MIN_ISO               && sign < 0) ||
            (lens_info.raw_iso >= (bv_auto ? MAX_ISO_BV : MAX_ISO) && sign > 0))
        {
            if (lens_set_rawiso(0)) // ISO auto
                return;
        }

        int digic_gain = get_digic_iso_gain_movie();
        if (digic_gain != 1024) // keep the DIGIC gain, toggle ISO in full-stops
            iso_checker = is_native_iso;
    }
    
    int i = raw2index_iso(lens_info.raw_iso);
    int i0 = i;
    int k;
    for (k = 0; k < 10; k++)
    {
        i = mod(i + sign, COUNT(codes_iso));
        

        while (!iso_checker(values_iso[i]))
            i = mod(i + sign, COUNT(codes_iso));
        
        if (priv == (void*)-1 && SGN(i - i0) != sign) // wrapped around
            break;
        
        if (priv == (void*)-1 && i == 0) break; // no auto iso allowed from shortcuts
        
        if (lens_set_rawiso(codes_iso[i])) break;
    }
}

#endif // FEATURE_EXPO_ISO

#ifdef FEATURE_EXPO_SHUTTER

static MENU_UPDATE_FUNC(shutter_display)
{
    if (is_movie_mode())
    {
        int s = get_current_shutter_reciprocal_x1000() + 50;
        int deg = 3600 * fps_get_current_x1000() / s;
        deg = (deg + 5) / 10;
        MENU_SET_VALUE(
            "1/%d.%d, %d ",
            s/1000, (s%1000)/100,
            deg);
    }
    else
    {
        MENU_SET_VALUE(
            "1/%d",
            lens_info.shutter
        );
    }

/*
    if (is_movie_mode())
    {
        int xc = x + font_large.width * (strlen(msg) - 1);
        draw_circle(xc + 2, y + 7, 3, COLOR_WHITE);
        draw_circle(xc + 2, y + 7, 4, COLOR_WHITE);
    }
*/

    if (!menu_active_but_hidden())
    {
        
        int Tv = APEX_TV(lens_info.raw_shutter) * 10/8;
        if (lens_info.raw_shutter) MENU_SET_RINFO(
            "Tv%s%d.%d",
            FMT_FIXEDPOINT1(Tv)
        );
    }

    if (lens_info.raw_shutter)
    {
        MENU_SET_ICON(MNI_PERCENT, (lens_info.raw_shutter - codes_shutter[1]) * 100 / (codes_shutter[COUNT(codes_shutter)-1] - codes_shutter[1]));
        MENU_SET_ENABLED(1);
    }
    else 
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Shutter speed is automatic - cannot adjust manually.");

    MENU_SET_SHORT_NAME(" "); // obvious from value
}

void
shutter_toggle(void* priv, int sign)
{
    if (!lens_info.raw_shutter) return;
    int i = raw2index_shutter(lens_info.raw_shutter);
    int k;
    for (k = 0; k < 15; k++)
    {
        int new_i = i;
        new_i = mod(new_i + sign, COUNT(codes_shutter));

        //~ bmp_printf(FONT_MED, 100, 300, "%d -> %d ", codes_shutter[i0], codes_shutter[new_i]);
        
        if (priv == (void*)-1 && (new_i == 0 || i + sign != new_i)) // wrapped around
            break;
        i = new_i;
        if (lens_set_rawshutter(codes_shutter[i])) break;
    }
}

#endif // FEATURE_EXPO_SHUTTER

#ifdef FEATURE_EXPO_APERTURE

static MENU_UPDATE_FUNC(aperture_display)
{
    int a = lens_info.aperture;
    int av = APEX_AV(lens_info.raw_aperture) * 10/8;
    if (!a || !lens_info.name[0]) // for unchipped lenses, always display zero
        a = av = 0;
    MENU_SET_VALUE(
        "f/%d.%d",
        a / 10,
        a % 10, 
        av / 8, 
        (av % 8) * 10/8
    );

    if (!menu_active_but_hidden())
    {
        if (a) MENU_SET_RINFO(
            "Av%s%d.%d",
            FMT_FIXEDPOINT1(av)
        );
    }
    if (!lens_info.aperture)
    {
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, lens_info.name[0] ? "Aperture is automatic - cannot adjust manually." : "Manual lens - cannot adjust aperture.");
        MENU_SET_ICON(MNI_PERCENT_OFF, 0);
    }
    else
    {
        MENU_SET_ICON(MNI_PERCENT, (lens_info.raw_aperture - lens_info.raw_aperture_min) * 100 / (lens_info.raw_aperture_max - lens_info.raw_aperture_min));
        MENU_SET_ENABLED(1);
    }

    MENU_SET_SHORT_NAME(" "); // obvious from value
}

void
aperture_toggle( void* priv, int sign)
{
    if (!lens_info.name[0]) return; // only chipped lenses can change aperture
    if (!lens_info.raw_aperture) return;
    int amin = codes_aperture[1];
    int amax = codes_aperture[COUNT(codes_aperture)-1];
    
    int a = lens_info.raw_aperture;

    for (int k = 0; k < 4; k++)
    {
        do {
            a += sign;
            if (priv == (void*)-1) // don't wrap around
            {
                if (a > amax) { a = amax; break; }
                if (a < amin) { a = amin; break; }
            }
            else // allow wrap around
            {
                if (a > amax) a = amin;
                if (a < amin) a = amax;
            }
            if (lens_info.raw_aperture_min >= lens_info.raw_aperture_max) break;
        }
        while (a < lens_info.raw_aperture_min || a > lens_info.raw_aperture_max);

        if (lens_set_rawaperture(a)) break;
    }
}

#endif

#ifdef FEATURE_WHITE_BALANCE

void
kelvin_toggle( void* priv, int sign )
{
    //~ if (uniwb_is_active()) return;

    int k;
    switch (lens_info.wb_mode)
    {
        case WB_SUNNY: k = 5200; break;
        case WB_SHADE: k = 7000; break;
        case WB_CLOUDY: k = 6000; break;
        case WB_TUNGSTEN: k = 3200; break;
        case WB_FLUORESCENT: k = 4000; break;
        case WB_FLASH: k = 6500; break; // maybe?
        default: k = lens_info.kelvin;
    }
    
    int step = KELVIN_STEP;
    if (k + sign * step > 7000)
        step *= 5;
    
    k = (k/step) * step;
    if (priv == (void*)-1) // no wrap around
        k = COERCE(k + sign * step, KELVIN_MIN, KELVIN_MAX);
    else // allow wrap around
        k = KELVIN_MIN + mod(k - KELVIN_MIN + sign * step, KELVIN_MAX - KELVIN_MIN + step);
    
    lens_set_kelvin(k);
}

PROP_INT( PROP_WB_KELVIN_PH, wb_kelvin_ph );

static MENU_UPDATE_FUNC(kelvin_display)
{
    if (lens_info.wb_mode == WB_KELVIN)
    {
        MENU_SET_VALUE(
            "%dK",
            lens_info.kelvin
        );
        MENU_SET_ICON(MNI_PERCENT, (lens_info.kelvin - KELVIN_MIN) * 100 / (KELVIN_MAX - KELVIN_MIN));
        if (lens_info.kelvin != wb_kelvin_ph)
            MENU_SET_WARNING(MENU_WARN_ADVICE, "Extended WB values are only applied to movies, not photos.");
    }
    else
    {
        MENU_SET_VALUE(
            uniwb_is_active()      ? "UniWB"   : 
            lens_info.wb_mode == 0 ? "Auto"    : 
            lens_info.wb_mode == 1 ? "Sunny"   :
            lens_info.wb_mode == 2 ? "Cloudy"  : 
            lens_info.wb_mode == 3 ? "Tungsten": 
            lens_info.wb_mode == 4 ? "Fluor."  : 
            lens_info.wb_mode == 5 ? "Flash"   : 
            lens_info.wb_mode == 6 ? "Custom"  : 
            lens_info.wb_mode == 8 ? "Shade"   :
             "unknown"
        );
        MENU_SET_ICON(MNI_AUTO, 0);
    }
}

static MENU_UPDATE_FUNC(kelvin_wbs_display)
{
    kelvin_display(entry, info);

    if (lens_info.wbs_gm)
    {
        MENU_APPEND_RINFO(
            " %s%d",
            lens_info.wbs_gm > 0 ? "G" : "M", ABS(lens_info.wbs_gm)
        );
    }
    if (lens_info.wbs_ba)
    {
        MENU_APPEND_RINFO(
            " %s%d",
            lens_info.wbs_ba > 0 ? "A" : "B", ABS(lens_info.wbs_ba)
        );
    }

    MENU_SET_SHORT_NAME(" "); // obvious from value
    MENU_SET_SHORT_VALUE("%s%s", info->value, info->rinfo); // squeeze both on the same field
}

static int kelvin_auto_flag = 0;
static int wbs_gm_auto_flag = 0;
static void kelvin_auto()
{
    if (lv) kelvin_auto_flag = 1;
}

static void wbs_gm_auto()
{
    if (lv) wbs_gm_auto_flag = 1;
}

void kelvin_n_gm_auto()
{
    if (lv)
    {
        kelvin_auto_flag = 1;
        wbs_gm_auto_flag = 1;
    }
}

static MENU_UPDATE_FUNC(wb_custom_gain_display)
{
    int p = (intptr_t) entry->priv;
    int raw_value =
        p==1 ? lens_info.WBGain_R :
        p==2 ? lens_info.WBGain_G :
               lens_info.WBGain_B ;

    int multiplier = 1000 * 1024 / raw_value;
    MENU_SET_NAME(
        "%s multiplier",
        p==1 ? "R" : p==2 ? "G" : "B"
    );
    MENU_SET_VALUE(
        "%d.%03d",
        multiplier/1000, multiplier%1000
    );
    
    if (lens_info.wb_mode != WB_CUSTOM)
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Custom white balance is not active => not used.");
    
    int ll = log_length(125);
    int lh = log_length(8000);
    int l = log_length(raw_value);
    MENU_SET_ICON(MNI_PERCENT, (l-lh) * 100 / (ll-lh));
}

static void
wb_custom_gain_toggle( void * priv, int delta )
{
    //~ if (uniwb_is_active()) return;
    int p = (intptr_t) priv;
    int deltaR = p == 1 ? -delta * 16 * MAX(1, lens_info.WBGain_R/1024) : 0;
    int deltaG = p == 2 ? -delta * 16 * MAX(1, lens_info.WBGain_G/1024) : 0;
    int deltaB = p == 3 ? -delta * 16 * MAX(1, lens_info.WBGain_B/1024) : 0;
    lens_set_custom_wb_gains(lens_info.WBGain_R + deltaR, lens_info.WBGain_G + deltaG, lens_info.WBGain_B + deltaB);
}

/*
static void uniwb_save_normal_wb_params()
{
    if (uniwb_is_active_check_lensinfo_only()) return;
    //~ info_led_blink(1,50,50);
    uniwb_old_wb_mode = lens_info.wb_mode;
    if (lens_info.WBGain_R != 1024 || lens_info.WBGain_G != 1024 || lens_info.WBGain_B != 1024)
    {
        uniwb_old_gain_R = lens_info.WBGain_R;
        uniwb_old_gain_G = lens_info.WBGain_G;
        uniwb_old_gain_B = lens_info.WBGain_B;
    }
}

static void uniwb_enable()
{
    uniwb_save_normal_wb_params();
    lens_set_custom_wb_gains(1024, 1024, 1024);
}

static void uniwb_disable()
{
    //~ info_led_blink(2,200,200);
    if (!uniwb_old_gain_R) return;
    lens_set_custom_wb_gains(uniwb_old_gain_R, uniwb_old_gain_G, uniwb_old_gain_B);
    prop_request_change(PROP_WB_MODE_LV, &uniwb_old_wb_mode, 4);
    prop_request_change(PROP_WB_MODE_PH, &uniwb_old_wb_mode, 4);
    msleep(100);
    if (!uniwb_is_active_check_lensinfo_only()) // successfully disabled
    {
        uniwb_old_gain_R = uniwb_old_gain_G = uniwb_old_gain_B = uniwb_old_wb_mode = 0;
    }
}

void uniwb_step()
{
    //~ if (!lv) return;
    
    int uniwb_desired_state = 0;
    switch (uniwb_mode)
    {
        case 0: // always off
            uniwb_desired_state = 0;
            break;
        case 1: // always on
            uniwb_desired_state = 1;
            break;
        case 2: // halfshutter
            uniwb_desired_state = get_halfshutter_pressed();
            break;
        case 3: // halfshutter not pressed
            uniwb_desired_state = !get_halfshutter_pressed();
            break;
    }

    if (!display_idle() && !gui_menu_shown())
    {
        uniwb_save_normal_wb_params(); // maybe user is changing WB settings from Canon menu - save them as non-uniWB params
    }
    else if (uniwb_desired_state == 0) 
    {
        if (uniwb_old_gain_R) uniwb_disable();
    }
    else
    {
        if (!uniwb_is_active()) uniwb_enable();
    }
}
*/

static int crit_kelvin(int k)
{
    if (!lv) return 0;

    if (k > 0)
    {
        lens_set_kelvin(k * KELVIN_STEP);
        msleep(750);
    }

    int Y, U, V;
    get_spot_yuv(100, &Y, &U, &V);

    int R,G,B;
    yuv2rgb(Y,U,V,&R,&G,&B);
    
    NotifyBox(5000, "Adjusting white balance...");

    return B - R;
}

static int crit_wbs_gm(int k)
{
    if (!lv) return 0;

    k = COERCE(k, -10, 10);
    lens_set_wbs_gm(k);
    msleep(750);

    int Y, U, V;
    get_spot_yuv(100, &Y, &U, &V);

    int R,G,B;
    yuv2rgb(Y,U,V,&R,&G,&B);

    NotifyBox(5000, "Adjusting white balance shift...");

    //~ BMP_LOCK( draw_ml_bottombar(0,0); )
    return (R+B)/2 - G;
}

static void kelvin_auto_run()
{
    if (EXT_MONITOR_RCA) { NotifyBox(2000, "Not working on SD monitors."); return; }
    
    gui_stop_menu();
    int c0 = crit_kelvin(-1); // test current kelvin
    int i;
    if (c0 > 0) i = bin_search(lens_info.kelvin/KELVIN_STEP, KELVIN_MAX/KELVIN_STEP + 1, crit_kelvin);
    else i = bin_search(KELVIN_MIN/KELVIN_STEP, lens_info.kelvin/KELVIN_STEP + 1, crit_kelvin);
    lens_set_kelvin(i * KELVIN_STEP);
    //~ NotifyBoxHide();
    //~ redraw();
}

static void wbs_gm_auto_run()
{
    if (EXT_MONITOR_RCA) { NotifyBox(2000, "Not working on SD monitors."); return; }

    gui_stop_menu();
    int c0 = crit_wbs_gm(100); // test current value
    int i;
    if (c0 > 0) i = bin_search(lens_info.wbs_gm, 10, crit_wbs_gm);
    else i = bin_search(-9, lens_info.wbs_gm + 1, crit_wbs_gm);
    lens_set_wbs_gm(i);
    NotifyBoxHide();
    redraw();
}

static MENU_UPDATE_FUNC(wbs_gm_display)
{
    int gm = lens_info.wbs_gm;
    MENU_SET_VALUE(
        "%s%d", 
        gm > 0 ? "Green " : (gm < 0 ? "Magenta " : ""), 
        ABS(gm)
    );
    MENU_SET_ENABLED(gm);
    if (gm) MENU_SET_ICON(MNI_PERCENT_ALLOW_OFF, (-gm+9) * 100 / 18);
    else MENU_SET_ICON(MNI_PERCENT_OFF, 50);
}

static void
wbs_gm_toggle( void * priv, int sign )
{
    int gm = lens_info.wbs_gm;
    int newgm = mod((gm + 9 - sign), 19) - 9;
    newgm = newgm & 0xFF;
    prop_request_change(PROP_WBS_GM, &newgm, 4);
}


static MENU_UPDATE_FUNC(wbs_ba_display)
{
    int ba = lens_info.wbs_ba;
    MENU_SET_VALUE(
        "%s%d", 
        ba > 0 ? "Amber " : (ba < 0 ? "Blue " : ""), 
        ABS(ba)
    );
    MENU_SET_ENABLED(ba);
    if (ba) MENU_SET_ICON(MNI_PERCENT_ALLOW_OFF, (ba+9) * 100 / 18);
    else MENU_SET_ICON(MNI_PERCENT_OFF, 50);
}

static void
wbs_ba_toggle( void * priv, int sign )
{
    int ba = lens_info.wbs_ba;
    int newba = mod((ba + 9 + sign), 19) - 9;
    newba = newba & 0xFF;
    prop_request_change(PROP_WBS_BA, &newba, 4);
}

#endif

#ifdef FEATURE_PICSTYLE

static void
contrast_toggle( void * priv, int sign )
{
    int c = lens_get_contrast();
    if (c < -4 || c > 4) return;
    int newc = mod((c + 4 + sign), 9) - 4;
    lens_set_contrast(newc);
}


static MENU_UPDATE_FUNC(contrast_display)
{
    int s = lens_get_contrast();
    MENU_SET_VALUE(
        "%d",
        s
    );
    MENU_SET_ICON(MNI_PERCENT, (s+4) * 100 / 8);
}

static void
sharpness_toggle( void * priv, int sign )
{
    int c = lens_get_sharpness();
    if (c < 0 || c > 7) return;
    int newc = mod(c + sign, 8);
    lens_set_sharpness(newc);
}

static MENU_UPDATE_FUNC(sharpness_display)
{
    int s = lens_get_sharpness();
    MENU_SET_VALUE(
        "%d ",
        s
    );
    MENU_SET_ICON(MNI_PERCENT, s * 100 / 7);
}

static void
saturation_toggle( void * priv, int sign )
{
    int c = lens_get_saturation();
    if (c < -4 || c > 4) return;
    int newc = mod((c + 4 + sign), 9) - 4;
    lens_set_saturation(newc);
}

static MENU_UPDATE_FUNC(saturation_display)
{
    int s = lens_get_saturation();
    int ok = (s >= -4 && s <= 4);
    MENU_SET_VALUE(
        ok ? 
            "%d " :
            "N/A",
        s
    );
    MENU_SET_ENABLED(ok);
    if (ok) MENU_SET_ICON(MNI_PERCENT, (s+4) * 100 / 8);
    else { MENU_SET_ICON(MNI_OFF, 0); MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "N/A"); }
}

static void
color_tone_toggle( void * priv, int sign )
{
    int c = lens_get_color_tone();
    if (c < -4 || c > 4) return;
    int newc = mod((c + 4 + sign), 9) - 4;
    lens_set_color_tone(newc);
}

static MENU_UPDATE_FUNC(color_tone_display)
{
    int s = lens_get_color_tone();
    int ok = (s >= -4 && s <= 4);
    MENU_SET_VALUE(
        ok ? 
            "%d " :
            "N/A",
        s
    );
    MENU_SET_ENABLED(ok);
    if (ok) MENU_SET_ICON(MNI_PERCENT, (s+4) * 100 / 8);
    else { MENU_SET_ICON(MNI_OFF, 0); MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "N/A"); }
}

static CONFIG_INT("picstyle.rec", picstyle_rec, 0);
static int picstyle_before_rec = 0; // if you use a custom picstyle during REC, the old one will be saved here

static char user_picstyle_name_1[50] = "";
static char user_picstyle_name_2[50] = "";
static char user_picstyle_name_3[50] = "";
static char user_picstyle_shortname_1[10] = "";
static char user_picstyle_shortname_2[10] = "";
static char user_picstyle_shortname_3[10] = "";

static void copy_picstyle_name(char* fullname, char* shortname, char* name)
{
    snprintf(fullname, 50, "%s", name);
    // CineStyle => CineS
    // Flaat_10p => Fl10p
    // Flaat_2   => Flaa2
    // Flaat03   => Fla03
    
    int L = strlen(name);
    shortname[0] = name[0];
    shortname[1] = name[1];
    shortname[2] = name[2];
    shortname[3] = name[3];
    shortname[4] = name[4];
    shortname[5] = '\0';
    
    if (isdigit(name[L-3]))
        shortname[2] = name[L-3];
    if (isdigit(name[L-3]) || isdigit(name[L-2]))
        shortname[3] = name[L-2];
    if (isdigit(name[L-3]) || isdigit(name[L-2]) || isdigit(name[L-1]))
        shortname[4] = name[L-1];
}

PROP_HANDLER(PROP_PC_FLAVOR1_PARAM)
{
    copy_picstyle_name(user_picstyle_name_1, user_picstyle_shortname_1, (char*) buf + 4);
}
PROP_HANDLER(PROP_PC_FLAVOR2_PARAM)
{
    copy_picstyle_name(user_picstyle_name_2, user_picstyle_shortname_2, (char*) buf + 4);
}
PROP_HANDLER(PROP_PC_FLAVOR3_PARAM)
{
    copy_picstyle_name(user_picstyle_name_3, user_picstyle_shortname_3, (char*) buf + 4);
}

static PROP_INT(PROP_PICSTYLE_OF_USERDEF1, picstyle_of_user1);
static PROP_INT(PROP_PICSTYLE_OF_USERDEF2, picstyle_of_user2);
static PROP_INT(PROP_PICSTYLE_OF_USERDEF3, picstyle_of_user3);


const char* get_picstyle_name(int raw_picstyle)
{
    return
        raw_picstyle == 0x81 ? "Standard" : 
        raw_picstyle == 0x82 ? "Portrait" :
        raw_picstyle == 0x83 ? "Landscape" :
        raw_picstyle == 0x84 ? "Neutral" :
        raw_picstyle == 0x85 ? "Faithful" :
        raw_picstyle == 0x86 ? "Monochrome" :
        raw_picstyle == 0x87 ? "Auto" :
        raw_picstyle == 0x21 ? (picstyle_of_user1 < 0x80 ? user_picstyle_name_1 : "UserDef1") :
        raw_picstyle == 0x22 ? (picstyle_of_user2 < 0x80 ? user_picstyle_name_2 : "UserDef2") :
        raw_picstyle == 0x23 ? (picstyle_of_user3 < 0x80 ? user_picstyle_name_3 : "UserDef3") : 
                                "Unknown";
}

const char* get_picstyle_shortname(int raw_picstyle)
{
    return
        raw_picstyle == 0x81 ? "Std." : 
        raw_picstyle == 0x82 ? "Port." :
        raw_picstyle == 0x83 ? "Land." :
        raw_picstyle == 0x84 ? "Neut." :
        raw_picstyle == 0x85 ? "Fait." :
        raw_picstyle == 0x86 ? "Mono." :
        raw_picstyle == 0x87 ? "Auto" :
        raw_picstyle == 0x21 ? (picstyle_of_user1 < 0x80 ? user_picstyle_shortname_1 : "User1") :
        raw_picstyle == 0x22 ? (picstyle_of_user2 < 0x80 ? user_picstyle_shortname_2 : "User2") :
        raw_picstyle == 0x23 ? (picstyle_of_user3 < 0x80 ? user_picstyle_shortname_3 : "User3") : 
                            "Unk.";
}
static MENU_UPDATE_FUNC(picstyle_display)
{
    int i = picstyle_rec && recording ? picstyle_before_rec : (int)lens_info.picstyle;
    
    MENU_SET_VALUE(
        get_picstyle_name(get_prop_picstyle_from_index(i))
    );

    
    if (picstyle_rec && is_movie_mode())
    {
        MENU_SET_VALUE(
            get_picstyle_shortname(get_prop_picstyle_from_index(i))
        );
        MENU_SET_RINFO(
            "REC:%s",
            get_picstyle_name(get_prop_picstyle_from_index(picstyle_rec))
        );
    }
    else MENU_SET_RINFO(
            "%d,%d,%d,%d",
            lens_get_from_other_picstyle_sharpness(i),
            lens_get_from_other_picstyle_contrast(i),
            ABS(lens_get_from_other_picstyle_saturation(i)) < 10 ? lens_get_from_other_picstyle_saturation(i) : 0,
            ABS(lens_get_from_other_picstyle_color_tone(i)) < 10 ? lens_get_from_other_picstyle_color_tone(i) : 0
        );
    
    MENU_SET_ENABLED(1);
}

static MENU_UPDATE_FUNC(picstyle_display_submenu)
{
    int p = get_prop_picstyle_from_index(lens_info.picstyle);
    MENU_SET_VALUE(
        "%s",
        get_picstyle_name(p)
    );
    MENU_SET_ENABLED(1);
}

static void
picstyle_toggle(void* priv, int sign )
{
    if (recording) return;
    int p = lens_info.picstyle;
    p = mod(p + sign - 1, NUM_PICSTYLES) + 1;
    if (p)
    {
        p = get_prop_picstyle_from_index(p);
        prop_request_change(PROP_PICTURE_STYLE, &p, 4);
    }
}

#ifdef FEATURE_REC_PICSTYLE

static MENU_UPDATE_FUNC(picstyle_rec_sub_display)
{
    if (!picstyle_rec)
    {
        MENU_SET_VALUE("OFF");
        return;
    }
    
    MENU_SET_VALUE(
        get_picstyle_name(get_prop_picstyle_from_index(picstyle_rec))
    );
    //~ MENU_SET_RINFO(
    if (info->x) bmp_printf(MENU_FONT_GRAY, info->x_val, info->y + font_large.height,
        "%d,%d,%d,%d",
        lens_get_from_other_picstyle_sharpness(picstyle_rec),
        lens_get_from_other_picstyle_contrast(picstyle_rec),
        ABS(lens_get_from_other_picstyle_saturation(picstyle_rec)) < 10 ? lens_get_from_other_picstyle_saturation(picstyle_rec) : 0,
        ABS(lens_get_from_other_picstyle_color_tone(picstyle_rec)) < 10 ? lens_get_from_other_picstyle_color_tone(picstyle_rec) : 0
    );
}

static void
picstyle_rec_sub_toggle( void * priv, int delta )
{
    if (recording) return;
    picstyle_rec = mod(picstyle_rec+ delta, NUM_PICSTYLES+1);
}

static void rec_picstyle_change(int rec)
{
    static int prev = -1;

    if (picstyle_rec)
    {
        if (prev == 0 && rec) // will start recording
        {
            picstyle_before_rec = lens_info.picstyle;
            int p = get_prop_picstyle_from_index(picstyle_rec);
            if (p)
            {
                NotifyBox(2000, "Picture Style : %s", get_picstyle_name(p));
                prop_request_change(PROP_PICTURE_STYLE, &p, 4);
            }
        }
        else if (prev == 2 && rec == 0) // recording => will stop
        {
            int p = get_prop_picstyle_from_index(picstyle_before_rec);
            if (p)
            {
                NotifyBox(2000, "Picture Style : %s", get_picstyle_name(p));
                prop_request_change(PROP_PICTURE_STYLE, &p, 4);
            }
            picstyle_before_rec = 0;
        }
    }
    prev = rec;
}

#endif // REC pic style
#endif // pic style


static void redraw_after_task(int msec)
{
    msleep(msec);
    redraw();
}

void redraw_after(int msec)
{
    task_create("redraw", 0x1d, 0, redraw_after_task, (void*)msec);
}

#ifdef CONFIG_50D
PROP_HANDLER(PROP_SHOOTING_TYPE)
{
    int rec = (shooting_type == 4 ? 2 : 0);

    #ifdef FEATURE_REC_NOTIFY
    rec_notify_trigger(rec);
    #endif
    
    #ifdef FEATURE_REC_PICSTYLE
    rec_picstyle_change(rec);
    #endif
    
    #ifdef FEATURE_MOVIE_RECORDING_50D_SHUTTER_HACK
    shutter_btn_rec_do(rec);
    #endif
}
void mvr_rec_start_shoot(){}
#else
void mvr_rec_start_shoot(int rec)
{
    #ifdef FEATURE_REC_NOTIFY
    rec_notify_trigger(rec);
    #endif
    
    #ifdef FEATURE_REC_PICSTYLE
    rec_picstyle_change(rec);
    #endif
}
#endif

#ifdef FEATURE_FLASH_TWEAKS
static void
flash_ae_toggle(void* priv, int sign )
{
    int ae = lens_info.flash_ae;
    int newae = ae + sign * (ABS(ae + sign) <= 24 ? 4 : 8);
    lens_set_flash_ae(newae);
}

static MENU_UPDATE_FUNC(flash_ae_display)
{
    int ae_ev = (lens_info.flash_ae) * 10 / 8;
    MENU_SET_VALUE(
        "%s%d.%d EV",
        FMT_FIXEDPOINT1S(ae_ev)
    );
    MENU_SET_ENABLED(ae_ev);
}
#endif

#ifdef FEATURE_EXPO_ISO_HTP
static void
htp_toggle( void * priv )
{
    int htp = get_htp();
    if (htp)
        set_htp(0);
    else
        set_htp(1);
}

static MENU_UPDATE_FUNC(htp_display)
{
    int htp = get_htp();
    MENU_SET_VALUE(htp ? "ON" : "OFF");
    MENU_SET_ENABLED(htp);
}
#endif

#ifdef FEATURE_LV_ZOOM_SETTINGS
static void zoom_x5_x10_toggle(void* priv, int delta)
{
    *(int*)priv = ! *(int*)priv;
    
    if (zoom_disable_x5 && zoom_disable_x10) // can't disable both at the same time
    {
        if (priv == &zoom_disable_x5) zoom_disable_x10 = 0;
        else zoom_disable_x5 = 0;
    }
}

static void zoom_lv_face_step()
{
#ifdef CONFIG_LIVEVIEW
    if (!lv) return;
    if (recording) return;
    /*if (face_zoom_request && lv_dispsize == 1 && !recording)
    {
        if (lvaf_mode == 2 && wait_for_lv_err_msg(200)) // zoom request in face detect mode; temporary switch to live focus mode
        {
            int afmode = 1;
            int afx = afframe[2];
            int afy = afframe[3];
            prop_request_change(PROP_LVAF_MODE, &afmode, 4);
            msleep(100);
            afframe[2] = afx;
            afframe[3] = afy;
            prop_request_change(PROP_LV_AFFRAME, afframe, 0);
            msleep(1);
            set_lv_zoom(5);
            msleep(1);
        }
        else if (lvaf_mode == 1) // back from temporary live focus mode
        {
            int afmode = 2;
            prop_request_change(PROP_LVAF_MODE, &afmode, 4);
            msleep(100);
            face_zoom_request = 0;
            //~ bmp_printf(FONT_LARGE, 10, 50, "       ");
        }
        else // cancel zoom request
        {
            msleep(100);
            face_zoom_request = 0;
            //~ bmp_printf(FONT_LARGE, 10, 50, "Zoom :(");
        }
    }*/
    
    if (zoom_halfshutter && is_manual_focus())
    {
        int hs = get_halfshutter_pressed();
        if (hs && lv_dispsize == 1)
        {
            msleep(200);
            if (hs && lv_dispsize == 1)
            {
                zoom_was_triggered_by_halfshutter = 1;
                int zoom = zoom_disable_x10 ? 5 : 10;
                set_lv_zoom(zoom);
                msleep(100);
            }
        }
        if (!hs && lv_dispsize > 1 && zoom_was_triggered_by_halfshutter)
        {
            zoom_was_triggered_by_halfshutter = 0;
            set_lv_zoom(1);
            msleep(100);
        }
    }
#endif
}

static int zoom_focus_ring_disable_time = 0;
static int zoom_focus_ring_flag = 0;
void zoom_focus_ring_trigger() // called from prop handler
{
    if (recording) return;
    if (lv_dispsize > 1) return;
    if (gui_menu_shown()) return;
    if (!DISPLAY_IS_ON) return;
    int zfr = (zoom_focus_ring == 1 && is_manual_focus());
    if (!zfr) return;
    zoom_focus_ring_flag = 1;
}
void zoom_focus_ring_engage() // called from shoot_task
{
    if (recording) return;
    if (lv_dispsize > 1) return;
    if (gui_menu_shown()) return;
    if (!DISPLAY_IS_ON) return;
    int zfr = (zoom_focus_ring && is_manual_focus());
    if (!zfr) return;
    zoom_focus_ring_disable_time = ms100_clock + 5000;
    int zoom = zoom_disable_x10 ? 5 : 10;
    set_lv_zoom(zoom);
}
static void zoom_focus_ring_step()
{
    int zfr = (zoom_focus_ring && is_manual_focus());
    if (!zfr) return;
    if (recording) return;
    if (!DISPLAY_IS_ON) return;
    if (zoom_focus_ring_disable_time && ms100_clock > zoom_focus_ring_disable_time && !get_halfshutter_pressed())
    {
        if (lv_dispsize > 1) set_lv_zoom(1);
        zoom_focus_ring_disable_time = 0;
    }
}
/*
int zoom_x5_x10_step()
{
    if (zoom_disable_x5 && lv_dispsize == 5)
    {
        set_lv_zoom(10);
        return 1;
    }
    if (zoom_disable_x10 && lv_dispsize == 10)
    {
        set_lv_zoom(1);
        return 1;
    }
    return 0;
}*/


int handle_zoom_x5_x10(struct event * event)
{
    if (!lv) return 1;
    if (recording) return 1;
    
    if (!zoom_disable_x5 && !zoom_disable_x10) return 1;
    #ifdef CONFIG_600D
    if (get_disp_pressed()) return 1;
    #endif
    
    if (event->param == BGMT_PRESS_ZOOMIN_MAYBE && liveview_display_idle() && !gui_menu_shown())
    {
        set_lv_zoom(lv_dispsize > 1 ? 1 : zoom_disable_x5 ? 10 : 5);
        return 0;
    }
    return 1;
}

// called from some prop_handlers (shoot.c and zebra.c)
void zoom_sharpen_step()
{
#ifdef FEATURE_LV_ZOOM_SHARP_CONTRAST
    if (!zoom_sharpen) return;

    static int co = 100;
    static int sa = 100;
    static int sh = 100;
    
    if (zoom_sharpen && lv && lv_dispsize > 1 && (!HALFSHUTTER_PRESSED || zoom_was_triggered_by_halfshutter) && !gui_menu_shown() && !bulb_ramp_calibration_running) // bump contrast/sharpness
    {
        if (co == 100)
        {
            co = lens_get_contrast();
            sh = lens_get_sharpness();
            sa = lens_get_saturation();
            lens_set_contrast(4);
            lens_set_sharpness(7);
            lens_set_saturation(MAX(0, sa));
        }
    }
    else // restore contrast/sharpness
    {
        if (co < 100)
        {
            lens_set_contrast(co);
            lens_set_sharpness(sh);
            lens_set_saturation(sa);
            co = sa = sh = 100;
        }
    }
#endif
}

#ifdef CONFIG_EXPSIM
static void restore_expsim_task(int es)
{
    for (int i = 0; i < 50; i++)
    {
        lens_wait_readytotakepic(64);
        set_expsim(es);
        msleep(300);
        if (get_expsim() == es) return;
    }
    NotifyBox(5000, "Could not restore ExpSim :(");
    info_led_blink(5, 50, 50);
}
#endif

// to be called from the same places as zoom_sharpen_step
void zoom_auto_exposure_step()
{
#ifdef FEATURE_LV_ZOOM_AUTO_EXPOSURE
    if (!zoom_auto_exposure) return;

    static int es = -1;
    // static int aem = -1;
    
    if (lv && lv_dispsize > 1 && (!HALFSHUTTER_PRESSED || zoom_was_triggered_by_halfshutter) && !gui_menu_shown() && !bulb_ramp_calibration_running)
    {
        // photo mode: disable ExpSim
        // movie mode 5D2: disable ExpSim
        // movie mode small cams: change PROP_AE_MODE_MOVIE
        if (is_movie_mode())
        {
            #ifdef CONFIG_5D2
            if (es == -1)
            {
                es = get_expsim();
                set_expsim(0);
            }
            /* #else // unstable
                #ifndef CONFIG_50D
                if (aem == -1)
                {
                    aem = ae_mode_movie;
                    int x = 0;
                    prop_request_change(PROP_AE_MODE_MOVIE, &x, 4);
                }
                #endif */
            #endif
        }
        else // photo mode
        {
            if (es == -1)
            {
                es = get_expsim();
                set_expsim(0);
            }
        }
    }
    else // restore things back
    {
        if (es >= 0)
        {
            // not sure why, but when taking a picture, expsim can't be restored;
            // workaround: create a task that retries a few times
            task_create("restore_expsim", 0x1a, 0, restore_expsim_task, (void*)es);
            es = -1;
        }
        /* if (aem >= 0)
        {
            prop_request_change(PROP_AE_MODE_MOVIE, &aem, 4);
            aem = -1;
        }*/
    }
#endif
}

#endif // FEATURE_LV_ZOOM_SETTINGS

#ifdef FEATURE_HDR_BRACKETING
static MENU_UPDATE_FUNC(hdr_display)
{
    if (!hdr_enabled)
    {
        MENU_SET_VALUE("OFF");
    }
    else
    {
        MENU_SET_VALUE("%s%Xx%d%sEV,%s%s%s",
            hdr_type == 0 ? "" : hdr_type == 1 ? "F," : "DOF,",
            hdr_steps == 1 ? 10 : hdr_steps, // trick: when steps=1 (auto) it will display A :)
            hdr_stepsize / 8,
            ((hdr_stepsize/4) % 2) ? ".5" : "",
            hdr_sequence == 0 ? "0--" : hdr_sequence == 1 ? "0-+" : "0++",
            hdr_delay ? ",2s" : "",
            hdr_iso == 1 ? ",ISO" : hdr_iso == 2 ? ",iso" : ""
        );
    }

    if (aeb_setting)
    {
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Turn off Canon bracketing (AEB)!");
    }
    
}

// 0,4,8,12,16, 24, 32, 40
static MENU_SELECT_FUNC(hdr_stepsize_toggle)
{
    int h = hdr_stepsize;
    delta *= (h+delta < 16 ? 4 : 8);
    h += delta;
    if (h > 40) h = 4;
    if (h < 4) h = 40;
    hdr_stepsize = h;
}
#endif

int is_bulb_mode()
{
#ifdef CONFIG_BULB
    if (shooting_mode == SHOOTMODE_BULB) return 1;
    if (shooting_mode != SHOOTMODE_M) return 0;
    if (lens_info.raw_shutter != 0xC) return 0;
    return 1;
#else
    return 0;
#endif
}

static int is_bulb_mode_or_bulb_ramping()
{
#ifdef CONFIG_BULB
    if (BULB_EXPOSURE_CONTROL_ACTIVE) return 1; // this will force bulb mode when needed
    return is_bulb_mode();
#else
    return 0;
#endif
}

void ensure_bulb_mode()
{
#ifdef CONFIG_BULB

    while (lens_info.job_state) msleep(100);

    #ifdef CONFIG_SEPARATE_BULB_MODE
        int a = lens_info.raw_aperture;
        set_shooting_mode(SHOOTMODE_BULB);
        if (get_expsim() == 2) set_expsim(1);
        lens_set_rawaperture(a);
    #else
        if (shooting_mode != SHOOTMODE_M)
            set_shooting_mode(SHOOTMODE_M);
        int shutter = 12; // huh?!
        prop_request_change( PROP_SHUTTER, &shutter, 4 );
        prop_request_change( PROP_SHUTTER_ALSO, &shutter, 4 );
    #endif
    
    SetGUIRequestMode(0);
    while (!display_idle()) msleep(100);
    
#endif
}

// returns old drive mode if changed, -1 if nothing changed
int set_drive_single()
{
    if (drive_mode != DRIVE_SINGLE
        #ifdef DRIVE_SILENT
        && drive_mode != DRIVE_SILENT
        #endif
        )
    {
        int orig_mode = drive_mode;
        #ifdef DRIVE_SILENT
        lens_set_drivemode(DRIVE_SILENT);
        #else
        lens_set_drivemode(DRIVE_SINGLE);
        #endif
        return orig_mode;
    }
    return -1;
}

// goes to Bulb mode and takes a pic with the specified duration (ms)
void
bulb_take_pic(int duration)
{
#ifdef CONFIG_BULB

    extern int ml_taking_pic;
    if (ml_taking_pic) return;
    ml_taking_pic = 1;


    //~ NotifyBox(2000,  "Bulb: %d ", duration); msleep(2000);
    duration = MAX(duration, BULB_MIN_EXPOSURE) + BULB_EXPOSURE_CORRECTION;
    int s0r = lens_info.raw_shutter; // save settings (for restoring them back)
    int m0r = shooting_mode;

    ensure_bulb_mode();
    
    lens_setup_af(AF_DISABLE);
    
    msleep(100);
    
    int d0 = set_drive_single();
    //~ NotifyBox(3000, "BulbStart (%d)", duration); msleep(1000);
    mlu_lock_mirror_if_needed();
    
    SW1(1,300);
    
    int t_start = get_ms_clock_value();
    int t_end = t_start + duration;
    SW2(1,300);
    
    //~ msleep(duration);
    //int d = duration/1000;
    while (get_ms_clock_value() <= t_end - 1500)
    {
        msleep(100);

        // number of seconds that passed
        static int prev_s = 0;
        int s = (get_ms_clock_value() - t_start) / 1000;
        if (s == prev_s) continue;
        prev_s = s;
        
        // check the following at every second:
        
        // for 550D and other cameras that may keep the display on during bulb exposures -> always turn it off
        if (DISPLAY_IS_ON && s==1) fake_simple_button(BGMT_INFO);

        // tell how many minutes the exposure will take
        if (s == 2)
        {
            int d = duration / 1000;
            if (d/60) { beep_times(d/60); msleep(500); }
        }
        
        // turn off the LED - no light pollution, please :)
        // but blink it quickly every 10 seconds to have some feedback
        if (s % 10 == 1) { _card_led_on(); msleep(10); _card_led_off(); }

        // blink twice every minute, and beep as many times as elapsed minutes
        if (s % 60 == 1) { msleep(200); _card_led_on(); msleep(10); _card_led_off(); if (s/60) beep_times(s/60); }
        
        // exposure was canceled earlier by user
        if (job_state_ready_to_take_pic()) 
        {
            beep();
            break;
        }
    }
    
    while (get_ms_clock_value() < t_end && !job_state_ready_to_take_pic())
        msleep(MIN_MSLEEP);
    
    //~ NotifyBox(3000, "BulbEnd");
    
    SW2(0,0);
    SW1(0,0);
    
    lens_wait_readytotakepic(64);
    lens_cleanup_af();
    if (d0 >= 0) lens_set_drivemode(d0);
    prop_request_change( PROP_SHUTTER, &s0r, 4 );
    prop_request_change( PROP_SHUTTER_ALSO, &s0r, 4);
    set_shooting_mode(m0r);
    msleep(200);
    
    ml_taking_pic = 0;
#endif
}

#ifdef FEATURE_BULB_TIMER
static void bulb_toggle(void* priv, int delta)
{
    bulb_duration_index = mod(bulb_duration_index + delta - 1, COUNT(timer_values) - 1) + 1;
    bulb_shutter_valuef = (float)timer_values[bulb_duration_index];
    #ifdef FEATURE_EXPO_OVERRIDE
    bv_auto_update();
    #endif
}

static MENU_UPDATE_FUNC(bulb_display)
{
    int d = BULB_SHUTTER_VALUE_S;
    if (!bulb_duration_index) d = 0;

    if (bulb_timer)
        MENU_SET_VALUE(
            format_time_hours_minutes_seconds(d)
        );
    else if (is_bulb_mode() && intervalometer_running) // even if it's not enabled, it will be used for intervalometer
        MENU_SET_VALUE(
            "OFF (%s)",
            format_time_hours_minutes_seconds(d)
        );
    
    if (!is_bulb_mode()) MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Bulb timer only works in BULB mode");
    if (entry->selected && intervalometer_running) timelapse_calc_display(entry, info);
}

static MENU_UPDATE_FUNC(bulb_display_submenu)
{
    int d = BULB_SHUTTER_VALUE_S;
    if (!bulb_duration_index) d = 0;
    MENU_SET_VALUE(
        format_time_hours_minutes_seconds(d)
    );
}
#endif

#ifdef FEATURE_MLU
static void mlu_selftimer_update()
{
    if (MLU_SELF_TIMER)
    {
        int mlu_auto_value = (drive_mode == DRIVE_SELFTIMER_2SEC || drive_mode == DRIVE_SELFTIMER_REMOTE) ? 1 : 0;
        int mlu_current_value = get_mlu();
        if (mlu_auto_value != mlu_current_value)
        {
            set_mlu(mlu_auto_value); // shooting mode, ML decides to toggle MLU
        }
    }
}

static void
mlu_update()
{
    if (mlu_mode == 0)
        set_mlu(mlu_auto ? 1 : 0);
    else if (mlu_mode == 1)
    {
        if (mlu_auto) mlu_selftimer_update();
        else set_mlu(0);
    }
    else
        set_mlu(0);
}

static void
mlu_toggle_mode( void * priv, int delta )
{
    #ifdef FEATURE_MLU_HANDHELD
    mlu_mode = mod(mlu_mode + delta, 3);
    #else
    mlu_mode = !mlu_mode;
    #endif
    mlu_update();
}

static void
mlu_toggle( void * priv, int delta )
{
    #ifndef CONFIG_1100D
    mlu_auto = !mlu_auto;
    mlu_update();
    #endif
}

static MENU_UPDATE_FUNC(mlu_display)
{
    MENU_SET_VALUE(
        MLU_SELF_TIMER ? (get_mlu() ? "SelfTimer (ON)" : "SelfTimer (OFF)")
        : MLU_HANDHELD ? (mlu_handheld_shutter ? "HandH,1/2-1/125" : "Handheld")
        : MLU_ALWAYS_ON ? "Always ON"
        : get_mlu() ? "ON" : "OFF"
    );
    if (mlu_mode == 2 && 
        (
            HDR_ENABLED || 
            trap_focus || 
            is_bulb_mode() || 
            intervalometer_running || 
            motion_detect || 
            aeb_setting ||
            #ifdef FEATURE_AUDIO_REMOTE_SHOT
            audio_release_running ||
            #endif
            0)
        )
    {
        static char msg[60];
        snprintf(msg, sizeof(msg), "Handhedld MLU does not work with %s.",
            HDR_ENABLED ? "HDR bracketing" :
            trap_focus ? "trap focus" :
            is_bulb_mode() ? "bulb shots" :
            intervalometer_running ? "intervalometer" :
            motion_detect ? "motion detection" :
            aeb_setting ? "Canon bracketing (AEB)" :
            #ifdef FEATURE_AUDIO_REMOTE_SHOT
            audio_release_running ? "audio remote" :
            #endif
            "?!"
        );
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, msg);
    }
}
#endif // FEATURE_MLU

#ifdef FEATURE_PICQ_DANGEROUS
static MENU_UPDATE_FUNC(picq_display)
{
    int raw = pic_quality & 0x60000;
    int rawsize = pic_quality & 0xF;
    int jpegtype = pic_quality >> 24;
    int jpegsize = (pic_quality >> 8) & 0xF;
    MENU_SET_VALUE(
        "%s%s%s%s%s",
        rawsize == 1 ? "M" : rawsize == 2 ? "S" : "",
        raw ? "RAW" : "",
        jpegtype != 4 && raw ? "+" : "",
        jpegtype == 4 ? "" : jpegsize == 0 ? "Large" : jpegsize == 1 ? "Med" : "Small",
        jpegtype == 2 ? "Coarse" : jpegtype == 3 ? "Fine" : ""
    );
    MENU_SET_ENABLED(1);
}

static int picq_next(int p)
{
    switch(pic_quality)
    {
        case PICQ_RAW: return PICQ_MRAW;
        case PICQ_MRAW: return PICQ_SRAW;
        case PICQ_SRAW: return PICQ_RAW_JPG_LARGE_FINE;
        case PICQ_RAW_JPG_LARGE_FINE: return PICQ_MRAW_JPG_LARGE_FINE;
        case PICQ_MRAW_JPG_LARGE_FINE: return PICQ_SRAW_JPG_LARGE_FINE;
        case PICQ_SRAW_JPG_LARGE_FINE: return PICQ_SRAW_JPG_MED_FINE;
        case PICQ_SRAW_JPG_MED_FINE: return PICQ_SRAW_JPG_SMALL_FINE;
        case PICQ_SRAW_JPG_SMALL_FINE: return PICQ_LARGE_FINE;
        case PICQ_LARGE_FINE: return PICQ_MED_FINE;
        case PICQ_MED_FINE: return PICQ_SMALL_FINE;
    }
    return PICQ_RAW;
}

static void picq_toggle(void* priv)
{
    int newp = picq_next(pic_quality);
    set_pic_quality(newp);
}
#endif

#ifdef FEATURE_BULB_RAMPING

static int bulb_ramping_adjust_iso_180_rule_without_changing_exposure(int intervalometer_delay)
{
    int raw_shutter_0 = shutter_ms_to_raw(BULB_SHUTTER_VALUE_MS);
    int raw_iso_0 = lens_info.raw_iso;
    
    int ideal_shutter_speed_ms = intervalometer_delay * 1000 / 2; // 180 degree rule => ideal value
    int ideal_shutter_speed_raw = shutter_ms_to_raw(ideal_shutter_speed_ms);

    int delta = 0;  // between 90 and 180 degrees => OK

    if (ideal_shutter_speed_raw > raw_shutter_0 + 4)
        delta = 8; // shutter too slow (more than 270 degrees -- ideal value) => boost ISO

    if (ideal_shutter_speed_raw < raw_shutter_0 - 4)
        delta = -8; // shutter too fast (less than 128 degrees) => lower ISO
    
    if (delta) // should we change something?
    {
        int max_auto_iso = auto_iso_range & 0xFF;
        int new_raw_iso = COERCE(lens_info.raw_iso + delta, MIN_ISO, max_auto_iso); // Allowed values: ISO 100 (or 200 with HTP) ... max auto ISO from Canon menu
        delta = new_raw_iso - raw_iso_0;
        if (delta == 0) return 0; // nothing to change
        float new_bulb_shutter = 
            delta ==  8 ? bulb_shutter_valuef / 2 :
            delta == -8 ? bulb_shutter_valuef * 2 :
            bulb_shutter_valuef;
        
        lens_set_rawiso(new_raw_iso); // try to set new iso
        msleep(100);
        if (lens_info.raw_iso == new_raw_iso) // new iso accepted
        {
            bulb_shutter_valuef = new_bulb_shutter;
            return 1;
        }
        // if we are here, either iso was refused
        // => restore old iso, just to be sure
        lens_set_rawiso(raw_iso_0); 
    }
    return 0; // nothing changed
}

static FILE* bramp_log_file = 0;
static int bramp_init_state = 0;
static int bramp_init_done = 0;
static int bramp_reference_level = 0;
static int bramp_measured_level = 0;
//~ int bramp_level_ev_ratio = 0;
static int bramp_hist_dirty = 0;
static int bramp_ev_reference_x1000 = 0;
static int bramp_prev_shot_was_bad = 1;
static float bramp_u1 = 0; // for the feedback controller: command at previous step
static int bramp_last_exposure_rounding_error_evx1000;

static int measure_brightness_level(int initial_wait)
{
    msleep(initial_wait);
    // hack so the playback histogram won't disturb us
    // todo: remove dependency on hist_build
    int ans;
    BMP_LOCK(
        if (bramp_hist_dirty)
        {
            struct vram_info * vram = get_yuv422_vram();
            hist_build(vram->vram, vram->width, vram->pitch);
            bramp_hist_dirty = 0;
        }
        ans = hist_get_percentile_level(bramp_percentile);
    )
    //~ get_out_of_play_mode(500);
    return ans;
}

static void bramp_change_percentile(int dir)
{
    ASSERT(PLAY_MODE);
    NotifyBoxHide();
    bramp_percentile = COERCE(bramp_percentile + dir * 5, 5, 95);
    
    int i;
    for (i = 0; i <= 20; i++)
    {
        bramp_reference_level = measure_brightness_level(0); // at bramp_percentile
        if (bramp_reference_level > 230) bramp_percentile = COERCE(bramp_percentile - 5, 5, 95);
        else if (bramp_reference_level < 25) bramp_percentile = COERCE(bramp_percentile + 5, 5, 95);
        else break;
    }
    if (i >= 20) { NotifyBox(1000, "Image not properly exposed"); return; }

    int level_8bit = bramp_reference_level;
    int level_8bit_plus = level_8bit + 5; //hist_get_percentile_level(bramp_percentile + 5) * 255 / 100;
    int level_8bit_minus = level_8bit - 5; //hist_get_percentile_level(bramp_percentile - 5) * 255 / 100;
    clrscr();
    highlight_luma_range(level_8bit_minus, level_8bit_plus, COLOR_BLUE, COLOR_WHITE);
    hist_highlight(level_8bit);
    bmp_printf(FONT_LARGE, 50, 400, 
        "Meter for %s\n"
        "(%2d%% luma at %dth percentile)",
        bramp_percentile < 40 ? "shadows" : bramp_percentile < 70 ? "midtones" : "highlights",
        bramp_reference_level*100/255, 0,
        bramp_percentile);
}

int handle_bulb_ramping_keys(struct event * event)
{
    if (intervalometer_running && bramp_init_state && PLAY_MODE)
    {
        switch (event->param)
        {
            case BGMT_PRESS_SET:
            {
                bramp_init_state = 0; // OK :)
                NotifyBox(1000, "OK");
                return 1;
            }
            case BGMT_WHEEL_LEFT:
            case BGMT_WHEEL_RIGHT:
            {
                int dir = event->param == BGMT_WHEEL_LEFT ? -1 : 1;
                bramp_change_percentile(dir);
                //~ NotifyBoxHide();
                return 0;
            }
        }
    }
    
    // test interpolation on luma-ev curve
    //~ for (int i = 0; i < 255; i += 5)
        //~ bramp_plot_luma_ev_point(i, COLOR_GREEN1);

    return 1;
}

static void flip_zoom()
{
    if (!lv) return;
    if (is_movie_mode())
    {
        if (recording) return;
        if (video_mode_crop) return;
    }
    
    // flip zoom mode back and forth to apply settings instantly
    int zoom0 = lv_dispsize;
    int zoom1 = zoom0 == 10 ? 5 : zoom0 == 5 ? 1 : 10;
    set_lv_zoom(zoom1);
    set_lv_zoom(zoom0);
}


static int bramp_measure_luma(int delay)
{
    ASSERT(lv);
    ASSERT(lv_dispsize > 1);
    ASSERT(get_expsim());
    ASSERT(shooting_mode == SHOOTMODE_M);
    //~ ASSERT(LVAE_DISP_GAIN); // display gain can also be zero, no problem
    
    msleep(delay);
    // we are in zoom mode, histogram not normally updated => we can reuse the buffer
    //~ struct vram_info * vram = get_yuv422_vram();
    //~ hist_build(vram->vram, vram->width, vram->pitch);
    //~ bramp_hist_dirty = 0;
    //~ return hist_get_percentile_level(50) * 255/100; // median => much more robust in cluttered scenes, but more sensitive to noise
    int Y,U,V;
    get_spot_yuv(200, &Y, &U, &V);
    return Y;
}

// still useful for bulb ramping
static int bramp_zoom_toggle_needed = 0; // for 600D and some new lenses?!
static int bramp_set_display_gain_and_measure_luma(int gain)
{
    gain = COERCE(gain, 0, 65534);
    //~ bmp_printf(FONT_MED, 100, 100, "%d ", gain);
    //~ set_display_gain_equiv(gain);
    call("lvae_setdispgain", gain);
    if (lv_dispsize == 1) set_lv_zoom(5);
    if (bramp_zoom_toggle_needed)
    {
        flip_zoom();
        msleep(1000);
    }
    #ifdef BRAMP_CALIBRATION_DELAY
    msleep(BRAMP_CALIBRATION_DELAY);
    #else
    msleep(500);
    #endif
    return bramp_measure_luma(0);
}

static int crit_dispgain_50(int gain)
{
    if (!lv) return 0;
    int Y = bramp_set_display_gain_and_measure_luma(gain);
    NotifyBox(1000, "Gain=%d => Luma=%d ", gain, Y);
    return 128 - Y;
}


static int bramp_luma_ev[11];

static void bramp_plot_luma_ev()
{
    for (int i = -5; i < 5; i++)
    {
        int luma1 = bramp_luma_ev[i+5];
        int luma2 = bramp_luma_ev[i+6];
        int x1 =  350 + i * 20;
        int x2 =  350 + (i+1) * 20;
        int y1 =  240 - (luma1-128)/2;
        int y2 =  240 - (luma2-128)/2;
        draw_line(x1, y1, x2, y2, COLOR_RED);
        draw_line(x1, y1+1, x2, y2+1, COLOR_RED);
        draw_line(x1, y1+2, x2, y2+2, COLOR_WHITE);
        draw_line(x1, y1-1, x2, y2-1, COLOR_WHITE);
    }
    int x1 =  350 - 5 * 20;
    int x2 =  350 + 5 * 20;
    int y1 =  240 - 128/2;
    int y2 =  240 + 128/2;
    bmp_draw_rect(COLOR_WHITE, x1, y1, x2-x1, y2-y1);
}

static int bramp_luma_to_ev_x100(int luma)
{
    int i;
    for (i = -5; i < 5; i++)
        if (luma <= bramp_luma_ev[i+5]) break;
    i = COERCE(i-1, -5, 4);
    // now, luma is between luma1 and luma2
    // EV correction is between i EV and (i+1) EV => linear approximation
    int luma1 = bramp_luma_ev[i+5];
    int luma2 = bramp_luma_ev[i+6];
    int k = (luma-luma1) * 1000 / (luma2-luma1);
    //~ return i * 100;
    int ev_x100 = ((1000-k) * i + k * (i+1))/10;
    //~ NotifyBox(1000, "%d,%d=>%d", luma, i, ev_x100);
    return COERCE(ev_x100, -500, 500);
}

static void bramp_plot_luma_ev_point(int luma, int color)
{
    luma = COERCE(luma, 0, 255);
    int ev = bramp_luma_to_ev_x100(luma);
    ev = COERCE(ev, -500, 500);
    int x = 350 + ev * 20 / 100;
    int y = 240 - (luma-128)/2;
    for (int r = 0; r < 5; r++)
    {
        draw_circle(x, y, r, color);
        draw_circle(x+1, y, r, color);
    }
    draw_circle(x, y, 6, COLOR_WHITE);
}

static void bramp_plot_holy_grail_hysteresis(int luma_ref)
{
    luma_ref = COERCE(luma_ref, 0, 255);
    int ev = bramp_luma_to_ev_x100(luma_ref);
    int ev1 = ev - BRAMP_LRT_HOLY_GRAIL_STOPS * 100;
    int ev2 = ev + BRAMP_LRT_HOLY_GRAIL_STOPS * 100;
    int x1 = 350 + ev1 * 20 / 100;
    int x2 = 350 + ev2 * 20 / 100;
    int y1 = 240 - (-128)/2;
    int y2 = 240 - ( 128)/2;

    draw_line(x1, y1, x1, y2, COLOR_BLACK);
    draw_line(x2, y1, x2, y2, COLOR_WHITE);
    draw_line(x1+1, y1, x1+1, y2, COLOR_WHITE);
    draw_line(x2+1, y1, x2+1, y2, COLOR_BLACK);

}

#define BRAMP_SHUTTER_0 56 // 1 second exposure => just for entering compensation
//~ static int bramp_temporary_exposure_compensation_ev_x100 = 0;

// bulb ramping calibration cache
static CONFIG_INT("bramp.calib.sig", bramp_calib_sig, 0);
static CONFIG_INT("bramp.calib.m5", bramp_calib_cache_m5, 0);
static CONFIG_INT("bramp.calib.m4", bramp_calib_cache_m4, 0);
static CONFIG_INT("bramp.calib.m3", bramp_calib_cache_m3, 0);
static CONFIG_INT("bramp.calib.m2", bramp_calib_cache_m2, 0);
static CONFIG_INT("bramp.calib.m1", bramp_calib_cache_m1, 0);
static CONFIG_INT("bramp.calib.0", bramp_calib_cache_0, 0);
static CONFIG_INT("bramp.calib.1", bramp_calib_cache_1, 0);
static CONFIG_INT("bramp.calib.2", bramp_calib_cache_2, 0);
static CONFIG_INT("bramp.calib.3", bramp_calib_cache_3, 0);
static CONFIG_INT("bramp.calib.4", bramp_calib_cache_4, 0);
static CONFIG_INT("bramp.calib.5", bramp_calib_cache_5, 0);

static void bramp_cleanup()
{
    if (bramp_log_file)
    {
        FIO_CloseFile(bramp_log_file);
        bramp_log_file = 0;
    }
}

static void bulb_ramping_init()
{
    if (bramp_init_done) return;

    if (is_movie_mode())
    {
        NotifyBox(2000, "Please switch to photo mode.");
        msleep(2000);
        intervalometer_stop();
        return;
    }
    
    if (BULB_EXPOSURE_CONTROL_ACTIVE) set_shooting_mode(SHOOTMODE_M);
    
    msleep(2000);

    static char fn[50];
    for (int i = 0; i < 100; i++)
    {
        snprintf(fn, sizeof(fn), CARD_DRIVE "ML/LOGS/BRAMP%02d.LOG", i);
        uint32_t size;
        if( FIO_GetFileSize( fn, &size ) != 0 ) break;
        if (size == 0) break;
    }
    bramp_log_file = FIO_CreateFileEx(fn);

    bulb_duration_index = 0; // disable bulb timer to avoid interference
    bulb_shutter_valuef = raw2shutterf(lens_info.raw_shutter);
    bramp_ev_reference_x1000 = 0;
    bramp_last_exposure_rounding_error_evx1000 = 0;
    //~ bramp_temporary_exposure_compensation_ev_x100 = 0;
    bramp_prev_shot_was_bad = 1; // force full correction at first step
    bramp_u1 = 0.0;
    
    if (!bramp_auto_exposure) 
    {
        bramp_init_done = 1;
        return;
    }

    // if calibration is cached, load it from config file
    int calib_sig = lens_info.picstyle * 123 + lens_get_contrast() + (get_htp() ? 17 : 23);
    if (calib_sig == (int)bramp_calib_sig)
    {
        bramp_luma_ev[0] = bramp_calib_cache_m5;
        bramp_luma_ev[1] = bramp_calib_cache_m4;
        bramp_luma_ev[2] = bramp_calib_cache_m3;
        bramp_luma_ev[3] = bramp_calib_cache_m2;
        bramp_luma_ev[4] = bramp_calib_cache_m1;
        bramp_luma_ev[5] = bramp_calib_cache_0;
        bramp_luma_ev[6] = bramp_calib_cache_1;
        bramp_luma_ev[7] = bramp_calib_cache_2;
        bramp_luma_ev[8] = bramp_calib_cache_3;
        bramp_luma_ev[9] = bramp_calib_cache_4;
        bramp_luma_ev[10] = bramp_calib_cache_5;

        my_fprintf(bramp_log_file, "Luma curve: cached: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n", bramp_calib_cache_m5, bramp_calib_cache_m4, bramp_calib_cache_m3, bramp_calib_cache_m2, bramp_calib_cache_m1, bramp_calib_cache_0, bramp_calib_cache_1, bramp_calib_cache_2, bramp_calib_cache_3, bramp_calib_cache_4, bramp_calib_cache_5);

    }
    else // compute calibration from scratch
    {

        NotifyBox(100000, "Calibration...");
        bulb_ramp_calibration_running = 1;

        set_shooting_mode(SHOOTMODE_M);
        if (!lv) force_liveview();
        int e0 = get_expsim();
        int iso0 = lens_info.raw_iso;
        int s0 = lens_info.raw_shutter;
        set_expsim(1);

    calib_start:
        SW1(1,50); // reset power management timers
        SW1(0,50);
        set_lv_zoom(lv_dispsize == 10 ? 5 : 10);
        
        lens_set_rawiso(COERCE(iso0, 80, 120));

        NotifyBox(2000, "Testing display gain...");
        int Y;
        int Yn = bramp_set_display_gain_and_measure_luma(100);
        int Yp = bramp_set_display_gain_and_measure_luma(65535);
        bramp_zoom_toggle_needed = (ABS(Yn - Yp) < 10);
        if (bramp_zoom_toggle_needed)
        {
            Yn = bramp_set_display_gain_and_measure_luma(100);
            Yp = bramp_set_display_gain_and_measure_luma(65535);
        }
        bramp_set_display_gain_and_measure_luma(0);
        int ok = (ABS(Yn - Yp) > 10);
        if (!ok)
        {
            set_expsim(e0);
            NotifyBox(5000, "Cannot calibrate.        \n"
                            "Please report to ML devs."); msleep(5000);
            intervalometer_stop();
            goto end;
        }
        
        // first try to brighten the image
        while (bramp_measure_luma(500) < 128)
        {
            if (lens_info.raw_iso+8 <= 120) // 6400
            {
                NotifyBox(2000, "Too dark, increasing ISO...");
                lens_set_rawiso(lens_info.raw_iso + 8);
                continue;
            }
            else if (lens_info.raw_shutter-8 >= 20)
            {
                NotifyBox(2000, "Too dark, increasing exp.time...");
                lens_set_rawshutter(lens_info.raw_shutter - 8);
                continue;
            }
            else break;
        }
        
        // then try to darken 
        while (bramp_measure_luma(500) > 150)
        {
            if (lens_info.raw_iso-8 >= 80) // 200
            {
                NotifyBox(2000, "Too bright, decreasing ISO...");
                lens_set_rawiso(lens_info.raw_iso - 8);
                continue;
            }
            else if (lens_info.raw_shutter <= 152) // 1/4000
            {
                NotifyBox(2000, "Too bright, decreasing exp.time...");
                lens_set_rawshutter(lens_info.raw_shutter + 8);
                continue;
            }
            else break;
        }
        
        // at this point, the image should be roughly OK exposed
        // we can now play only with display gain
        
        
        int gain0 = bin_search(128, 2000, crit_dispgain_50);
        Y = bramp_set_display_gain_and_measure_luma(gain0);
        if (ABS(Y-128) > 2) 
        {
            NotifyBox(1000, "Scene %s, retrying...", 
                gain0 > 1900 ? "too dark" :
                gain0 < 130 ? "too bright" : 
                "not static"
            ); 
            msleep(500);
            goto calib_start;
        }
        
        for (int i = -5; i <= 5; i++)
        {
            Y = bramp_set_display_gain_and_measure_luma(gain0 * (1 << (i+10)) / 1024);
            NotifyBox(500, "%d EV => luma=%d  ", i, Y);
            if (i == 0) // here, luma should be 128
            {
                if (ABS(Y-128) > 2) {msleep(500); NotifyBox(1000, "Middle check failed, retrying..."); msleep(1000); goto calib_start;}
                else Y = 128;
            }
            int prev_Y = i > -5 ? bramp_luma_ev[i+5-1] : 0;
            if (Y < prev_Y-3) 
            {
                msleep(500); NotifyBox(1000, "Decreasing curve (%d->%d), retrying...", prev_Y, Y); msleep(1000); 
                goto calib_start;
            }
            bramp_luma_ev[i+5] = MAX(Y, prev_Y);
            bramp_plot_luma_ev();
            //~ set_display_gain(1<<i);
        }
        
        // final check
        Y = bramp_set_display_gain_and_measure_luma(gain0);
        msleep(500);
        if (ABS(Y-128) > 2) { msleep(500); NotifyBox(1000, "Final check failed (%d), retrying...", Y); msleep(1000); goto calib_start;}

        // calibration accepted :)

        bulb_ramp_calibration_running = 0;
        bramp_set_display_gain_and_measure_luma(0);
        set_expsim(e0);
        lens_set_rawiso(iso0);
        lens_set_rawshutter(s0);

        fake_simple_button(BGMT_LV);
        msleep(1000);

        // save calibration results in config file
        bramp_calib_sig = calib_sig;
        bramp_calib_cache_m5 = bramp_luma_ev[0];
        bramp_calib_cache_m4 = bramp_luma_ev[1];
        bramp_calib_cache_m3 = bramp_luma_ev[2];
        bramp_calib_cache_m2 = bramp_luma_ev[3];
        bramp_calib_cache_m1 = bramp_luma_ev[4];
        bramp_calib_cache_0  = bramp_luma_ev[5];
        bramp_calib_cache_1  = bramp_luma_ev[6];
        bramp_calib_cache_2  = bramp_luma_ev[7];
        bramp_calib_cache_3  = bramp_luma_ev[8];
        bramp_calib_cache_4  = bramp_luma_ev[9];
        bramp_calib_cache_5  = bramp_luma_ev[10];
        my_fprintf(bramp_log_file, "Luma curve: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n", bramp_calib_cache_m5, bramp_calib_cache_m4, bramp_calib_cache_m3, bramp_calib_cache_m2, bramp_calib_cache_m1, bramp_calib_cache_0, bramp_calib_cache_1, bramp_calib_cache_2, bramp_calib_cache_3, bramp_calib_cache_4, bramp_calib_cache_5);

    }

    fake_simple_button(BGMT_PLAY);
    msleep(1000);
    
    if (!PLAY_MODE) { NotifyBox(1000, "BRamp: could not go to PLAY mode"); msleep(2000); intervalometer_stop(); goto end; }
    
    //~ bramp_level_ev_ratio = 0;
    bramp_measured_level = 0;
    
    bramp_init_state = 1;
    
    msleep(200);
    bramp_hist_dirty = 1;
    bramp_change_percentile(0); // show current selection;

    NotifyBox(100000, "Choose a well-exposed photo  \n"
                      "and tonal range to meter for.\n"
                      "Keys: arrows, main dial, SET.");
    
    void* play_buf = get_yuv422_vram()->vram;
    while (PLAY_MODE && bramp_init_state == 1)
    {
        if (get_yuv422_vram()->vram != play_buf) // another image selected
        {
            bramp_hist_dirty = 1;
            bramp_change_percentile(0); // update current selection
            play_buf = get_yuv422_vram()->vram;
        }
        msleep(100);
    }
    if (!PLAY_MODE) { intervalometer_stop(); goto end; }
    
    bramp_init_done = 1; // OK :)

    set_shooting_mode(SHOOTMODE_M);
    lens_set_rawshutter(BRAMP_SHUTTER_0);
    if (lv) fake_simple_button(BGMT_LV);
    msleep(1000);
    set_shooting_mode(SHOOTMODE_M);

    my_fprintf(bramp_log_file, "Reference level: %d at %d-th percentile\n", bramp_reference_level, bramp_percentile);

end:
    bulb_ramp_calibration_running = 0;
}

// monitor shutter speed and aperture and consider your changes as exposure compensation for bulb ramping
/*
static void bramp_temporary_exposure_compensation_update()
{
    if (!bramp_init_done) return;
    if (!bulb_ramping_enabled) return;
    int shutter = (int)lens_info.raw_shutter;
    int aperture = (int)lens_info.raw_aperture;

    static int prev_shutter = 0;
    static int prev_aperture = 0;

    int ec_rounded_abs = (ABS(bramp_temporary_exposure_compensation_ev_x100) + 5) / 10;

    if (prev_shutter > 0xC && shutter > 0xC)
    {
        int ec_delta_shutter = -(shutter - prev_shutter) * 100/8;
        int ec_delta_aperture = (aperture - prev_aperture) * 100/8;
        int ec_delta = ec_delta_shutter + ec_delta_aperture;
        if (ec_delta)
        {
            bramp_temporary_exposure_compensation_ev_x100 += ec_delta;
            ec_rounded_abs = (ABS(bramp_temporary_exposure_compensation_ev_x100) + 5) / 10;
            bmp_printf(FONT_LARGE, 0, 0, 
                "Exp.Comp for next shot: %s%d.%d EV",
                bramp_temporary_exposure_compensation_ev_x100 > 0 ? "+" : "-",
                ec_rounded_abs / 10, ec_rounded_abs % 10
            );
        }
    }

    // extend compensation range beyond normal shutter speed limits
    if (ec_rounded_abs == 0 && shutter != BRAMP_SHUTTER_0) // cancel drift
    {
        lens_set_rawshutter(BRAMP_SHUTTER_0);
        shutter = lens_info.raw_shutter;
    }
    else if (prev_shutter > 144) // 1/2000
    {
        lens_set_rawshutter(prev_shutter - 32);
        shutter = lens_info.raw_shutter;
    }
    else if (prev_shutter < 24) // 16 seconds
    {
        lens_set_rawshutter(prev_shutter + 32);
        shutter = lens_info.raw_shutter;
    }

    prev_shutter = shutter;
    prev_aperture = aperture;
}*/

/*
static int brightness_samples_a[11][11];
static int brightness_samples_b[11][11];
static int brightness_samples_delta[11][11];

int measure_brightness_difference()
{
    for (int i = 0; i <= 10; i++)
    {
        for (int j = 0; j <= 10; j++)
        {
            brightness_samples_a[i][j] = brightness_samples_b[i][j];
            int Y,U,V;
            int dx = (j-5) * 65;
            int dy = (i-5) * 40;
            get_spot_yuv_ex(10, dx, dy, &Y, &U, &V, 1, 0);
            brightness_samples_b[i][j] = Y;
            brightness_samples_delta[i][j] = bramp_luma_to_ev_x100(brightness_samples_b[i][j]) - bramp_luma_to_ev_x100(brightness_samples_a[i][j]);
            int xcb = os.x0 + os.x_ex/2 + dx;
            int ycb = os.y0 + os.y_ex/2 + dy;
            bmp_printf(SHADOW_FONT(FONT_SMALL), xcb, ycb, "%d ", brightness_samples_delta[i][j]);
        }
    }
}*/

static void compute_exposure_for_next_shot()
{
    #ifdef CONFIG_5DC
    return;
    #endif
    
    static int prev_file_number = 12345;
    if (prev_file_number == file_number)
    {
        my_fprintf(bramp_log_file, "Picture not taken\n");
        NotifyBox(2000, "Picture not taken :("); msleep(2000);
        return;
    }
    prev_file_number = file_number;
    
    int mf_steps = bramp_manual_speed_focus_steps_per_shot;
    int manual_evx1000 = bramp_manual_speed_evx1000_per_shot;

    // don't go slower than intervalometer, and reserve 2 seconds just in case
    float shutter_max = (float)MAX(2, timer_values[interval_timer_index] - 2);
    // also, don't go faster than 1/4000 (or 1/8000)
    float shutter_min = 1.0 / (FASTEST_SHUTTER_SPEED_RAW == 160 ? 8000 : 4000);
    
    if (bramp_auto_exposure)
    {
        //~ msleep(200);
        ensure_play_or_qr_mode_after_shot();
        //~ draw_livev_for_playback();

        //~ NotifyBox(2000, "Exposure for next shot..."); msleep(1000);

        //~ NotifyBoxHide();
        //~ msleep(500);
        bramp_hist_dirty = 1;
        bramp_measured_level = measure_brightness_level(0);
        int mev = bramp_luma_to_ev_x100(bramp_measured_level);
        //~ NotifyBox(1000, "Brightness level: %d (%s%d.%02d EV)", bramp_measured_level, FMT_FIXEDPOINT2(mev)); msleep(1000);

        my_fprintf(bramp_log_file, "%04d luma=%3d rounderr=%3d ", file_number, bramp_measured_level, bramp_last_exposure_rounding_error_evx1000);

        /**
         * Use a discrete feedback controller, designed such as the closed loop system 
         * has two real poles placed at f, where f is the smoothing factor (0.1 ... 0.9).
         *
         *  r = expo reference (0, unless manual ramping is active)
         *  e = expo difference          
         *  u = expo correction
         *  T = log2(exposure time)                  +----------< brightness change from real world (sunrise, sunset)
         *                                           |   +------< measurement noise (let's say around 0.03 EV stdev)
         *              _______        ______        |   |
         * r     _  e  |       |   u  |  1   |   T   V   V
         * -----( )----| Bramp |------|(z-1) |------(+)-(+)----+----> picture
         *     - ^     |_______|      |______|                 |
         *       |_____________________________________________| y = brightness level (EV); luma=bramp_reference_level => 0 EV.
         * 
         * P = 1/(z-1) - integrator. 
         * Rationale: the exposure correction at each step is accumulated.
         * 
         * Closed loop system:
         * S = B*P / (1 + B*P)
         *
         * We want to fix the closed loop response (S), so we try to find out the controller B by inverting the process P
         * => B = S / (P - S*P)
         *
         * We will place both closed-loop poles at smoothing factor value f in range [0.1 ... 0.9] and keep the static gain at 1.
         * S = z / (z-f) / (z-f) / (1 / (1-f) / (1-f))
         *
         * Result:
         *
         *      b*z          b
         * B = -----  = -----------
         *     z - a     1 - a*z^-1
         *
         * with:
         *    b = f^2 - 2f + 1
         *    a = f^2
         * 
         * Computing exposure correction:
         * 
         * u = B/A * e
         *    => u(k) = b e(k) + a u(k-1)
         * 
         * Exception: if ABS(e) > 2 EV, apply almost-full correction (B = 0.9) to bring it quickly back on track, 
         * without caring about flicker.
         * 
         */

        // unit: 0.01 EV
        int y_x100 = bramp_luma_to_ev_x100(bramp_measured_level) - bramp_luma_to_ev_x100(bramp_reference_level) - bramp_last_exposure_rounding_error_evx1000/10;
        int r_x100 = bramp_ev_reference_x1000/10;
        int e_x100 = COERCE(r_x100 - y_x100, -mev-500, -mev+500);
        // positive e => picture should be brightened

        my_fprintf(bramp_log_file, "y=%4d r=%4d e=%4d => ", y_x100, r_x100, e_x100);

        if (BRAMP_LRT_HOLY_GRAIL)
        {
            // only apply an integer amount of correction
            int step_x100 = BRAMP_LRT_HOLY_GRAIL_STOPS * 100;
            int c = (ABS(e_x100) / step_x100) * BRAMP_LRT_HOLY_GRAIL_STOPS;
            if (e_x100 < 0) c = -c;
            float u = c;
            bulb_shutter_valuef *= powf(2, u);

            int corr_x100 = (int) roundf(u * 100.0f);
            my_fprintf(bramp_log_file, "LRT: e=%4d u=%4d ", e_x100, corr_x100);

            NotifyBox(2000, "Exposure difference: %s%d.%02d EV \n"
                            "Exposure correction: %s%d.%02d EV ",
                            FMT_FIXEDPOINT2S(e_x100),
                            FMT_FIXEDPOINT2S(corr_x100)
                );
            msleep(500);
        }
        else if (BRAMP_FEEDBACK_LOOP)
        {
            // a difference of more than 2 EV will be fully corrected right away
            int expo_diff_too_big = 
                (e_x100 > 200 && bulb_shutter_valuef < shutter_max) ||
                (e_x100 < -200 && bulb_shutter_valuef > shutter_min);
            int should_apply_full_correction_immediately = (expo_diff_too_big || bramp_prev_shot_was_bad) && !BRAMP_LRT_HOLY_GRAIL;
            bramp_prev_shot_was_bad = expo_diff_too_big;

            if (should_apply_full_correction_immediately)
            {
                // big change in brightness - request a new picture without waiting, and apply full correction
                // most probably, user changed ND filters or moved the camera
                
                NotifyBox(1000, "Exposure difference: %s%d.%02d EV ", FMT_FIXEDPOINT2S(e_x100));
                msleep(500);

                float cor = COERCE((float)e_x100 / 111.0f, -3.0f, 3.0f);
                bulb_shutter_valuef *= powf(2, cor); // apply 90% of correction, but not more than 3 EV, to keep things stable
                
                // use high iso to adjust faster, then go back at low iso
                for (int i = 0; i < 5; i++)
                    bulb_ramping_adjust_iso_180_rule_without_changing_exposure(expo_diff_too_big ? 1 : timer_values[interval_timer_index]);
                    
                bulb_shutter_valuef = COERCE(bulb_shutter_valuef, shutter_min, shutter_max);

                // set Canon shutter speed close to bulb one (just for display)
                lens_set_rawshutter(shutterf_to_raw(bulb_shutter_valuef));

                my_fprintf(bramp_log_file, "harsh: cor=%d shutter=%6dms iso=%4d\n", (int)roundf(cor * 100.0f), BULB_SHUTTER_VALUE_MS, lens_info.iso);

                // force next shot to be taken quicker
                intervalometer_next_shot_time = seconds_clock;
                return;
            }
            else // small change in brightness - apply only a small amount of correction to keep things smooth
            {    // see comments above for the feedback loop design
                bramp_ev_reference_x1000 += manual_evx1000;

                float u = 0;

                // auto adjust the smooth factor based on exposure difference over last few frames
                // big expo difference => more aggressive correction
                // small expo difference => calm down, less flicker
                
                static int expo_diff = 0;
                expo_diff = (e_x100 * e_x100 / 100 + expo_diff * 9) / 10;
                
                // don't change the smooth factor too fast
                // let it become aggressive quickly (fast response to sudden ramps) 
                // but don't let it calm down too fast, to get some time for settling
                static int expo_diff_filtered = 0;
                if (expo_diff > expo_diff_filtered)
                     expo_diff_filtered = MIN(expo_diff, expo_diff_filtered + 50);
                else if (expo_diff < expo_diff_filtered - 10)
                     expo_diff_filtered = MAX(expo_diff + 10, expo_diff_filtered - 5);
                
                // try to follow the ramps at around 0.5 EV behind
                int fi = get_smooth_factor_from_max_ev_speed(expo_diff_filtered * 2);
                
                // plug this adaptive smooth factor into our feedback loop
                // here we have a small trick for reducing the side effects of changing the smooth factor while running
                float f = (float)fi / 100.0f;
                float e = (float)e_x100 / 100.0f;

                float b = f*f - 2*f + 1;
                float a = f*f;
                
                u = b*e + bramp_u1;
                bramp_u1 = a*u;
               
                bulb_shutter_valuef *= powf(2, u);

                // display some info
                int corr_x100 = (int) roundf(u * 100.0f);
                NotifyBox(2000, "Exposure difference: %s%d.%02d EV \n"
                                "Exposure correction: %s%d.%02d EV ",
                                FMT_FIXEDPOINT2S(e_x100),
                                FMT_FIXEDPOINT2S(corr_x100)
                    );  

                my_fprintf(bramp_log_file, "soft: f=%2d e=%4d u=%4d ", fi, (int)roundf(e*100), corr_x100);

                msleep(500);
            }
        }
    }

    // apply manual exposure ramping, if any
    if (manual_evx1000)
        bulb_shutter_valuef *= powf(2, (float)manual_evx1000 / 1000.0f);
    
    if (BULB_EXPOSURE_CONTROL_ACTIVE)
    {
        // adjust ISO if needed, and check shutter speed limits
        for (int i = 0; i < 5; i++)
            bulb_ramping_adjust_iso_180_rule_without_changing_exposure(timer_values[interval_timer_index]);
        bulb_shutter_valuef = COERCE(bulb_shutter_valuef, shutter_min, shutter_max);
        
        // set Canon shutter speed close to bulb one (just for display)
        lens_set_rawshutter(shutterf_to_raw(bulb_shutter_valuef));

        int shutter = (int)roundf(bulb_shutter_valuef * 100000.0f);
        my_fprintf(bramp_log_file, "shutter=%3d.%05ds iso=%4d\n", shutter/100000, shutter%100000, lens_info.iso);
    }
        
    if (mf_steps && !is_manual_focus())
    {
        while (lens_info.job_state) msleep(100);
        msleep(300);
        get_out_of_play_mode(500);
        if (!lv) 
        {
            msleep(500);
            if (!lv) force_liveview();
        }
        set_lv_zoom(5);
        msleep(1000);
        NotifyBox(1000, "Focusing...");
        lens_focus_enqueue_step(-mf_steps);
        msleep(1000);
        set_lv_zoom(1);
        msleep(500);
    }
}

static void bulb_ramping_showinfo()
{
    int s = BULB_SHUTTER_VALUE_MS;
    //~ int manual_evx1000 = (int)bramp_manual_speed_evx1000_per_shot;
    //~ int rate_x1000 = bramp_light_changing_rate_evx1000 + manual_evx1000;

    bmp_printf(FONT_MED, 50, 350, 
        //~ "Reference level (%2dth prc) :%3d%%    \n"
        //~ "Measured  level (%2dth prc) :%3d%%    \n"
        //~ "Level/EV ratio             :%3d%%/EV \n"
        //~ " EV rate :%s%d.%03d/shot\n"
        " Shutter :%3d.%03d s  \n"
        " ISO     :%5d (range: %d...%d)",
        //~ bramp_percentile, bramp_reference_level, 0,
        //~ bramp_percentile, bramp_measured_level, 0,
        //~ bramp_level_ev_ratio, 0,
        //~ FMT_FIXEDPOINT3S(rate_x1000)
        s / 1000, s % 1000,
        lens_info.iso, get_htp() ? 200 : 100, raw2iso(auto_iso_range & 0xFF)
        );
    
    if (bramp_auto_exposure && (PLAY_MODE || QR_MODE))
    {
        bramp_plot_luma_ev();
        bramp_plot_luma_ev_point(bramp_measured_level, COLOR_RED);
        bramp_plot_luma_ev_point(bramp_reference_level, COLOR_BLUE);
        
        if (BRAMP_LRT_HOLY_GRAIL)
            bramp_plot_holy_grail_hysteresis(bramp_reference_level);
    }
}

#endif // FEATURE_BULB_RAMPING

int expo_value_rounding_ok(int raw)
{
    if (raw == lens_info.raw_aperture_min || raw == lens_info.raw_aperture_max) return 1;
    int r = raw % 8;
    if (r != 0 && r != 4 && r != 3 && r != 5)
        return 0;
    return 1;
}

#ifdef FEATURE_EXPO_LOCK

static CONFIG_INT("expo.lock", expo_lock, 0);
static CONFIG_INT("expo.lock.tv", expo_lock_tv, 0);
static CONFIG_INT("expo.lock.av", expo_lock_av, 1);
static CONFIG_INT("expo.lock.iso", expo_lock_iso, 1);

// keep this constant
static int expo_lock_value = 12345;

static MENU_UPDATE_FUNC(expo_lock_display)
{
    if (expo_lock)
    {
        MENU_SET_VALUE(
            "%s%s%s",
            expo_lock_tv ? "Tv," : "",
            expo_lock_av ? "Av," : "",
            expo_lock_iso ? "ISO," : ""
        );
        info->value[strlen(info->value)-1] = 0; // trim last comma
    }

    if (lens_info.name[0] && lens_info.raw_aperture && lens_info.raw_shutter && lens_info.raw_iso && !menu_active_but_hidden())
    {
        int Av = APEX_AV(lens_info.raw_aperture);
        int Tv = APEX_TV(lens_info.raw_shutter);
        int Sv = APEX_SV(lens_info.iso_equiv_raw);
        int Bv = Av + Tv - Sv;
        Bv = Bv * 10/8;

        MENU_SET_RINFO(
            "Bv%s%d.%d",
            FMT_FIXEDPOINT1(Bv)
        );
    }

    if (HDR_ENABLED)
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "This feature does not work with HDR bracketing.");
}

// Tv + Av - Sv, in APEX units
static int expo_lock_get_current_value()
{
    return APEX_TV(lens_info.raw_shutter) + APEX_AV(lens_info.raw_aperture) - APEX_SV(lens_info.iso_equiv_raw);
}

// returns the remainder
static int expo_lock_adjust_tv(int delta)
{
    if (!delta) return 0;
    int old_tv = lens_info.raw_shutter;
    int new_tv = old_tv + delta;
    new_tv = COERCE(new_tv, 16, FASTEST_SHUTTER_SPEED_RAW);

    if (!expo_value_rounding_ok(new_tv)) // try to change it by a small amount, so Canon firmware will accept it
    {
        int new_tv_plus1  = COERCE(new_tv + 1, 16, FASTEST_SHUTTER_SPEED_RAW);
        int new_tv_minus1 = COERCE(new_tv - 1, 16, FASTEST_SHUTTER_SPEED_RAW);
        int new_tv_plus2  = COERCE(new_tv + 2, 16, FASTEST_SHUTTER_SPEED_RAW);
        int new_tv_minus2 = COERCE(new_tv - 2, 16, FASTEST_SHUTTER_SPEED_RAW);
        
        if (expo_value_rounding_ok(new_tv_plus1)) new_tv = new_tv_plus1;
        else if (expo_value_rounding_ok(new_tv_minus1)) new_tv = new_tv_minus1;
        else if (expo_value_rounding_ok(new_tv_plus2)) new_tv = new_tv_plus2;
        else if (expo_value_rounding_ok(new_tv_minus2)) new_tv = new_tv_minus2;
    }

    lens_set_rawshutter(new_tv);
    msleep(100);
    return delta - lens_info.raw_shutter + old_tv;
}

static int expo_lock_adjust_av(int delta)
{
    if (!delta) return 0;
    if (!lens_info.raw_aperture) return delta; // manual lens
    
    int old_av = lens_info.raw_aperture;
    int new_av = old_av + delta;
    new_av = COERCE(new_av, lens_info.raw_aperture_min, lens_info.raw_aperture_max);
    
    if (!expo_value_rounding_ok(new_av)) // try to change it by a small amount, so Canon firmware will accept it
    {
        int new_av_plus1  = COERCE(new_av + 1, lens_info.raw_aperture_min, lens_info.raw_aperture_max);
        int new_av_minus1 = COERCE(new_av - 1, lens_info.raw_aperture_min, lens_info.raw_aperture_max);
        int new_av_plus2  = COERCE(new_av + 2, lens_info.raw_aperture_min, lens_info.raw_aperture_max);
        int new_av_minus2 = COERCE(new_av - 2, lens_info.raw_aperture_min, lens_info.raw_aperture_max);
        
        if (expo_value_rounding_ok(new_av_plus1)) new_av = new_av_plus1;
        else if (expo_value_rounding_ok(new_av_minus1)) new_av = new_av_minus1;
        else if (expo_value_rounding_ok(new_av_plus2)) new_av = new_av_plus2;
        else if (expo_value_rounding_ok(new_av_minus2)) new_av = new_av_minus2;
    }
    
    lens_set_rawaperture(new_av);
    msleep(100);
    return delta - lens_info.raw_aperture + old_av;
}

static int expo_lock_adjust_iso(int delta)
{
    if (!delta) return 0;
    
    int old_iso = lens_info.raw_iso;
    int delta_r = ((delta + 4 * SGN(delta)) / 8) * 8;
    int new_iso = old_iso - delta_r;

    int max_auto_iso = auto_iso_range & 0xFF;
    if (new_iso > max_auto_iso && old_iso < max_auto_iso)
        new_iso = max_auto_iso;
    
    lens_set_rawiso(new_iso);
    msleep(100);
    return delta - old_iso + lens_info.raw_iso;
}

static void expo_lock_step()
{
    if (!expo_lock)
    {
        expo_lock_value = expo_lock_get_current_value();
        return;
    }
    
    if (shooting_mode != SHOOTMODE_M) return;
    if (!lens_info.raw_iso) return;
    if (ISO_ADJUSTMENT_ACTIVE) return;
    if (HDR_ENABLED) return;
    
    int max_auto_iso = auto_iso_range & 0xFF;
    
    if (expo_lock_value == 12345)
        expo_lock_value = expo_lock_get_current_value();
    
    static int p_tv = 0;
    static int p_av = 0;
    static int p_iso = 0;
    if (!p_tv) p_tv = lens_info.raw_shutter;
    if (!p_av) p_av = lens_info.raw_aperture;
    if (!p_iso) p_iso = lens_info.raw_iso;
    
    int r_iso = lens_info.raw_iso;
    int r_tv = lens_info.raw_shutter;
    int r_av = lens_info.raw_aperture;
    
    static int what_changed = 0; // 1=iso, 2=Tv, 3=Av
    
    if (p_iso != r_iso) what_changed = 1; // iso changed
    else if (p_tv != r_tv) what_changed = 2;
    else if (p_av != r_av) what_changed = 3;
    p_iso = r_iso;
    p_tv = r_tv;
    p_av = r_av;
    
    // let's see if user changed some setting for which exposure isn't locked => update expo reference value
    if ((what_changed == 1 && !expo_lock_iso) ||
        (what_changed == 2 && !expo_lock_tv) ||
        (what_changed == 3 && !expo_lock_av))
        {
            expo_lock_value = expo_lock_get_current_value();
            return;
        }

    int diff = expo_lock_value - expo_lock_get_current_value();
    //~ NotifyBox(1000, "%d %d ", diff, what_changed);

    if (diff >= -2 && diff <= 1) 
        return; // difference is too small, ignore it
    
    if (what_changed == 1 && expo_lock_iso)
    {
            int current_value = expo_lock_get_current_value();
            int delta = expo_lock_value - current_value;
            if (expo_lock_iso == 1)
            {
                delta = expo_lock_adjust_tv(delta);
                if (ABS(delta) >= 4) delta = expo_lock_adjust_av(delta);
            }
            else
            {
                delta = expo_lock_adjust_av(delta);
                if (ABS(delta) >= 4) delta = expo_lock_adjust_tv(delta);
            }
            //~ delta = expo_lock_adjust_iso(delta);
    }
    else if (what_changed == 2 && expo_lock_tv)
    {
        int current_value = expo_lock_get_current_value();
        int delta = expo_lock_value - current_value;
        if (expo_lock_tv == 1 || (lens_info.raw_iso > max_auto_iso - 8 && delta < 0))
        {
            delta = expo_lock_adjust_av(delta);
            if (ABS(delta) > 4) delta = expo_lock_adjust_iso(delta);
        }
        else
        {
            if (ABS(delta) > 4) delta = expo_lock_adjust_iso(delta);
            if (ABS(delta) >= 8) delta = expo_lock_adjust_av(delta);
        }
        //~ delta = expo_lock_adjust_tv(delta);
    }
    else if (what_changed == 3 && expo_lock_av)
    {
        int current_value = expo_lock_get_current_value();
        int delta = expo_lock_value - current_value;
        if (expo_lock_av == 1 || (lens_info.raw_iso > max_auto_iso - 8 && delta < 0))
        {
            delta = expo_lock_adjust_tv(delta);
            if (ABS(delta) > 4) delta = expo_lock_adjust_iso(delta);
        }
        else
        {
            if (ABS(delta) > 4) delta = expo_lock_adjust_iso(delta);
            if (ABS(delta) >= 8) delta = expo_lock_adjust_tv(delta);
        }
        //~ delta = expo_lock_adjust_av(delta);
    }
    
    p_tv = lens_info.raw_shutter;
    p_av = lens_info.raw_aperture;
    p_iso = lens_info.raw_iso;
    
}

#endif

#ifdef FEATURE_EXPO_PRESET

static CONFIG_INT("expo.preset", expo_preset, 0);
static CONFIG_INT("expo.pre.iso", pre_iso, 1234);
static CONFIG_INT("expo.pre.tv", pre_tv, 1234);
static CONFIG_INT("expo.pre.av", pre_av, 1234);
static CONFIG_INT("expo.pre.kelvin", pre_kelvin, 1234);

static void expo_preset_toggle()
{
    int c_iso = lens_info.raw_iso;
    int c_tv = lens_info.raw_shutter;
    int c_av = lens_info.raw_aperture;
    int c_kelvin = lens_info.kelvin;

    if (pre_iso == 1234) pre_iso = c_iso;
    if (pre_tv == 1234) pre_tv = c_tv;
    if (pre_av == 1234) pre_av = c_av; 
    if (pre_kelvin == 1234) pre_kelvin = c_kelvin;

    int ap = values_aperture[raw2index_aperture(pre_av)];
    if (lv)
        NotifyBox(2000, 
            "ISO %d 1/%d f/%d.%d %dK", 
            raw2iso(pre_iso), 
            (int)roundf(1/raw2shutterf(pre_tv)), 
            ap/10, ap%10, 
            lens_info.wb_mode == WB_KELVIN ? pre_kelvin : 0
        );
    else
        beep();
    
    if (pre_tv != 12) lens_set_rawshutter(pre_tv); else ensure_bulb_mode();
    lens_set_rawiso(pre_iso);
    lens_set_rawaperture(pre_av);
    if (lens_info.wb_mode == WB_KELVIN)
        lens_set_kelvin(pre_kelvin);
    
    pre_iso = c_iso;
    pre_tv = c_tv;
    pre_av = c_av;
    pre_kelvin = c_kelvin;
}

int handle_expo_preset(struct event * event)
{
    if (!expo_preset) return 1;
    
    if ((event->param == BGMT_PRESS_SET && expo_preset == 1) ||
        (event->param == BGMT_INFO && expo_preset == 2))
    {
        if (display_idle())
        {
            expo_preset_toggle();
            return 0;
        }
    }
    
    return 1;
}
#endif // FEATURE_EXPO_PRESET

static MENU_UPDATE_FUNC(pics_at_once_update)
{
    if (!pics_to_take_at_once)
    {
        MENU_SET_ENABLED(0);
    }
    if (HDR_ENABLED)
    {
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "No burst bracketing series, please.");
    }
}

static MENU_UPDATE_FUNC(use_af_update)
{
    if (HDR_ENABLED)
    {
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "Autofocus and bracketing don't mix.");
    }
}

// in lcdsensor.c
extern MENU_UPDATE_FUNC(lcd_release_display);

extern int voice_tags; // beep.c

static struct menu_entry shoot_menus[] = {
    #ifdef FEATURE_HDR_BRACKETING
    {
        .name = "Advanced Bracket",
        .priv = &hdr_enabled,
        .update  = hdr_display,
        .max  = 1,
        .help = "Advanced bracketing (expo, flash, DOF). Press shutter once.",
        .works_best_in = DEP_PHOTO_MODE | DEP_M_MODE | DEP_MANUAL_ISO,
        .submenu_width = 710,
        .children =  (struct menu_entry[]) {
            {
                .name = "Bracket type",
                .priv       = &hdr_type,
                .max = 2,
                .icon_type = IT_DICE,
                .choices = CHOICES("Exposure (Tv,Ae)", "Exposure (Flash)", "DOF (Aperture)"),
                .help  = "Choose the variables to bracket:",
                .help2 = "Expo bracket. M: changes shutter. Others: changes AEcomp.\n"
                         "Flash bracket: change flash exposure compensation.\n"
                         "DOF bracket: keep exposure constant, change Av/Tv ratio.",
            },
            {
                .name = "Frames",
                .priv       = &hdr_steps,
                .min = 1,
                .max = 9,
                .icon_type = IT_PERCENT,
                .choices = CHOICES("Autodetect", "2", "3", "4", "5", "6", "7", "8", "9"),
                .help = "Number of bracketed shots. Can be computed automatically.",
            },
            {
                .name = "EV increment",
                .priv       = &hdr_stepsize,
                .select     = hdr_stepsize_toggle,
                .min = 4,
                .max = 40,
                .unit = UNIT_1_8_EV,
                .icon_type = IT_PERCENT,
                .help = "Exposure difference between two frames.",
            },
            {
                .name = "Sequence",
                .priv       = &hdr_sequence,
                .max = 2,
                .help = "Bracketing sequence order / type. Zero is always first.",
                .icon_type = IT_DICE,
                .choices = CHOICES("0 - --", "0 - + -- ++", "0 + ++"),
            },
            #ifndef CONFIG_5DC
            {
                .name = "2-second delay",
                .priv       = &hdr_delay,
                .max = 1,
                .help  = "Delay before starting the exposure.",
                .help2 = "Only used if you start bracketing by pressing the shutter.",
                .choices = CHOICES("OFF", "Auto"),
            },
            #endif
            {
                .name = "ISO shifting",
                .priv       = &hdr_iso,
                .max = 2,
                .help =  "Also use ISO as bracket variable. Range: 100 - max AutoISO.",
                .help2 = " \n"
                         "Full: try ISO bracket first. If out of range, use main var.\n"
                         "Half: Bracket with both ISO (50%) and main variable (50%).\n",
                .choices = CHOICES("OFF", "Full", "Half"),
                .icon_type = IT_DICE_OFF,
            },
            MENU_EOL
        },
    },
    #endif
    
    #ifdef FEATURE_INTERVALOMETER
    {
        .name = "Intervalometer",
        .priv       = &intervalometer_running,
        .max        = 1,
        .update     = intervalometer_display,
        .help = "Take pictures at fixed intervals (for timelapse).",
        .submenu_width = 700,
        .works_best_in = DEP_PHOTO_MODE,
        .children =  (struct menu_entry[]) {
            {
                .name = "Take a pic every",
                .priv       = &interval_timer_index,
                .update     = interval_timer_display,
                .select     = interval_timer_toggle,
                .icon_type  = IT_PERCENT,
                .help = "Duration between two shots.",
            },
            {
                .name = "Start after",
                .priv       = &interval_start_timer_index,
                .update     = interval_start_after_display,
                .select     = interval_timer_toggle,
                .icon_type  = IT_PERCENT,
                .help = "Start the intervalometer after X seconds / minutes / hours.",
            },
            {
                .name = "Stop after",
                .priv       = &interval_stop_after,
                .max = 5000, // 5000 shots
                .update     = interval_stop_after_display,
                .icon_type  = IT_PERCENT_LOG_OFF,
                .help = "Stop the intervalometer after taking X shots.",
            },

            #ifdef FEATURE_BULB_RAMPING
                #ifndef FEATURE_HISTOGRAM
                #error This requires FEATURE_HISTOGRAM.
                #endif

            {
                .name = "Auto ExpoRamp",
                .priv       = &bramp_auto_exposure,
                .max = 2,
                .icon_type = IT_DICE_OFF,
                .choices = CHOICES("OFF", "Smooth ramping", "LRT Holy Grail 1EV"),
                .help = "Choose the algorithm for automatic bulb ramping.",
                .help2 = " \n"
                        "Feedback loop. Works best with expos longer than 1 second.\n"
                        "Expo is adjusted in 1EV integer steps. vimeo.com/26083323",
            },
            {
                .name = "Manual ExpoRamp",
                .priv       = &bramp_manual_speed_evx1000_per_shot,
                .max = 1000,
                .min = -1000,
                .select = bramp_manual_evx1000_toggle,
                .update = manual_expo_ramp_print,
                .help = "Manual exposure ramping (Tv+ISO), in EV per shot.",
            },
            {
                .name = "Manual FocusRamp",
                .priv       = &bramp_manual_speed_focus_steps_per_shot,
                .max = 100,
                .min = -100,
                .update = manual_focus_ramp_print,
                .help  = "Manual focus ramping, in steps per shot. LiveView only.",
                .help2 = "Tip: enable powersaving features from Prefs menu.",
                .depends_on = DEP_AUTOFOCUS,
                .works_best_in = DEP_LIVEVIEW,
            },
            
            #endif
            
            MENU_EOL
        },
    },
    #endif
    /*
    {
        .name = "Bulb Ramping", // will move focus ramping to scripts
        .priv       = &bulb_ramping_enabled,
        .update     = bulb_ramping_print,
        .max        = 1,
        .submenu_width = 710,
        .help = "Exposure / focus ramping for advanced timelapse sequences.",
        .depends_on = DEP_PHOTO_MODE,
        .children =  (struct menu_entry[]) {

            MENU_EOL,
        }
    },
    */
    #ifdef FEATURE_BULB_TIMER
    {
        .name = "Bulb Timer",
        .priv = &bulb_timer,
        .update = bulb_display, 
        .max  = 1,
        .help  = "For very long exposures (several minutes).",
        .help2 = "To trigger, hold shutter pressed halfway for 1 second.",
        .depends_on = DEP_PHOTO_MODE,
        .children =  (struct menu_entry[]) {
            {
                .name = "Exposure duration",
                .priv = &bulb_duration_index,
                .max = COUNT(timer_values)-1,
                .icon_type = IT_PERCENT,
                .select = bulb_toggle,
                .update = bulb_display_submenu,
            },
            MENU_EOL
        },
    },
    #endif  
    #ifdef FEATURE_LCD_SENSOR_REMOTE
    {
        .name = "LCDsensor Remote",
        .priv       = &lcd_release_running,
        .max        = 3,
        .update     = lcd_release_display,
        .choices    = CHOICES("OFF", "Near", "Away", "Wave"),
        .help = "Use the LCD face sensor as a simple remote (avoids shake).",
    },
    #endif
    #ifdef FEATURE_AUDIO_REMOTE_SHOT
    {
        .name = "Audio RemoteShot",
        .priv       = &audio_release_running,
        .max        = 1,
        .update     = audio_release_display,
        .help = "Clap your hands or pop a balloon to take a picture.",
        //.essential = FOR_PHOTO,
        .children =  (struct menu_entry[]) {
            {
                .name = "Trigger level (dB)",
                .priv = &audio_release_level, 
                .min = 1,
                .max = 20,
                .help = "Picture taken when sound level becomes X dB above average.",
            },
            MENU_EOL
        },
    },
    #endif
    #ifdef FEATURE_MOTION_DETECT
    {
        .name = "Motion Detect",
        .priv       = &motion_detect,
        .max        = 1,
        .update     = motion_detect_display,
        .help = "Take a picture when subject is moving or exposure changes.",
        .works_best_in = DEP_PHOTO_MODE,
        .submenu_width = 650,
        .children =  (struct menu_entry[]) {
            {
                .name = "Trigger by",
                .priv = &motion_detect_trigger, 
                .max = 2,
                .choices = CHOICES("Expo. change", "Frame diff.", "Steady hands"),
                .icon_type = IT_DICE,
                .help  = "Choose when the picture should be taken:",
                .help2 = "EXP: reacts to exposure changes (large movements).\n"
                         "DIF: detects smaller movements that do not change exposure.\n"
                         "STDY: take pic if there's little or no motion (cam steady).",
            },
            {
                .name = "Trigger level",
                .priv = &motion_detect_level, 
                .min = 1,   
                .max = 30,
                .help = "Higher values = more sensitive to motion.",
            },
            {
                .name = "Detect Size",
                .priv = &motion_detect_size, 
                .max = 2,
                .choices = CHOICES("Small", "Medium", "Large"),
                .help = "Size of the area on which motion shall be detected.",
            },
            {
                .name = "Delay",
                .priv = &motion_detect_delay,
                .max  = 10,
                .min  = 0,
                .icon_type = IT_PERCENT_OFF,
                .choices = CHOICES("OFF", "0.1s", "0.2s", "0.3s", "0.4s", "0.5s", "0.6s", "0.7s", "0.8s", "0.9s", "1s"),
                .help = "Delay between the detected motion and the picture taken.",
            },
			MENU_EOL
		}

    },
    #endif
    #ifdef FEATURE_SILENT_PIC
    #ifdef FEATURE_SILENT_PIC_RAW
    {
        .name = "Silent Picture",
        .priv = &silent_pic_enabled,
        .max  = 1,
        .depends_on = DEP_LIVEVIEW,
        .help  = "Take pics in LiveView without moving the shutter mechanism.",
        .help2 = "File format: 14-bit DNG.",
    },
    #else // who needs 422 when we have raw?
    {
        .name = "Silent Picture",
        .priv = &silent_pic_enabled,
        .max  = 1,
        .update = silent_pic_display,
        .depends_on = DEP_LIVEVIEW,
        .help  = "Take pics in LiveView without moving the shutter mechanism.",
        .help2 = "Do not try this if you are afraid of computers!",
        .children =  (struct menu_entry[]) {
            {
                .name = "Mode",
                .priv = &silent_pic_mode,
                #ifdef FEATURE_SILENT_PIC_HIRES
                .max = 3, // hi-res works
                .help = "Silent picture mode: simple, burst, continuous or high-resolution.",
                #else
                .max = 2, // hi-res doesn't work
                .help = "Silent picture mode: simple, burst or continuous.",
                #endif
                .choices = CHOICES("Simple", "Burst", "Continuous", "Hi-Res"),
                .icon_type = IT_DICE,
            },
            #ifdef FEATURE_SILENT_PIC_HIRES
            {
                .name = "Hi-Res", 
                .priv = &silent_pic_highres,
                .update = silent_pic_check_highres_warnings,
                .max = COUNT(silent_pic_sweep_modes_l)-1,
                .choices = CHOICES("2x1", "2x2", "2x3", "3x3", "3x4", "4x4", "4x5", "5x5"),
                .icon_type = IT_DICE,
                .help = "For hi-res matrix mode: select number of subpictures."
            },
            #endif
            #ifdef FEATURE_SILENT_PIC_JPG
            {
                .name = "LV JPEG", 
                .priv = &silent_pic_jpeg,
                .max = 1,
                .help = "Save LV as JPEG"
            },
            #endif
            MENU_EOL
        },
    },
    #endif
    #endif
    #ifdef FEATURE_MLU_HANDHELD
        #ifndef FEATURE_MLU
        #error This requires FEATURE_MLU.
        #endif
    #endif
    #ifdef FEATURE_MLU
    {
        // 5DC can't do handheld MLU
        // 5D3 can do, but doesn't need it (it has silent mode with little or no vibration)
        .name = "Mirror Lockup",
        .priv = &mlu_auto,
        .update = mlu_display, 
        .select = mlu_toggle,
        .max = 1,
        .depends_on = DEP_PHOTO_MODE | DEP_NOT_LIVEVIEW,
        #ifdef FEATURE_MLU_HANDHELD
        .help = "MLU tricks: hand-held or self-timer modes.",
        #elif defined(CONFIG_5DC)
        .help = "You can toggle MLU w. DirectPrint or link it to self-timer.",
        #else
        .help = "You can link MLU with self-timer (handy).",
        #endif
        .submenu_width = 700,
        .children =  (struct menu_entry[]) {
            {
                .name = "MLU mode",
                .priv = &mlu_mode,
                .select = mlu_toggle_mode,
                #ifdef FEATURE_MLU_HANDHELD
                .max = 2,
                #else
                .max = 1,
                #endif
                .choices = CHOICES("Always ON", "Self-Timer", "Handheld"),
                .help = "Choose when mirror lock-up should be active:",
                .help2 = "Always ON: just the Canon mode, press shutter twice.\n"
                         "Self-Timer: MLU setting will be linked to Canon self-timer.\n"
                         "Handheld: trick to reduce camera shake. Press shutter once.",
            },
            #ifdef FEATURE_MLU_HANDHELD
            {
                .name = "Handheld Shutter",
                .priv = &mlu_handheld_shutter, 
                .max = 1,
                .icon_type = IT_DICE,
                .choices = CHOICES("All values", "1/2...1/125"),
                .help = "At what shutter speeds you want to use handheld MLU."
            },
            {
                .name = "Handheld Delay",
                .priv = &mlu_handheld_delay, 
                .min = 1,
                .max = 7,
                .icon_type = IT_PERCENT,
                .choices = CHOICES("0.1s", "0.2s", "0.3s", "0.4s", "0.5s", "0.75s", "1s"),
                .help = "Delay between mirror and shutter movement."
            },
            #endif
            #ifdef FEATURE_MLU_HANDHELD_DEBUG
                #ifndef FEATURE_MLU_HANDHELD
                #error This requires FEATURE_MLU_HANDHELD.
                #endif
            {
                .name = "Handheld Debug",
                .priv = &mlu_handled_debug, 
                .max = 1,
                .help = "Check whether the 'mirror up' event is detected correctly."
            },
            #endif
            {
                .name   = "Normal MLU Delay",
                .priv   = &lens_mlu_delay,
                .min    = 5,
                .max    = 11,
                .icon_type = IT_PERCENT,
                .choices = CHOICES("0.5s", "0.75s", "1s", "2s", "3s", "4s", "5s"),
                .help = "MLU delay used with intervalometer, bracketing etc.",
            }, 
            MENU_EOL
        },
    },
    #endif

    #ifdef FEATURE_PICQ_DANGEROUS
    {
        .update = picq_display, 
        .select = picq_toggle, 
        .help = "Experimental SRAW/MRAW mode. You may get corrupted files."
    },
    #endif

    #ifdef FEATURE_VOICE_TAGS
    {
        .name = "Voice Tags", 
        .priv = &voice_tags, 
        .max = 1,
        .help = "After you take a picture, press SET to add a voice tag.",
        .help2 = "For playback, go to Audio -> Sound Recorder.",
        .works_best_in = DEP_PHOTO_MODE,
    },
    #endif
    
    MENU_PLACEHOLDER("RAW Blinkies"),

    #ifdef FEATURE_LV_3RD_PARTY_FLASH
        #ifndef FEATURE_FLASH_TWEAKS
        #error This requires FEATURE_FLASH_TWEAKS.
        #endif 
    #endif

    #ifdef FEATURE_FLASH_TWEAKS
    {
        .name = "Flash Tweaks",
        .select     = menu_open_submenu,
        .help = "Flash exposure compensation, 3rd party flash in LiveView...",
        .depends_on = DEP_PHOTO_MODE,
        .children =  (struct menu_entry[]) {
            {
                .name = "Flash expo comp.",
                .priv = &lens_info.flash_ae,
                .min = FLASH_MIN_EV * 8,
                .max = FLASH_MAX_EV * 8,
                .update    = flash_ae_display,
                .select     = flash_ae_toggle,
                .help = "Flash exposure compensation, from -10EV to +3EV.",
                .icon_type = IT_PERCENT_OFF,
                .edit_mode = EM_MANY_VALUES,
                .depends_on = DEP_PHOTO_MODE,
            },
            {
                .name = "Flash / No flash",
                .update    = flash_and_no_flash_display,
                .priv = &flash_and_no_flash,
                .max = 1,
                .depends_on = DEP_PHOTO_MODE,
                .help = "Take odd pictures with flash, even pictures without flash.",
            },
            #ifdef FEATURE_LV_3RD_PARTY_FLASH
            {
                .name = "3rd p. flash LV",
                .priv = &lv_3rd_party_flash,
                .max = 1,
                .depends_on = DEP_LIVEVIEW | DEP_PHOTO_MODE,
                .help  = "A trick to allow 3rd party flashes to fire in LiveView.",
                .help2 = "!!! DISABLE THIS OPTION WHEN YOU ARE NOT USING IT !!!  ",
            },
            #endif
            MENU_EOL,
        },
    },
    #endif
    
    {
        .name = "Shoot Preferences",
        .select     = menu_open_submenu,
        .help = "Autofocus, number of pics to take at once...",
        .depends_on = DEP_PHOTO_MODE,
        .submenu_width = 710,
        .children =  (struct menu_entry[]) {
            {
                .name = "Pics at once",
                .priv = &pics_to_take_at_once,
                .max = 4,
                .choices = CHOICES("1 (OFF)", "2", "3", "4", "5"),
                .update = pics_at_once_update,
                .icon_type = IT_PERCENT_OFF,
                .help = "How many pictures to take at once (for each trigger event).",
                .help2 = "For intervalometer, motion detect, trap focus, audio remote.",
            },
            #ifdef CONFIG_PROP_REQUEST_CHANGE
            {
                .name = "Use Autofocus", 
                .priv = &shoot_use_af,
                .update = use_af_update,
                .max = 1,
                .help  = "For intervalometer, audio remote shot and motion detect.",
                .help2 = "Be careful, won't take pics if it can't autofocus.",
                .icon_type = IT_BOOL,
                .depends_on = DEP_AUTOFOCUS,
                .works_best_in = DEP_NOT_LIVEVIEW,
            },
            #endif
            #if defined(FEATURE_HDR_BRACKETING) || defined(FEATURE_FOCUS_STACKING)
            {
                .name = "Post scripts",
                .priv       = &hdr_scripts,
                .max = 3,
                .help = "Post-processing scripts for bracketing and focus stacking.",
                .choices = CHOICES("OFF", "Enfuse", "Align+Enfuse", "File List"),
            },
            #endif
            #ifdef FEATURE_SNAP_SIM
            {
                .name = "Snap Simulation",
                .priv = &snap_sim, 
                .max = 1,
                .icon_type = IT_BOOL,
                .choices = CHOICES(
                    "OFF", 
                    
                    "Blink"
                    #ifdef CONFIG_BEEP
                    " & Beep"
                    #endif
                ),
                .help = "You can take virtual (fake) pictures just for testing.",
            },
            #endif
            MENU_EOL,
        },
    }
};

#ifdef FEATURE_ZOOM_TRICK_5D3
extern int zoom_trick;
#endif

struct menu_entry tweak_menus_shoot[] = {
    #ifdef FEATURE_LV_ZOOM_SETTINGS
    {
        .name = "LiveView zoom tweaks",
        .select = menu_open_submenu,
        .submenu_width = 650,
        .icon_type = IT_SUBMENU,
        .help = "Disable x5 or x10, boost contrast/sharpness...",
        .depends_on = DEP_LIVEVIEW,
        .children =  (struct menu_entry[]) {
            {
                .name = "Zoom x5",
                .priv = &zoom_disable_x5, 
                .max = 1,
                .choices = CHOICES("ON", "Disable"),
                .select = zoom_x5_x10_toggle,
                .help = "Disable x5 zoom in LiveView.",
                .icon_type = IT_DISABLE_SOME_FEATURE,
            },
            {
                .name = "Zoom x10",
                .priv = &zoom_disable_x10, 
                .max = 1,
                .select = zoom_x5_x10_toggle,
                .choices = CHOICES("ON", "Disable"),
                .help = "Disable x10 zoom in LiveView.",
                .icon_type = IT_DISABLE_SOME_FEATURE,
            },
            #ifdef FEATURE_LV_ZOOM_AUTO_EXPOSURE
                #ifndef CONFIG_EXPSIM
                #error This requires CONFIG_EXPSIM.
                #endif
            {
                .name = "Auto exposure on Zoom",
                .priv = &zoom_auto_exposure,
                .max = 1,
                .help = "Auto adjusts exposure, so you can focus manually wide open.",
                #ifndef CONFIG_5D2
                .depends_on = DEP_PHOTO_MODE,
                #endif
            },
            #endif
            #ifdef FEATURE_LV_ZOOM_SHARP_CONTRAST
            {
                .name = "Increase SharpContrast",
                .priv = &zoom_sharpen,
                .max = 1,
                .help = "Increase sharpness and contrast when you zoom in LiveView."
            },
            #endif
            {
                .name = "Zoom on HalfShutter",
                .priv = &zoom_halfshutter,
                .max = 1,
                .help = "Enable zoom when you hold the shutter halfway pressed.",
                .depends_on = DEP_MANUAL_FOCUS,
            },
            {
                .name = "Zoom with Focus Ring",
                .priv = &zoom_focus_ring,
                .max = 1,
                .help = "Zoom when you turn the focus ring (only some Canon lenses).",
                .depends_on = DEP_MANUAL_FOCUS,
            },
            #ifdef FEATURE_ZOOM_TRICK_5D3
            #ifdef CONFIG_6D
            {
                .name = "Double Click",
                .priv = &zoom_trick,
                .max = 2,
                .help = "Double-click top-right button in LV. Shortcuts or Zoom.",
                .choices = CHOICES("OFF", "Zoom", "Shortcuts"),
            },
            #else // 5D3
            {
                .name = "Zoom with old button",
                .priv = &zoom_trick,
                .max = 1,
                .help = "Use the old Zoom In button, as in 5D2. Double-click in LV.",
                .choices = CHOICES("OFF", "ON (!)"),
            },
            #endif
            #endif
            MENU_EOL
        },
    },
    #endif
};

#ifdef FEATURE_ML_AUTO_ISO

static CONFIG_INT("auto.iso.ml", ml_auto_iso, 0);
static CONFIG_INT("auto.iso.av.tv", ml_auto_iso_av_shutter, 3);
static CONFIG_INT("auto.iso.tv.av", ml_auto_iso_tv_aperture, 3);

static MENU_UPDATE_FUNC(ml_auto_iso_display)
{
    if (shooting_mode != SHOOTMODE_AV && shooting_mode != SHOOTMODE_TV)
        MENU_SET_WARNING(MENU_WARN_NOT_WORKING, "This feature only works in Tv and Av modes.");
}

static void auto_iso_tweak_step()
{
    static int last_iso = -1;
    if (!ml_auto_iso)
    {
        if (last_iso != -1) // when disabling ML auto ISO, restore previous ISO
        {   
            lens_set_rawiso(last_iso);
            last_iso = -1;
        }
        return;
    }
    if (ISO_ADJUSTMENT_ACTIVE) return;
    if (!display_idle()) return;
    
    if (last_iso == -1) last_iso = lens_info.raw_iso;
    
    int min_iso = MIN_ISO;
    int max_iso = auto_iso_range & 0xFF;
    
    if (shooting_mode == SHOOTMODE_AV && lens_info.raw_shutter)
    {
        int ref_tv = 88 + 8*ml_auto_iso_av_shutter;

        int new_iso = lens_info.raw_iso;
        int e = ABS(lens_info.raw_shutter - ref_tv);
        int er = (e+4)/8*8;
        if (lens_info.raw_shutter <= ref_tv-4)
            new_iso = MIN(lens_info.raw_iso + er, max_iso);
        else if (lens_info.raw_shutter > ref_tv+4)
            new_iso = MAX(lens_info.raw_iso - er, min_iso);
        if (new_iso != lens_info.raw_iso)
            lens_set_rawiso(new_iso);
    }
    else if (shooting_mode == SHOOTMODE_TV && lens_info.raw_aperture)
    {
        // you can't go fully wide open, because ML would have no way to know when to raise ISO
        int av_min = (int)lens_info.raw_aperture_min + 4;
        int av_max = (int)lens_info.raw_aperture_max - 5;
        if (av_min >= av_max) return;
        int ref_av = COERCE(16 + 8*(int)ml_auto_iso_tv_aperture, av_min, av_max);

        int e = ABS(lens_info.raw_aperture - ref_av);
        int er = (e+4)/8*8;
        int new_iso = lens_info.raw_iso;
        if (lens_info.raw_aperture <= ref_av-4)
            new_iso = MIN(lens_info.raw_iso + er, max_iso);
        else if (lens_info.raw_aperture > ref_av+4)
            new_iso = MAX(lens_info.raw_iso - er, min_iso);
        if (new_iso != lens_info.raw_iso)
            lens_set_rawiso(new_iso);
    }
    else return;
    
    if (get_halfshutter_pressed()) msleep(200); // try to reduce the influence over autofocus
}
#endif // FEATURE_ML_AUTO_ISO

extern int lvae_iso_max;
extern int lvae_iso_min;
extern int lvae_iso_speed;

extern MENU_UPDATE_FUNC(digic_iso_print_movie);
extern MENU_SELECT_FUNC(digic_iso_toggle_movie);

extern int digic_black_level;
extern MENU_UPDATE_FUNC(digic_black_print);

extern int digic_shadow_lift;

static struct menu_entry expo_menus[] = {
    #ifdef FEATURE_WHITE_BALANCE
    {
        .name = "WhiteBalance",
        .update    = kelvin_wbs_display,
        .select     = kelvin_toggle,
        .help  = "Adjust Kelvin white balance and GM/BA WBShift.",
        .help2 = "Advanced: WBShift, RGB multipliers, UniWB, Push-button WB...",
        .edit_mode = EM_MANY_VALUES_LV,
        .submenu_width = 700,
        .children =  (struct menu_entry[]) {
            {
                .name = "White Balance",
                .update    = kelvin_display,
                .select     = kelvin_toggle,
                .help = "Adjust Kelvin white balance.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "WBShift G/M",
                .update = wbs_gm_display, 
                .select = wbs_gm_toggle,
                .min = -9,
                .max = 9,
                .icon_type = IT_PERCENT_OFF,
                .help = "Green-Magenta white balance shift, for fluorescent lights.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "WBShift B/A",
                .update = wbs_ba_display, 
                .select = wbs_ba_toggle, 
                .min = -9,
                .max = 9,
                .icon_type = IT_PERCENT_OFF,
                .help = "Blue-Amber WBShift; 1 unit = 5 mireks on Kelvin axis.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "R multiplier",
                .priv = (void *)(1),
                .update = wb_custom_gain_display,
                .select = wb_custom_gain_toggle,
                .icon_type = IT_PERCENT,
                .help = "RED channel multiplier, for custom white balance.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "G multiplier",
                .priv = (void *)(2),
                .update = wb_custom_gain_display,
                .select = wb_custom_gain_toggle,
                .icon_type = IT_PERCENT,
                .help = "GREEN channel multiplier, for custom white balance.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "B multiplier",
                .priv = (void *)(3),
                .update = wb_custom_gain_display,
                .select = wb_custom_gain_toggle,
                .icon_type = IT_PERCENT,
                .help = "BLUE channel multiplier, for custom white balance.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            /*{
                .name = "UniWB",
                .priv = &uniwb_mode,
                .max = 3,
                .choices = CHOICES("OFF", "Always ON", "on HalfShutter", "not HalfShutter"),
                .help = "Cancels white balance => good RAW histogram approximation.",
            },
            */
            /*{
                .name = "Auto adjust Kelvin",
                .select = kelvin_auto,
                .help = "LiveView: adjust Kelvin value once for the current scene."
            },
            {
                .name = "Auto adjust Green-Magenta",
                .select = wbs_gm_auto,
                .help = "LiveView: adjust Green-Magenta once for the current scene."
            },*/
            {
                .name = "Auto adjust Kelvin + G/M",
                .select = kelvin_n_gm_auto,
                .help = "LiveView: adjust Kelvin and G-M once (Push-button WB).",
                .depends_on = DEP_LIVEVIEW,
            },
            MENU_EOL
        },
    },
    #endif

    #ifdef FEATURE_EXPO_ISO_HTP
        #ifndef FEATURE_EXPO_ISO
        #error This requires FEATURE_EXPO_ISO.
        #endif
    #endif

    #ifdef FEATURE_EXPO_ISO
    {
        .name = "ISO",
        .update    = iso_display,
        .select     = iso_toggle,
        .help  = "Adjust and fine-tune ISO. Also displays APEX Sv value.",
        .help2 = "Advanced: digital ISO tweaks, HTP, ISO 50, ISO 800.000...",
        .edit_mode = EM_MANY_VALUES_LV,
        
        .submenu_width = 650,

        .children =  (struct menu_entry[]) {
            {
                .name = "Equivalent ISO",
                .help = "ISO equivalent (analog + digital components).",
                .priv = &lens_info.iso_equiv_raw,
                .unit = UNIT_ISO,
                .select     = iso_toggle,
                .edit_mode = EM_MANY_VALUES_LV,
                .update = iso_icon_update,
            },
            {
                .name = "Canon analog ISO",
                .help = "Analog ISO component (ISO at which the sensor is driven).",
                .priv = &lens_info.iso_analog_raw,
                .unit = UNIT_ISO,
                .select     = analog_iso_toggle,
                .edit_mode = EM_MANY_VALUES_LV,
                .depends_on = DEP_MANUAL_ISO,
                .update = iso_icon_update,
            },
            {
                .name = "Canon digital ISO",
                .help = "Canon's digital ISO component. Strongly recommended: 0.",
                .priv = &lens_info.iso_digital_ev,
                .unit = UNIT_1_8_EV,
                .select     = digital_iso_toggle,
                .edit_mode = EM_MANY_VALUES_LV,
                .depends_on = DEP_MANUAL_ISO,
                .icon_type = IT_DICE_OFF,
            },
            #ifdef FEATURE_EXPO_ISO_DIGIC
            {
                .name = "ML digital ISO",
                .update = digic_iso_print_movie,
                .select = digic_iso_toggle_movie,
                .help = "ISO tweaks. Negative gain has better highlight roll-off.",
                .edit_mode = EM_MANY_VALUES_LV,
                .depends_on = DEP_MOVIE_MODE | DEP_MANUAL_ISO,
                .icon_type = IT_DICE_OFF,
            },
            #endif
            #ifdef FEATURE_EXPO_ISO_HTP
            {
                .name = "Highlight Tone P.",
                .select = (void (*)(void *,int))htp_toggle,
                .update = htp_display,
                .icon_type = IT_BOOL,
                .help = "Highlight Tone Priority. Use with negative ML digital ISO.",
            },
            #endif
            /*
            #ifdef FEATURE_EXPO_ISO_DIGIC
            {
                .name = "ISO Selection",
                .priv = &iso_selection,
                .max = 1,
                .help = "What ISOs should be available from main menu and shortcuts.",
                .choices = CHOICES("C 100/160x", "ML ISOs"),
                .icon_type = IT_DICE,
            },
            #endif
            */
            #if 0 // unstable
            {
                .name = "Min Movie AutoISO",
                .priv = &lvae_iso_min,
                .min = 72,
                .max = 120,
                .unit = UNIT_ISO,
                .help = "Minimum value for Auto ISO in movie mode.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "Max Movie AutoISO",
                .priv = &lvae_iso_max,
                .min = 72,
                .max = 120,
                .unit = UNIT_ISO,
                .help = "Maximum value for Auto ISO in movie mode.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "A-ISO smoothness",
                .priv = &lvae_iso_speed,
                .min = 3,
                .max = 30,
                .help = "Speed for movie Auto ISO. Low values = smooth transitions.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            #endif
            MENU_EOL
        },
    },
    #endif
    #ifdef FEATURE_EXPO_SHUTTER
    {
        .name = "Shutter",
        .update     = shutter_display,
        .select     = shutter_toggle,
        .icon_type  = IT_PERCENT,
        .help = "Fine-tune shutter value. Displays APEX Tv or degrees equiv.",
        .edit_mode = EM_MANY_VALUES_LV,
    },
    #endif
    #ifdef FEATURE_EXPO_APERTURE
    {
        .name = "Aperture",
        .update     = aperture_display,
        .select     = aperture_toggle,
        .icon_type  = IT_PERCENT,
        .help = "Adjust aperture. Also displays APEX aperture (Av) in stops.",
        .depends_on = DEP_CHIPPED_LENS,
        .edit_mode = EM_MANY_VALUES_LV,
    },
    #endif
    #ifdef FEATURE_PICSTYLE
    {
        .name = "PictureStyle",
        .update     = picstyle_display,
        .select     = picstyle_toggle,
        .priv = &lens_info.picstyle,
        .help = "Change current picture style.",
        .edit_mode = EM_MANY_VALUES_LV,
        .icon_type = IT_DICE,
        .choices = (const char *[]) {
                #if NUM_PICSTYLES == 10 // 600D, 5D3...
                "Auto",
                #endif
                "Standard", "Portrait", "Landscape", "Neutral", "Faithful", "Monochrome", "UserDef1", "UserDef2", "UserDef3" },
        .min = 1,
        .max = NUM_PICSTYLES,
        .submenu_width = 550,
        .submenu_height = 300,
        //~ .show_liveview = 1,
        //~ //.essential = FOR_PHOTO | FOR_MOVIE,
        .children =  (struct menu_entry[]) {
            {
                .name = "Picture Style",
                .priv = &lens_info.picstyle,
                .min = 1,
                .max = NUM_PICSTYLES,
                .choices = (const char *[]) {
                        #if NUM_PICSTYLES == 10 // 600D, 5D3...
                        "Auto",
                        #endif
                        "Standard", "Portrait", "Landscape", "Neutral", "Faithful", "Monochrome", "UserDef1", "UserDef2", "UserDef3" },
                .update     = picstyle_display_submenu,
                .select     = picstyle_toggle,
                .help = "Change current picture style.",
                //~ .show_liveview = 1,
                .edit_mode = EM_MANY_VALUES_LV,
                .icon_type = IT_DICE,
            },
            {
                .name = "Sharpness",
                .update     = sharpness_display,
                .select     = sharpness_toggle,
                .help = "Adjust sharpness in current picture style.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "Contrast",
                .update     = contrast_display,
                .select     = contrast_toggle,
                .help = "Adjust contrast in current picture style.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "Saturation",
                .update     = saturation_display,
                .select     = saturation_toggle,
                .help = "Adjust saturation in current picture style.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
            {
                .name = "Color Tone",
                .update     = color_tone_display,
                .select     = color_tone_toggle,
                .help = "Adjust color tone in current picture style.",
                .edit_mode = EM_MANY_VALUES_LV,
            },
    #ifdef FEATURE_REC_PICSTYLE
            {
                .name = "REC-PicStyle",
                .priv = &picstyle_rec,
                .max  = NUM_PICSTYLES,
                .icon_type = IT_DICE_OFF,
                .update     = picstyle_rec_sub_display,
                .select     = picstyle_rec_sub_toggle,

                .choices = (const char *[]) {"OFF",
                #if NUM_PICSTYLES == 10 // 600D, 5D3...
                "Auto",
                #endif
                "Standard", "Portrait", "Landscape", "Neutral", "Faithful", "Monochrome", "UserDef1", "UserDef2", "UserDef3" },
                
                .help = "You can use a different picture style when recording.",
                .depends_on = DEP_MOVIE_MODE,
            },
    #endif
            MENU_EOL
        },
    },
    #endif
    #ifdef FEATURE_ML_AUTO_ISO
    {
        .name = "ML Auto ISO",
        .priv = &ml_auto_iso, 
        .max = 1,
        .update = ml_auto_iso_display,
        .help = "Experimental auto ISO algorithms.",
        .submenu_width = 700,
        .depends_on = DEP_PHOTO_MODE,
        .children =  (struct menu_entry[]) {
            {
                .name = "Shutter for Av mode",
                .priv = &ml_auto_iso_av_shutter,
                .max = 7,
                .icon_type = IT_PERCENT,
                .choices = CHOICES("1/15", "1/30", "1/60", "1/125", "1/250", "1/500", "1/1000", "1/2000"),
                .help = "Preferred shutter speed for Av mode (+/- 0.5 EV)."
            },
            {
                .name = "Aperture for Tv mode",
                .priv = &ml_auto_iso_tv_aperture,
                .max = 8,
                .icon_type = IT_PERCENT,
                .choices = CHOICES("f/1.4", "f/2.0", "f/2.8", "f/4.0", "f/5.6", "f/8", "f/11", "f/16", "f/22"),
                .help = "Preferred aperture for Tv mode (+/- 0.5 EV)."
            },
            /*
            {
                .name = "A-ISO smoothness",
                .priv = &lvae_iso_speed,
                .min = 3,
                .max = 30,
                .help = "Speed for movie Auto ISO. Low values = smooth transitions.",
                .edit_mode = EM_MANY_VALUES_LV,
            },*/
            MENU_EOL
        }
    },
    #endif
    #ifdef FEATURE_EXPO_LOCK
    {
        .name       = "Expo.Lock",
        .priv       = &expo_lock,
        .max        = 1,
        .update     = expo_lock_display,
        .help       = "In M mode, adjust Tv/Av/ISO without changing exposure.",
        .help2      = "It may change the way you use M mode. Maybe I'm just crazy.",
        .depends_on = DEP_M_MODE | DEP_MANUAL_ISO,
        .children =  (struct menu_entry[]) {
            {
                .name = "Tv  -> ",
                .priv    = &expo_lock_tv,
                .max = 2,
                .icon_type = IT_DICE_OFF,
                .choices = CHOICES("OFF", "Av,ISO", "ISO,Av"),
                .help = "When you change Tv, ML adjusts Av and ISO to keep exposure.",
            },
            {
                .name = "Av  -> ",
                .priv    = &expo_lock_av,
                .max = 2,
                .icon_type = IT_DICE_OFF,
                .choices = CHOICES("OFF", "Tv,ISO", "ISO,Tv"),
                .help = "When you change Av, ML adjusts Tv and ISO to keep exposure.",
            },
            {
                .name = "ISO -> ",
                .priv    = &expo_lock_iso,
                .max = 2,
                .icon_type = IT_DICE_OFF,
                .choices = CHOICES("OFF", "Tv,Av", "Av,Tv"),
                .help = "When you change ISO, ML adjusts Tv and Av to keep exposure.",
            },
            MENU_EOL
        },
    },
    #endif
    #ifdef FEATURE_EXPO_PRESET
    {
        .name = "Expo.Presets",
        .priv = &expo_preset,
        .max = 2,
        .choices = CHOICES("OFF", "Press SET", "Press " INFO_BTN_NAME),
        .help = "Quickly toggle between two expo presets (ISO,Tv,Av,Kelvin).",
        .works_best_in = DEP_M_MODE,
    },
    #endif
};


// for firing HDR shots - avoids random misfire due to low polling frequency
static int picture_was_taken_flag = 0;

void hdr_flag_picture_was_taken()
{
    picture_was_taken_flag = 1;
}

#if defined(FEATURE_HDR_BRACKETING) || defined(FEATURE_FOCUS_STACKING)

int hdr_script_get_first_file_number(int skip0)
{
    return mod(file_number + 1 - (skip0 ? 1 : 0), 10000);
}

// create a post script for HDR bracketing or focus stacking,
// starting from file number f0 till the current file_number
void hdr_create_script(int f0, int focus_stack)
{
    if (!hdr_scripts) return;
    
    #ifdef FEATURE_SNAP_SIM
    if (snap_sim) return; // no script for virtual shots
    #endif
    
    int steps = mod(file_number - f0 + 1, 10000);
    if (steps <= 1) return;

    char name[100];
    snprintf(name, sizeof(name), "%s/%s_%04d.%s", get_dcim_dir(), focus_stack ? "FST" : "HDR", f0, hdr_scripts == 3 ? "txt" : "sh");

    FILE * f = FIO_CreateFileEx(name);
    if ( f == INVALID_PTR )
    {
        bmp_printf( FONT_LARGE, 30, 30, "FIO_CreateFileEx: error for %s", name );
        return;
    }
    
    if (hdr_scripts == 1)
    {
        my_fprintf(f, "#!/usr/bin/env bash\n");
        my_fprintf(f, "\n# %s_%04d.JPG from IMG_%04d.JPG ... IMG_%04d.JPG\n\n", focus_stack ? "FST" : "HDR", f0, f0, mod(f0 + steps - 1, 10000));
        my_fprintf(f, "enfuse \"$@\" %s --output=%s_%04d.JPG ", focus_stack ? "--exposure-weight=0 --saturation-weight=0 --contrast-weight=1 --hard-mask" : "", focus_stack ? "FST" : "HDR", f0);
        for(int i = 0; i < steps; i++ )
        {
            my_fprintf(f, "IMG_%04d.JPG ", mod(f0 + i, 10000));
        }
        my_fprintf(f, "\n");
    }
    else if (hdr_scripts == 2)
    {
        my_fprintf(f, "#!/usr/bin/env bash\n");
        my_fprintf(f, "\n# %s_%04d.JPG from IMG_%04d.JPG ... IMG_%04d.JPG with aligning first\n\n", focus_stack ? "FST" : "HDR", f0, f0, mod(f0 + steps - 1, 10000));
        my_fprintf(f, "align_image_stack -m -a %s_AIS_%04d", focus_stack ? "FST" : "HDR", f0);
        for(int i = 0; i < steps; i++ )
        {
            my_fprintf(f, " IMG_%04d.JPG", mod(f0 + i, 10000));
        }
        my_fprintf(f, "\n");
        my_fprintf(f, "enfuse \"$@\" %s --output=%s_%04d.JPG %s_AIS_%04d*\n", focus_stack ? "--contrast-window-size=9 --exposure-weight=0 --saturation-weight=0 --contrast-weight=1 --hard-mask" : "", focus_stack ? "FST" : "HDR", f0, focus_stack ? "FST" : "HDR", f0);
        my_fprintf(f, "rm %s_AIS_%04d*\n", focus_stack ? "FST" : "HDR", f0);
    }
    else if (hdr_scripts == 3)
    {
        for(int i = 0; i < steps; i++ )
        {
            my_fprintf(f, " IMG_%04d.JPG", mod(f0 + i, 10000));
        }
    }
    
    FIO_CloseFile(f);
    NotifyBox(5000, "Saved %s\nIMG_%04d.JPG ... IMG_%04d.JPG", name + 17, f0, mod(f0 + steps - 1, 10000));
}
#endif // HDR/FST

// normal pic, silent pic, bulb pic...
void take_a_pic(int should_af, int allow_bulb)
{
    #ifdef FEATURE_SNAP_SIM
    if (snap_sim) {
        beep();
        _card_led_on();
        display_off();
        msleep(250);
        display_on();
        _card_led_off();
        msleep(100);
        return;
    }
    #endif
    #ifdef FEATURE_SILENT_PIC
    if (silent_pic_enabled)
    {
        //msleep(500);
        silent_pic_take(0); 
    }
    else
    #endif
    {
        //~ beep();
        if (allow_bulb && is_bulb_mode_or_bulb_ramping()) hdr_shot(0, 1);
        else lens_take_picture(64, should_af);
    }
    lens_wait_readytotakepic(64);
}

// do a part of the bracket (half or full) with ISO
// return the remainder EV to be done normally (shutter, flash, whatever)
static int hdr_iso00;
static int hdr_iso_shift(int ev_x8)
{
    hdr_iso00 = lens_info.raw_iso;
    int iso0 = hdr_iso00;
    if (!iso0) iso0 = lens_info.raw_iso_auto;

    if (hdr_iso && iso0) // dynamic range optimization
    {
        if (ev_x8 < 0)
        {
            int iso_delta = MIN(iso0 - MIN_ISO, -ev_x8 / (hdr_iso == 2 ? 2 : 1)); // lower ISO, down to ISO 100

            // if we are going to hit shutter speed limit, use more iso shifting, to get the correct bracket
            int rs = get_exposure_time_raw();
            int rc = rs - (ev_x8 + iso_delta);
            if (rc >= FASTEST_SHUTTER_SPEED_RAW)
                iso_delta = MIN(iso0 - MIN_ISO, iso_delta + rc - FASTEST_SHUTTER_SPEED_RAW + 1);

            iso_delta = (iso_delta+6)/8*8; // round to full stops; also, prefer lower ISOs
            ev_x8 += iso_delta;
            hdr_set_rawiso(iso0 - iso_delta);
        }
        else if (ev_x8 > 0)
        {
            int max_auto_iso = auto_iso_range & 0xFF;
            int iso_delta = MIN(max_auto_iso - iso0, ev_x8 / (hdr_iso == 2 ? 2 : 1)); // raise ISO, up to max auto iso
            iso_delta = (iso_delta)/8*8; // round to full stops; also, prefer lower ISOs
            if (iso_delta < 0) iso_delta = 0;
            ev_x8 -= iso_delta;
            hdr_set_rawiso(iso0 + iso_delta);
        }
    }
    return ev_x8;
}

static void hdr_iso_shift_restore()
{
    hdr_set_rawiso(hdr_iso00);
}
// Here, you specify the correction in 1/8 EV steps (for shutter or exposure compensation)
// The function chooses the best method for applying this correction (as exposure compensation, altering shutter value, or bulb timer)
// And then it takes a picture
// .. and restores settings back

// Return value: 1 if OK, 0 if it couldn't set some parameter (but it will still take the shot)
static int hdr_shutter_release(int ev_x8)
{
    int ans = 1;
    //~ NotifyBox(2000, "hdr_shutter_release: %d", ev_x8); msleep(2000);
    lens_wait_readytotakepic(64);

    int manual = (shooting_mode == SHOOTMODE_M || is_movie_mode() || is_bulb_mode_or_bulb_ramping());
    int dont_change_exposure = ev_x8 == 0 && !HDR_ENABLED && !BULB_EXPOSURE_CONTROL_ACTIVE;

    if (dont_change_exposure)
    {
        take_a_pic(AF_DONT_CHANGE, 1);
        return 1;
    }
    
    // let's see if we have to do some other type of bracketing (aperture or flash)
    int av0 = lens_info.raw_aperture;
    if (HDR_ENABLED)
    {
        if (hdr_type == 1) // flash => just set it
        {
            ev_x8 = hdr_iso_shift(ev_x8);
            int fae0 = lens_info.flash_ae;
            ans = hdr_set_flash_ae(fae0 + ev_x8);
            take_a_pic(AF_DONT_CHANGE, 0);
            hdr_set_flash_ae(fae0);
            hdr_iso_shift_restore();
            return ans;
        }
        else if (hdr_type == 2) // aperture
        {
            ev_x8 = COERCE(-ev_x8, lens_info.raw_aperture_min - av0, lens_info.raw_aperture_max - av0);
            ans = hdr_set_rawaperture(av0 + ev_x8);
            if (!manual) ev_x8 = 0; // no need to compensate, Canon meter does it
            // don't return, do the normal exposure bracketing
        }
    }
    
    
    if (!manual) // auto modes
    {
        hdr_iso_shift(ev_x8); // don't change the EV value
        int ae0 = lens_get_ae();
        ans = MIN(ans, hdr_set_ae(ae0 + ev_x8));
        take_a_pic(AF_DONT_CHANGE, 0);
        hdr_set_ae(ae0);
        hdr_iso_shift_restore();
    }
    else // manual mode or bulb
    {
        ev_x8 = hdr_iso_shift(ev_x8);

        // apply EV correction in both "domains" (milliseconds and EV)
        int ms = get_exposure_time_ms();
        int msc = ms * roundf(1000.0f * powf(2, ev_x8 / 8.0f))/1000;
        
        int rs = (BULB_EXPOSURE_CONTROL_ACTIVE) ? shutterf_to_raw_noflicker(bulb_shutter_valuef) : get_exposure_time_raw();
        if (rs == 0) // shouldn't happen
        {
            msleep(1000);
            rs = lens_info.raw_shutter; // maybe lucky this time?
            ASSERT(rs);
        }
        int rc = rs - ev_x8;

        int s0r = lens_info.raw_shutter; // save settings (for restoring them back)
        #if defined(CONFIG_5D2) || defined(CONFIG_50D)
        int expsim0 = get_expsim();
        #endif
        
        //~ NotifyBox(2000, "ms=%d msc=%d rs=%x rc=%x", ms,msc,rs,rc); msleep(2000);

#ifdef CONFIG_BULB
        // then choose the best option (bulb for long exposures, regular for short exposures)
        if (msc >= 10000 || (BULB_EXPOSURE_CONTROL_ACTIVE && msc > BULB_MIN_EXPOSURE && !BRAMP_LRT_HOLY_GRAIL))
        {
            bulb_take_pic(msc);
            #ifdef FEATURE_BULB_RAMPING
            bramp_last_exposure_rounding_error_evx1000 = 0; // bulb ramping assumed to be exact
            #endif
        }
        else
#endif
        {
            #if defined(CONFIG_5D2) || defined(CONFIG_50D)
            if (get_expsim() == 2) { set_expsim(1); msleep(300); } // can't set shutter slower than 1/30 in movie mode
            #endif
            ans = MIN(ans, hdr_set_rawshutter(rc));
            take_a_pic(AF_DONT_CHANGE, 0);
            
            #ifdef FEATURE_BULB_RAMPING
            if (BULB_EXPOSURE_CONTROL_ACTIVE)
            {
                // since actual shutter speed differs from float value quite a bit, 
                // we will need this to correct metering readings
                bramp_last_exposure_rounding_error_evx1000 = (int)roundf(log2f(raw2shutterf(rs) / bulb_shutter_valuef) * 1000.0f);
                ASSERT(ABS(bramp_last_exposure_rounding_error_evx1000) < 500);
            }
            else bramp_last_exposure_rounding_error_evx1000 = 0;
            #endif
        }
        
        if (drive_mode == DRIVE_SELFTIMER_2SEC) msleep(2500);
        if (drive_mode == DRIVE_SELFTIMER_REMOTE) msleep(10500);

        // restore settings back
        //~ set_shooting_mode(m0r);
        hdr_set_rawshutter(s0r);
        hdr_iso_shift_restore();
        #if defined(CONFIG_5D2) || defined(CONFIG_50D)
        if (expsim0 == 2) set_expsim(expsim0);
        #endif
    }

    if (HDR_ENABLED && hdr_type == 2) // aperture bracket - restore initial value
        hdr_set_rawaperture(av0);

    lens_wait_readytotakepic(64);
    return ans;
}

#ifdef FEATURE_HDR_BRACKETING

static int hdr_check_cancel(int init)
{
    static int m;
    if (init)
    {
        m = shooting_mode;
        return 0;
    }
    
    extern int ml_started;
    if (!ml_started)
        return 0;

    // cancel bracketing
    if (shooting_mode != m || MENU_MODE) 
    { 
        beep(); 
        lens_wait_readytotakepic(64);
        NotifyBox(5000, "Bracketing stopped.");
        return 1; 
    }
    return 0;
}
#endif // FEATURE_HDR_BRACKETING

static void ensure_play_or_qr_mode_after_shot()
{
    msleep(300);
    while (!job_state_ready_to_take_pic()) msleep(100);
    msleep(500);
    #define QR_OR_PLAY (DISPLAY_IS_ON && (QR_MODE || PLAY_MODE))
    for (int i = 0; i < 20; i++)
    {
        msleep(100);
        if (QR_OR_PLAY)
            break;
        if (display_idle())
            break;
    }
    
    if (!QR_OR_PLAY) // image review disabled?
    {
        while (!job_state_ready_to_take_pic()) msleep(100);
        fake_simple_button(BGMT_PLAY);
        for (int i = 0; i < 50; i++)
        {
            msleep(100);
            if (PLAY_MODE) break;
        }
        msleep(1000);
    }
}

#ifdef FEATURE_HDR_BRACKETING

static void hdr_check_for_under_or_over_exposure(int* under, int* over)
{
    if (hdr_type == 2) // DOF bracket => just repeat until reaching the limits
    {
        *under = 1;
        *over = 1;
        return;
    }
    
    if (!silent_pic_enabled) ensure_play_or_qr_mode_after_shot();

    int under_numpix, over_numpix;
    int total_numpix = get_under_and_over_exposure(20, 235, &under_numpix, &over_numpix);
    *under = under_numpix > 10;
    *over = over_numpix > 10;
    int po = over_numpix * 10000 / total_numpix;
    int pu = under_numpix * 10000 / total_numpix;
    if (*under) pu = MAX(pu, 1);
    if (*over) po = MAX(po, 1);
    bmp_printf(
        FONT_LARGE, 50, 50, 
        "Under:%3d.%02d%%\n"
        "Over :%3d.%02d%%", 
        pu/100, pu%100, 0, 
        po/100, po%100, 0
    ); 
    msleep(500);
}

static int hdr_shutter_release_then_check_for_under_or_over_exposure(int ev_x8, int* under, int* over)
{
    int ans = hdr_shutter_release(ev_x8);
    hdr_check_for_under_or_over_exposure(under, over);
    return ans;
}

static void hdr_auto_take_pics(int step_size, int skip0)
{
    int i;
    
    // make sure it won't autofocus
    lens_setup_af(AF_DISABLE);
    // be careful: don't return without restoring the setting back!
    
    hdr_check_cancel(1);
    
    int UNDER = 1;
    int OVER = 1;
    int under, over;
    
    // first frame for the bracketing script
    int f0 = hdr_script_get_first_file_number(skip0);
    
    // first exposure is always at 0 EV (and might be skipped)
    if (!skip0) hdr_shutter_release_then_check_for_under_or_over_exposure(0, &under, &over);
    else hdr_check_for_under_or_over_exposure(&under, &over);
    if (!under) UNDER = 0; if (!over) OVER = 0;
    if (hdr_check_cancel(0)) goto end;
    
    switch (hdr_sequence)
    {
        case 1: // 0 - + -- ++ 
        {
            for( i = 1; i <= 20; i ++  )
            {
                if (OVER)
                {
                    int ok = hdr_shutter_release_then_check_for_under_or_over_exposure(-step_size * i, &under, &over);
                    if (!under) UNDER = 0; if (!over) OVER = 0;
                    if (!ok) OVER = 0; // Canon limit reached, don't continue this sequence
                    if (hdr_check_cancel(0)) goto end;
                }
                
                if (UNDER)
                {
                    int ok = hdr_shutter_release_then_check_for_under_or_over_exposure(step_size * i, &under, &over);
                    if (!under) UNDER = 0; if (!over) OVER = 0;
                    if (!ok) UNDER = 0; // Canon limit reached, don't continue this sequence
                    if (hdr_check_cancel(0)) goto end;
                }
            }
            break;
        }
        case 0: // 0 - -- => will only check highlights
        {
            for( i = 1; i < 20; i ++  )
            {
                if (OVER)
                {
                    int ok = hdr_shutter_release_then_check_for_under_or_over_exposure(-step_size * i, &under, &over);
                    if (!under) UNDER = 0; if (!over) OVER = 0;
                    if (!ok) OVER = 0;
                    if (hdr_check_cancel(0)) goto end;
                }
            }
            break;
        }
        case 2: // 0 + ++
        {
            for( i = 1; i < 20; i ++  )
            {
                if (UNDER)
                {
                    int ok = hdr_shutter_release_then_check_for_under_or_over_exposure(step_size * i, &under, &over);
                    if (!under) UNDER = 0; if (!over) OVER = 0;
                    if (!ok) UNDER = 0;
                    if (hdr_check_cancel(0)) goto end;
                }
            }
            break;
        }
    }

    hdr_create_script(f0, 0);

end:
    lens_cleanup_af();
}

// skip0: don't take the middle exposure
static void hdr_take_pics(int steps, int step_size, int skip0)
{
    if (steps < 2)  // auto number of steps, based on highlight/shadow levels
    {
        hdr_auto_take_pics(step_size, skip0);
        return;
    }
    //~ NotifyBox(2000, "hdr_take_pics: %d, %d, %d", steps, step_size, skip0); msleep(2000);
    int i;
    
    // make sure it won't autofocus
    lens_setup_af(AF_DISABLE);
    // be careful: don't return without restoring the setting back!
    
    hdr_check_cancel(1);

    // first frame for the bracketing script
    int f0 = hdr_script_get_first_file_number(skip0);

    // first exposure is always at 0 EV (and might be skipped)
    if (!skip0) hdr_shutter_release(0);
    if (hdr_check_cancel(0)) goto end;
    
    switch (hdr_sequence)
    {
        case 1: // 0 - + -- ++ 
        {
            for( i = 1; i <= steps/2; i ++  )
            {
                hdr_shutter_release(-step_size * i);
                if (hdr_check_cancel(0)) goto end;

                if (steps % 2 == 0 && i == steps/2) break;
                
                hdr_shutter_release(step_size * i);
                if (hdr_check_cancel(0)) goto end;
            }
            break;
        }
        case 0: // 0 - --
        case 2: // 0 + ++
        {
            for( i = 1; i < steps; i ++  )
            {
                hdr_shutter_release(step_size * i * (hdr_sequence == 2 ? 1 : -1));
                if (hdr_check_cancel(0)) goto end;
            }
            break;
        }
    }

    hdr_create_script(f0, 0);

end:
    lens_cleanup_af();
}
#endif

static void press_rec_button()
{
#if defined(CONFIG_50D) || defined(CONFIG_5D2)
    fake_simple_button(BGMT_PRESS_SET);
#else
    fake_simple_button(BGMT_LV);
#endif
}

void movie_start()
{
#ifdef CONFIG_MOVIE
    while (get_halfshutter_pressed()) msleep(100);
    if (!job_state_ready_to_take_pic()) return; 

    ensure_movie_mode();
    
    if (recording)
    {
        NotifyBox(2000, "Already recording ");
        return;
    }
    
    #if defined(CONFIG_500D) || defined(CONFIG_50D) || defined(CONFIG_5D2) // record button is used in ML menu => won't start recording
    //~ gui_stop_menu(); msleep(1000);
    while (gui_menu_shown())
    {
        gui_stop_menu();
        msleep(1000);
    }
    #endif
    
    while (get_halfshutter_pressed()) msleep(100);
    
    press_rec_button();
    
    for (int i = 0; i < 30; i++)
    {
        msleep(100);
        if (recording == 2) break; // recording started
    }
    msleep(500);
#endif
}

void movie_end()
{
#ifdef CONFIG_MOVIE
    if (shooting_type != 3 && !is_movie_mode())
    {
        NotifyBox(2000, "movie_end: not movie mode (%d,%d) ", shooting_type, shooting_mode);
        return;
    }
    if (!recording)
    {
        NotifyBox(2000, "movie_end: not recording ");
        return;
    }

    while (get_halfshutter_pressed()) msleep(100);

    msleep(500);

    press_rec_button();

    // wait until it stops recording, but not more than 2s
    for (int i = 0; i < 20; i++)
    {
        msleep(100);
        if (!recording) break;
    }
    msleep(500);
#endif
}

// take one picture or a HDR / focus stack sequence
// to be used with the intervalometer, focus stack, etc
// AF is disabled (don't enable it here, it will only introduce weird bugs)
void hdr_shot(int skip0, int wait)
{
    NotifyBoxHide();
#ifdef FEATURE_HDR_BRACKETING
    if (HDR_ENABLED)
    {
        //~ NotifyBox(1000, "HDR shot (%dx%dEV)...", hdr_steps, hdr_stepsize/8); msleep(1000);
        lens_wait_readytotakepic(64);

        int drive_mode_bak = set_drive_single();

        hdr_take_pics(hdr_steps, hdr_stepsize, skip0);

        lens_wait_readytotakepic(64);
        if (drive_mode_bak >= 0) lens_set_drivemode(drive_mode_bak);
    }
    else // regular pic (not HDR)
#endif
    {
        lens_setup_af(AF_DISABLE);
        hdr_shutter_release(0);
        lens_cleanup_af();
    }

    lens_wait_readytotakepic(64);
    picture_was_taken_flag = 0;
}

int remote_shot_flag = 0; // also in lcdsensor.c
void schedule_remote_shot() { remote_shot_flag = 1; }

static int movie_start_flag = 0;
void schedule_movie_start() { movie_start_flag = 1; }
//~ int is_movie_start_scheduled() { return movie_start_flag; }

static int movie_end_flag = 0;
void schedule_movie_end() { movie_end_flag = 1; }

void get_out_of_play_mode(int extra_wait)
{
    if (gui_state == GUISTATE_QR)
    {
        fake_simple_button(BGMT_PLAY);
        msleep(200);
        fake_simple_button(BGMT_PLAY);
    }
    else if (PLAY_MODE) 
    {
        fake_simple_button(BGMT_PLAY);
    }
    while (PLAY_MODE) msleep(100);
    msleep(extra_wait);
}

// take one shot, a sequence of HDR shots, or start a movie
// to be called by remote triggers
void remote_shot(int wait)
{
    // save zoom value (x1, x5 or x10)
    int zoom = lv_dispsize;
    
    #ifdef FEATURE_FOCUS_STACKING
    if (is_focus_stack_enabled())
    {
        focus_stack_run(0);
    }
    else
    #endif
    if (is_movie_mode())
    {
        movie_start();
    }
    else if (HDR_ENABLED)
    {
        hdr_shot(0, wait);
    }
    else
    {
        take_fast_pictures(pics_to_take_at_once+1);
    }
    if (!wait) return;
    
    lens_wait_readytotakepic(64);
    msleep(500);
    while (gui_state != GUISTATE_IDLE) msleep(100);
    msleep(500);
    // restore zoom
    if (lv && !recording && zoom > 1) set_lv_zoom(zoom);

    picture_was_taken_flag = 0;
}


static void display_expsim_status()
{
#ifdef CONFIG_EXPSIM
    get_yuv422_vram();
    static int prev_expsim = 0;
    int x = 610 + font_med.width;
    int y = os.y_max - os.off_169 - font_med.height - 5;
    if (!get_expsim())
    {
        bmp_printf( FONT(FONT_MED, COLOR_WHITE, 0), x, y, " ExpSim " );
        draw_line(x-5 + font_med.width, y + font_med.height * 3/4, x + font_med.width * 7, y + font_med.height * 1/4, COLOR_WHITE);
    }
    else
    {
        if (get_expsim() != prev_expsim)// redraw();
            bmp_printf( FONT(FONT_MED, COLOR_WHITE, 0), x, y, "        " );
    }
    prev_expsim = get_expsim();
#endif
}

void display_shooting_info_lv()
{
#ifndef CONFIG_5D2
    int screen_layout = get_screen_layout();
    int audio_meters_at_top = audio_meters_are_drawn() 
        && (screen_layout == SCREENLAYOUT_3_2);

    display_lcd_remote_icon(450, audio_meters_at_top ? 25 : 3);
#endif
    display_trap_focus_info();
    display_expsim_status();
}

static void display_trap_focus_msg()
{
#ifdef FEATURE_TRAP_FOCUS
#ifndef DISPLAY_TRAP_FOCUSMSG_POS_X
#define DISPLAY_TRAP_FOCUSMSG_POS_X 10
#define DISPLAY_TRAP_FOCUSMSG_POS_Y 10
#endif
    int bg = bmp_getpixel(DISPLAY_TRAP_FOCUS_POS_X, DISPLAY_TRAP_FOCUS_POS_Y);
    int fg = COLOR_FG_NONLV;
    char *msg = "                \n                \n                ";

    switch(trap_focus_msg)
    {
        case TRAP_ERR_CFN:
            msg = "Trap Focus:     \nCFn Fail. Set AF\n to shutter btn ";
            break;
        case TRAP_IDLE:
            msg = "Trap Focus:     \nIDLE, press half\nshutter shortly ";
            break;
        case TRAP_ACTIVE:
            msg = "Trap Focus:     \nACTIVE, keys are\ncurrently locked";
            break;
    }
    
    static int dirty = 0;
    if (trap_focus_msg)
    {
        bmp_printf(FONT(FONT_MED, fg, bg), DISPLAY_TRAP_FOCUSMSG_POS_X, DISPLAY_TRAP_FOCUSMSG_POS_Y, msg);
        dirty = 1;
    }
    else if (dirty) // clean old message, if any
    {
        redraw();
        dirty = 0;
    }
#endif
}

void display_trap_focus_info()
{
#ifdef FEATURE_TRAP_FOCUS
    int show, fg, bg, x, y;
    static int show_prev = 0;
    if (lv)
    {
        show = trap_focus && can_lv_trap_focus_be_active();
        int active = show && get_halfshutter_pressed();
        bg = active ? COLOR_BG : 0;
        fg = active ? COLOR_RED : COLOR_BG;
        x = 8; y = 160;
        if (show || show_prev)
        {
            bmp_printf(FONT(FONT_MED, fg, bg), x, y, show ? "TRAP \nFOCUS" : "     \n     ");
        }
    }
    else
    {
        show = (trap_focus && ((af_mode & 0xF) == 3) && lens_info.raw_aperture);
        bg = bmp_getpixel(DISPLAY_TRAP_FOCUS_POS_X, DISPLAY_TRAP_FOCUS_POS_Y);
        fg = HALFSHUTTER_PRESSED ? COLOR_RED : COLOR_FG_NONLV;
        x = DISPLAY_TRAP_FOCUS_POS_X; y = DISPLAY_TRAP_FOCUS_POS_Y;
        if (show || show_prev) bmp_printf(FONT(FONT_MED, fg, bg), x, y, show ? DISPLAY_TRAP_FOCUS_MSG : DISPLAY_TRAP_FOCUS_MSG_BLANK);
        
        display_trap_focus_msg();
    }
    show_prev = show;
#endif
}

void intervalometer_stop()
{
#ifdef FEATURE_INTERVALOMETER
    if (intervalometer_running)
    {
        intervalometer_running = 0;
        #ifdef FEATURE_BULB_RAMPING
        bramp_init_state = 0;
        #endif
        NotifyBox(2000, "Intervalometer stopped.");
        //~ display_on();
    }
#endif
}

int handle_intervalometer(struct event * event)
{
#ifdef FEATURE_INTERVALOMETER
    // stop intervalometer with MENU or PLAY
    if (!IS_FAKE(event) && (event->param == BGMT_MENU || event->param == BGMT_PLAY) && !gui_menu_shown())
        intervalometer_stop();
    return 1;
#endif
}

// this syncs with DIGIC clock from clock_task
void wait_till_next_second()
{
    int prev_t = get_seconds_clock();
    while (1)
    {
        int t = get_seconds_clock();
        if (t != prev_t) break;
        prev_t = t;
        msleep(20);
    }
}

#ifdef FEATURE_MLU_DIRECT_PRINT_SHORTCUT
// use direct print button to toggle MLU and display its status
int handle_mlu_toggle(struct event * event)
{
    if (event->param == BGMT_PRESS_DIRECT_PRINT && display_idle())
    {
        int m = !get_mlu();
        set_mlu(m);
        if (mlu_auto)
        {
            static int prev_drive_mode = DRIVE_SINGLE;
            if (m)
            {
                if (drive_mode != DRIVE_SELFTIMER_REMOTE) prev_drive_mode = drive_mode;
                lens_set_drivemode(DRIVE_SELFTIMER_REMOTE);
            }
            else
            {
                lens_set_drivemode(prev_drive_mode);
            }
        }
        return 0;
    }
    return 1;
}
#endif

#ifdef FEATURE_MLU
PROP_HANDLER(PROP_DRIVE)
{
    drive_mode = buf[0];
    mlu_selftimer_update();
}

static void mlu_step()
{
    if (lv) return;

#ifdef FEATURE_MLU_DIRECT_PRINT_SHORTCUT
    int mlu = get_mlu();
    static int prev_mlu = 0;
    if (mlu) info_led_on();
    else if (prev_mlu) info_led_off();
    prev_mlu = mlu;
#endif

    if (MLU_ALWAYS_ON)
    {
        if (!get_mlu()) set_mlu(1);
    }
}
#endif

// continuous, hi-speed, silent continuous, depending on the camera
int is_continuous_drive()
{
    return
        (
            drive_mode == DRIVE_CONTINUOUS 
            #ifdef DRIVE_HISPEED_CONTINUOUS
            || drive_mode == DRIVE_HISPEED_CONTINUOUS
            #endif
            #ifdef DRIVE_SILENT_CONTINUOUS
            || drive_mode == DRIVE_SILENT_CONTINUOUS
            #endif
        );
}

void take_fast_pictures( int number ) 
{
    // take fast pictures
#ifdef CONFIG_PROP_REQUEST_CHANGE
    if ( number > 1 && is_continuous_drive() && !is_bulb_mode() && !snap_sim)
    {
        lens_setup_af(shoot_use_af ? AF_ENABLE : AF_DISABLE);
        
        // continuous mode - simply hold shutter pressed 
        int f0 = file_number;
        SW1(1,100);
        SW2(1,100);
        while (mod(f0 + number - file_number + 10, 10000) > 10 && get_halfshutter_pressed()) {
            msleep(10);
        }
        SW2(0,100);
        SW1(0,100);

        #if defined(CONFIG_7D)
        /* on EOS 7D the code to trigger SW1/SW2 is buggy that the metering somehow locks up.
         * This causes the camera not to shut down when the card door is opened.
         * There is a workaround: Just wait until shooting is possible again and then trigger SW1 for a short time.
         * Then the camera will shut down clean.
         */
        lens_wait_readytotakepic(64);
        SW1(1,50);
        SW1(0,50);
        #endif

        lens_cleanup_af();
    }
    else
#endif
    {
        for (int i = 0; i < number; i++)
        {
            take_a_pic(shoot_use_af ? AF_ENABLE : AF_DISABLE, 1);
        }
    }
}

#ifdef FEATURE_MOTION_DETECT
static void md_take_pics() // for motion detection
{
    if (motion_detect_delay > 1) {
        for (int t=0; t<(int)motion_detect_delay; t++) {
            bmp_printf(FONT_MED, 0, 80, " Taking picture in %d.%ds   ", (int)(motion_detect_delay-t)/10, (int)(motion_detect_delay-t)%10);
            msleep(100);
            int mdx = motion_detect && (liveview_display_idle() || (lv && !DISPLAY_IS_ON)) && !recording && !gui_menu_shown();
            if (!mdx) return;
        }
    }
    take_fast_pictures( pics_to_take_at_once+1 );
    
    // wait until liveview comes back
    lens_wait_readytotakepic(64);
    for (int i = 0; i < 50; i++)
    {
        msleep(100);
        if (lv) break;
    }
    msleep(1000);
}
#endif

static struct msg_queue * shoot_task_mqueue = NULL;

/* cause an immediate redraw of the shooting task infos. not used yet, but can be triggered by model-specific code */
void shoot_task_redraw()
{
    if(shoot_task_mqueue)
    {
        msg_queue_post(shoot_task_mqueue, 1);
    }
}


static void misc_shooting_info()
{
    if (!DISPLAY_IS_ON) return;
    
    display_shortcut_key_hints_lv();

    if (get_global_draw())
    {
        #ifdef CONFIG_PHOTO_MODE_INFO_DISPLAY
        if (!lv && display_idle())
        BMP_LOCK
        (
            display_shooting_info();
            free_space_show_photomode();
        )
        #endif
    
        if (lv && !gui_menu_shown())
        {
            BMP_LOCK (
                display_shooting_info_lv();
            )
            #ifdef CONFIG_MOVIE_AE_WARNING
            #if defined(CONFIG_5D2)
            static int ae_warned = 0;
            if (is_movie_mode() && !lens_info.raw_shutter && recording && MVR_FRAME_NUMBER < 10)
            {
                if (!ae_warned && !gui_menu_shown())
                {
                    msleep(2000);
                    bmp_printf(SHADOW_FONT(FONT_MED), 50, 50, 
                        "!!! Auto exposure !!!\n"
                        "Use M mode and set 'LV display: Movie' from Expo menu");
                    msleep(4000);
                    redraw();
                    ae_warned = 1;
                }
            }
            else ae_warned = 0;
            #else
            if (is_movie_mode() && !ae_mode_movie && lv_dispsize == 1) 
            {
                static int ae_warned = 0;
                if (!ae_warned && !gui_menu_shown())
                {
                    bmp_printf(SHADOW_FONT(FONT_MED), 50, 50, 
                        "!!! Auto exposure !!!\n"
                        "Set 'Movie Exposure -> Manual' from Canon menu");
                    msleep(2000);
                    redraw();
                    ae_warned = 1;
                }
            }
            #endif
            #endif
            
            if (EXT_MONITOR_RCA) 
            {
                static int rca_warned = 0;
                if (!rca_warned && !gui_menu_shown())
                {
                    msleep(2000);
                    if (EXT_MONITOR_RCA) // check again
                    {
                        bmp_printf(SHADOW_FONT(FONT_LARGE), 50, 50, 
                            "SD monitors NOT fully supported!\n"
                            "RGB tools and MZoom won't work. ");
                        msleep(4000);
                        redraw();
                        rca_warned = 1;
                    }
                }
            }
        }
    }
}

static void
shoot_task( void* unused )
{
    /* this is used to determine if a feature is active that requires high task rate */
    int priority_feature_enabled = 0;

    /* creating a message queue primarily for interrupting sleep to repaint immediately */
    shoot_task_mqueue = (void*)msg_queue_create("shoot_task_mqueue", 1);

    bulb_shutter_valuef = (float)timer_values[bulb_duration_index];
    
    #ifdef FEATURE_MLU
    mlu_selftimer_update();
    #endif
    
    /*int loops = 0;
    int loops_abort = 0;*/
    TASK_LOOP
    {
        int msg;
        int delay = 50;
        
        /* specify the maximum wait time */
        if(!DISPLAY_IS_ON)
        {
            delay = 200;
        }
        if(priority_feature_enabled)
        {
            delay = MIN_MSLEEP;
        }
        int err = msg_queue_receive(shoot_task_mqueue, (struct event**)&msg, delay);        

        priority_feature_enabled = 0;

        /* when we received a message, redraw immediately */
        if (k%5 == 0 || !err) misc_shooting_info();

#if defined(CONFIG_MODULES)
        module_exec_cbr(CBR_SHOOT_TASK);
#endif

        #ifdef FEATURE_MLU_HANDHELD_DEBUG
        if (mlu_handled_debug) big_bmp_printf(FONT_MED, 50, 100, "%s", mlu_msg);
        #endif
        
        if (lcd_release_running)
            priority_feature_enabled = 1;

        #ifdef FEATURE_WHITE_BALANCE
        if (kelvin_auto_flag)
        {
            kelvin_auto_run();
            kelvin_auto_flag = 0;
        }
        if (wbs_gm_auto_flag)
        {
            wbs_gm_auto_run();
            wbs_gm_auto_flag = 0;
        }
        #endif
        
        #ifdef FEATURE_LCD_SENSOR_REMOTE
        lcd_release_step();
        #endif
        
        #ifdef FEATURE_EXPO_LOCK
        expo_lock_step();
        #endif
        
        if (remote_shot_flag)
        {
            remote_shot(1);
            remote_shot_flag = 0;
        }
        #ifdef CONFIG_MOVIE
        if (movie_start_flag)
        {
            movie_start();
            movie_start_flag = 0;
        }
        if (movie_end_flag)
        {
            movie_end();
            movie_end_flag = 0;
        }
        #endif
        #ifdef FEATURE_LV_ZOOM_SETTINGS
        if (zoom_focus_ring_flag)
        {
            zoom_focus_ring_engage();
            zoom_focus_ring_flag = 0;
        }
        zoom_lv_face_step();
        zoom_focus_ring_step();
        #endif
        
        #ifdef FEATURE_ML_AUTO_ISO
        auto_iso_tweak_step();
        #endif
        
        #ifdef FEATURE_MLU
        mlu_step();
        #endif

        #ifdef FEATURE_LV_FOCUS_BOX_SNAP
        if (center_lv_aff)
        {
            center_lv_afframe_do();
            center_lv_aff = 0;
        }
        #endif

        #if defined(FEATURE_HDR_BRACKETING)
        // avoid camera shake for HDR shots => force self timer
        static int drive_mode_bk = -1;
        if ((HDR_ENABLED && hdr_delay) && drive_mode != DRIVE_SELFTIMER_2SEC && drive_mode != DRIVE_SELFTIMER_REMOTE)
        {
            priority_feature_enabled = 1;
            if (get_halfshutter_pressed())
            {
                drive_mode_bk = drive_mode;
                #ifndef CONFIG_5DC
                lens_set_drivemode(DRIVE_SELFTIMER_2SEC);
                #endif
                info_led_on();
                msleep(100);
            }
        }
        
        // restore drive mode if it was changed
        if (!get_halfshutter_pressed() && drive_mode_bk >= 0)
        {
            msleep(50);
            lens_set_drivemode(drive_mode_bk);
            drive_mode_bk = -1;
            info_led_off();
            msleep(100);
        }
        #endif
    
        #ifdef FEATURE_BULB_TIMER
        if (bulb_timer && is_bulb_mode() && !gui_menu_shown())
        {
            // look for a transition of half-shutter during idle state
            static int was_idle_not_pressed = 0;
            int is_idle_not_pressed = !get_halfshutter_pressed() && display_idle();
            int is_idle_and_pressed = get_halfshutter_pressed() && display_idle();
            int trigger_condition = was_idle_not_pressed && is_idle_and_pressed;
            was_idle_not_pressed = is_idle_not_pressed;

            if (trigger_condition)
            {
                info_led_on();
                // need to keep halfshutter pressed for one second
                for (int i = 0; i < 10; i++)
                {
                    msleep(100);
                    if (!get_halfshutter_pressed() || !job_state_ready_to_take_pic()) break;
                }
                if (!get_halfshutter_pressed() || !job_state_ready_to_take_pic()) { info_led_off(); continue; }
                
                beep();
                info_led_blink(1,50,50); // short blink so you know bulb timer was triggered
                info_led_on();
                
                int d = BULB_SHUTTER_VALUE_S;
                NotifyBox(10000, "[HalfShutter] Bulb timer: %s", format_time_hours_minutes_seconds(d));
                while (get_halfshutter_pressed())
                {
                    msleep(100);
                }
                int m0 = shooting_mode;
                wait_till_next_second();
                NotifyBox(2000, "[2s] Bulb timer: %s", format_time_hours_minutes_seconds(d));
                info_led_on();
                wait_till_next_second();
                if (get_halfshutter_pressed() || !display_idle() || m0 != shooting_mode || !job_state_ready_to_take_pic()) 
                {
                    NotifyBox(2000, "Bulb timer canceled.");
                    info_led_off();
                    continue;
                }
                NotifyBox(2000, "[1s] Bulb timer: %s", format_time_hours_minutes_seconds(d));
                info_led_on();
                wait_till_next_second();
                if (get_halfshutter_pressed() || !display_idle() || m0 != shooting_mode || !job_state_ready_to_take_pic()) 
                {
                    NotifyBox(2000, "Bulb timer canceled.");
                    info_led_off();
                    continue;
                }
                info_led_off();
                bulb_take_pic(d * 1000);
            }
        }
        #endif
        
        if (picture_was_taken_flag) // just took a picture, maybe we should take another one
        {
            if (!recording)
            {
                #ifdef FEATURE_HDR_BRACKETING
                if (HDR_ENABLED)
                {
                    lens_wait_readytotakepic(64);
                    hdr_shot(1,1); // skip the middle exposure, which was just taken
                    lens_wait_readytotakepic(64); 
                }
                #endif
            }
            picture_was_taken_flag = 0;
        }

        #ifdef FEATURE_FLASH_TWEAKS
        // toggle flash on/off for next picture
        if (!is_movie_mode() && flash_and_no_flash && strobo_firing < 2 && strobo_firing != file_number % 2)
        {
            strobo_firing = file_number % 2;
            set_flash_firing(strobo_firing);
        }
        
        static int prev_flash_and_no_flash;
        if (!flash_and_no_flash && prev_flash_and_no_flash && strobo_firing==1)
            set_flash_firing(0);
        prev_flash_and_no_flash = flash_and_no_flash;

        #ifdef FEATURE_LV_3RD_PARTY_FLASH
        /* when pressing half-shutter in LV mode, this code will first switch to photo mode, wait for half-
           shutter release and then switches back. this will fire external flashes when running in LV mode.
         */
        if (lv_3rd_party_flash && !is_movie_mode())
        {
            if (lv && HALFSHUTTER_PRESSED)
            {
                /* timeout after 2 minutes */
                uint32_t loops = 1200;

                /* unpress half-shutter, maybe not really needed but might prevent confusion of gui tasks */
                SW1(0,100);
                
                /* switch into normal mode */
                fake_simple_button(BGMT_LV);
                
                while (lv && loops--)
                {
                    msleep(100);
                }

                /* re-press half-shutter */
                SW1(1,100);
                
                bmp_printf(FONT_MED, 0, 20, "(waiting for releasing half-shutter)");
                
                /* timeout after 2 minutes */
                loops = 1200;
                /* and wait for being released again */
                while (HALFSHUTTER_PRESSED && loops--) msleep(100);

                if(loops)
                {
                    /* switch into LV mode again */
                    fake_simple_button(BGMT_LV);
                }
            }
        }
        #endif
        #endif
        
        #ifdef FEATURE_TRAP_FOCUS
        // trap focus (outside LV) and all the preconditions
        int tfx = trap_focus && is_manual_focus() && display_idle() && !intervalometer_running && !is_movie_mode();

        static int trap_focus_display_time = 0;
       
        /* in continuous mode force half shutter being pressed */
        switch(trap_focus_continuous_state)
        {
            case 0:
                /* do this only in continuous mode */
                if(trap_focus == 2)
                {
                    if(cfn_get_af_button_assignment()!=0)
                    {
                        if(should_run_polling_action(250, &trap_focus_display_time) && !gui_menu_shown())
                        {
                            trap_focus_msg = TRAP_ERR_CFN;
                        }
                    }
                    else if(HALFSHUTTER_PRESSED)
                    {
                        /* user requested enabling trap focus */
                        trap_focus_continuous_state = 1;
                    }
                    else
                    {
                        if(should_run_polling_action(250, &trap_focus_display_time) && !gui_menu_shown())
                        {
                            trap_focus_msg = TRAP_IDLE;
                        }
                    }
                }
                else
                {
                    trap_focus_msg = TRAP_NONE;
                }
                break;
                
            case 1:
                /* wait for user to release his shutter button, then set it on our own */
                if(!HALFSHUTTER_PRESSED)
                {
                    trap_focus_continuous_state = 2;
                    SW1(1,50);
                }
                break;
                
            case 2:
                info_led_off();
                priority_feature_enabled = 1;
                /* some abort situation happened? */
                if(gui_menu_shown() || !display_idle() || !HALFSHUTTER_PRESSED || !tfx || trap_focus != 2)
                {
                    trap_focus_continuous_state = 0;
                    SW1(0,50);
                }
                else
                {
                    if(should_run_polling_action(250, &trap_focus_display_time))
                    {
                        trap_focus_msg = TRAP_ACTIVE;
                    }
                }
                break;
                
            case 3:
                /* re-enable after pic was taken */
                trap_focus_continuous_state = 1;
                priority_feature_enabled = 1;
                SW1(1,50);
                break;        
        }
        #else
        int tfx = 0;
        #endif

        #ifdef FEATURE_MOTION_DETECT
        if (motion_detect && motion_detect_trigger < 2 && !lv && display_idle() && !gui_menu_shown())
        {
            // plain photo mode, go to LiveView
            force_liveview();
        }

        // same for motion detect
        int mdx = motion_detect && (liveview_display_idle() || (lv && !DISPLAY_IS_ON)) && !recording && !gui_menu_shown();
        #else
        int mdx = 0;
        #endif

        #ifdef FEATURE_TRAP_FOCUS
        if (tfx) // MF
        {
            static int info_led_turned_on = 0;
            
            if (HALFSHUTTER_PRESSED)
            {
                info_led_on();
                info_led_turned_on = 1;
            }
            else if (info_led_turned_on)
            {
                info_led_off();
                info_led_turned_on = 0;
            }
            if ((!lv && FOCUS_CONFIRMATION) || get_lv_focus_confirmation())
            {
                take_fast_pictures(pics_to_take_at_once+1);

                /* continuous shooting active? */
                if (trap_focus_continuous_state)
                {
                    /* wait the review time then re-engage again */
                    if (image_review_time)
                    {
                        msleep(2000);
                    }

                    trap_focus_continuous_state = 3;
                }
            }
        }
        #endif

        #ifdef FEATURE_MOTION_DETECT
        //Reset the counter so that if you go in and out of live view, it doesn't start clicking away right away.
        static int K = 0;

        if(!mdx) K = 0;
        
        if (mdx)
        {
            priority_feature_enabled = 1;
            K = COERCE(K+1, 0, 1000);
            //~ bmp_printf(FONT_MED, 0, 50, "K= %d   ", K);
            int xcb = os.x0 + os.x_ex/2;
            int ycb = os.y0 + os.y_ex/2;
            
            int detect_size = 
                motion_detect_size == 0 ? 80 : 
                motion_detect_size == 1 ? 120 : 
                                          200 ;

            // center the motion detection window on focus box
            {
                get_afframe_pos(os.x_ex, os.y_ex, &xcb, &ycb);
                xcb += os.x0;
                ycb += os.y0;
                xcb = COERCE(xcb, os.x0 + (int)detect_size, os.x_max - (int)motion_detect_size );
                ycb = COERCE(ycb, os.y0 + (int)detect_size, os.y_max - (int)motion_detect_size );
             }

            if (motion_detect_trigger == 0)
            {
                int aev = 0;
                //If the new value has changed by more than the detection level, shoot.
                static int old_ae_avg = 0;
                int y,u,v;
                //TODO: maybe get the spot yuv of the target box
                get_spot_yuv_ex(detect_size, xcb-os.x_max/2, ycb-os.y_max/2, &y, &u, &v, 1, 1);
                aev = y / 2;
                if (K > 40) bmp_printf(FONT_MED, 0, 20, "Average exposure: %3d    New exposure: %3d   ", old_ae_avg/100, aev);
                if (K > 40 && ABS(old_ae_avg/100 - aev) >= (int)motion_detect_level)
                {
                    md_take_pics();
                    K = 0;
                }
                if (K == 40) idle_force_powersave_in_1s();
                old_ae_avg = old_ae_avg * 90/100 + aev * 10;
            }
            else if (motion_detect_trigger == 1) 
            {
                int d = get_spot_motion(detect_size, xcb, ycb, get_global_draw());
                if (K > 20) bmp_printf(FONT_MED, 0, 20, "Motion level: %d   ", d);
                if (K > 20 && d >= (int)motion_detect_level)
                {
                    md_take_pics();
                    K = 0;
                }
                if (K == 40) idle_force_powersave_in_1s();
            }
            else if (motion_detect_trigger == 2)
            {
                int hs = HALFSHUTTER_PRESSED;
                static int prev_hs = 0;
                static int prev_d[30];
                if (hs)
                {
                    int d = get_spot_motion(detect_size, xcb, ycb, get_global_draw());
                    
                    for (int i = 29; i > 0; i--)
                        prev_d[i] = prev_d[i-1];
                    prev_d[0] = d;
                    
                    int dmax = 0;
                    for (int i = 0; i < 30; i++)
                    {
                        dmax = MAX(dmax, prev_d[i]);
                    }
                    int steady = (dmax <= motion_detect_level);

                    for (int i = 1; i < 30; i++)
                    {
                        int d = MIN(prev_d[i], 30);
                        bmp_draw_rect(d <= motion_detect_level ? COLOR_CYAN : COLOR_RED, 60 - i*2, 100 - d, 1, d);
                        bmp_draw_rect(steady ? COLOR_GREEN1 : COLOR_BLACK, 60 - i*2, 100 - 30, 1, 30 - d);
                    }

                    bmp_printf(FONT_MED, 0, 20, "Motion level: %d   ", dmax);
                    if (steady)
                    {
                        md_take_pics();
                    }
                }
                else
                {
                    if (prev_hs) redraw();
                    prev_d[0] = 100;
                }
                prev_hs = hs;
            }
        }
        
        // this is an attempt to make "steady hands" detection work outside liveview too (well, sort of)
        // when you press shutter halfway, LiveView will be enabled temporarily (with display off)
        // and once the motion detect engine says "camera steady", the picture is taken and LiveView is turned off
        static int lv_forced_by_md = 0;
        if (!mdx && motion_detect && motion_detect_trigger == 2 && !lv && display_idle() && get_halfshutter_pressed())
        {
            priority_feature_enabled = 1;
            for (int i = 0; i < 10; i++)
            {
                if (!get_halfshutter_pressed()) break;
                msleep(50);
            }
            if (!get_halfshutter_pressed()) continue;
            SW1(0,50);
            fake_simple_button(BGMT_LV);
            for (int i = 0; i < 20; i++)
            {
                if (lv && DISPLAY_IS_ON) display_off();
                msleep(50);
            }
            if (lv)
            {
                SW1(1,50);
                lv_forced_by_md = 1;
                info_led_on();
            }
        }

        if (lv_forced_by_md && lv && DISPLAY_IS_ON) display_off();
        
        if (lv_forced_by_md && lv && !get_halfshutter_pressed())
        {
            info_led_off();
            fake_simple_button(BGMT_LV);
            msleep(500);
            lv_forced_by_md = 0;
        }
        #endif // motion detect
        
        #ifdef FEATURE_SILENT_PIC
        static int silent_pic_countdown;
        if (!display_idle())
        {
            silent_pic_countdown = 10;
        }
        else if (!get_halfshutter_pressed())
        {
            if (silent_pic_countdown) silent_pic_countdown--;
        }

        if (lv && silent_pic_enabled && get_halfshutter_pressed())
        {
            if (silent_pic_countdown) // half-shutter was pressed while in playback mode, for example
                continue;
            if (!HDR_ENABLED) silent_pic_take(1);
            else 
            {
                NotifyBox(5000, "HDR silent picture...");
                //~ if (beep_enabled) Beep();
                while (get_halfshutter_pressed()) msleep(100);
                if (!lv) force_liveview();
                hdr_shot(0,1);
            }
        }
        #endif
        
        #ifdef FEATURE_INTERVALOMETER        
        #define SECONDS_REMAINING (intervalometer_next_shot_time - seconds_clock)
        #define SECONDS_ELAPSED (seconds_clock - seconds_clock_0)
        if (intervalometer_running)
        {
            int seconds_clock_0 = seconds_clock;
            int display_turned_off = 0;
            //~ int images_compared = 0;
            msleep(20);
            while (SECONDS_REMAINING > 0 && !ml_shutdown_requested)
            {
                int dt = timer_values[interval_timer_index];
                msleep(dt < 5 ? 20 : 300);

                if (!intervalometer_running) break; // from inner loop only
                
                if (gui_menu_shown() || get_halfshutter_pressed())
                {
                    wait_till_next_second();

                    if (intervalometer_pictures_taken == 0)
                        intervalometer_next_shot_time = seconds_clock + MAX(timer_values[interval_start_timer_index], 1);
                    else
                        intervalometer_next_shot_time++;
                    continue;
                }
                
                static char msg[60];
                snprintf(msg, sizeof(msg),
                                " Intervalometer:%4d \n"
                                " Pictures taken:%4d ", 
                                SECONDS_REMAINING,
                                intervalometer_pictures_taken);
                if (interval_stop_after) { STR_APPEND(msg, "/ %d", interval_stop_after); }
                #ifdef CONFIG_VXWORKS
                bmp_printf(FONT_LARGE, 50, 310, msg);
                #else
                bmp_printf(FONT_MED, 50, 310, msg);
                #endif

                if (interval_stop_after && (int)intervalometer_pictures_taken >= (int)(interval_stop_after))
                    intervalometer_stop();

                //~ if (bulb_ramping_enabled)
                //~ {
                    //~ bramp_temporary_exposure_compensation_update();
                //~ }

                //~ if (!images_compared && SECONDS_ELAPSED >= 2 && SECONDS_REMAINING >= 2 && image_review_time - SECONDS_ELAPSED >= 1 && bramp_init_done)
                //~ {
                    //~ playback_compare_images(0);
                    //~ images_compared = 1; // do this only once
                //~ }
                
                if (PLAY_MODE && SECONDS_ELAPSED >= image_review_time)
                {
                    get_out_of_play_mode(0);
                }

                if (lens_info.job_state == 0 && liveview_display_idle() && intervalometer_running && !display_turned_off)
                {
                    idle_force_powersave_in_1s();
                    display_turned_off = 1; // ... but only once per picture (don't be too aggressive)
                }

                #ifdef FEATURE_BULB_RAMPING
                if (BULB_EXPOSURE_CONTROL_ACTIVE) bulb_ramping_init();
                #endif
            }

            if (interval_stop_after && (int)intervalometer_pictures_taken >= (int)(interval_stop_after))
                intervalometer_stop();

            if (PLAY_MODE) get_out_of_play_mode(500);
            if (LV_PAUSED) ResumeLiveView();

            if (!intervalometer_running) continue; // back to start of shoot_task loop
            if (gui_menu_shown() || get_halfshutter_pressed()) continue;

            if (!intervalometer_running) continue;
            if (gui_menu_shown() || get_halfshutter_pressed()) continue;

            int dt = timer_values[interval_timer_index];
            // compute the moment for next shot; make sure it stays somewhat in sync with the clock :)
            //~ intervalometer_next_shot_time = intervalometer_next_shot_time + dt;
            intervalometer_next_shot_time = COERCE(intervalometer_next_shot_time + dt, seconds_clock, seconds_clock + dt);
            
            #ifdef FEATURE_MLU
            mlu_step(); // who knows who has the idea of changing drive mode with intervalometer active :)
            #endif
            
            if (dt == 0) // crazy mode - needs to be fast
            {
                int num = interval_stop_after ? interval_stop_after : 100000;
                take_fast_pictures(num);
                intervalometer_pictures_taken += num - 1;
            }
            else if (HDR_ENABLED)
            {
                hdr_shot(0, 1);
            }
            else
            {
                // count this as 1 picture
                take_fast_pictures(pics_to_take_at_once+1);
            }
            intervalometer_next_shot_time = MAX(intervalometer_next_shot_time, seconds_clock);
            intervalometer_pictures_taken++;

            #ifdef FEATURE_BULB_RAMPING
            if (BULB_EXPOSURE_CONTROL_ACTIVE)
            {
                bulb_ramping_init(); // just in case
                compute_exposure_for_next_shot();
            }
            #endif

            #ifndef CONFIG_VXWORKS
            if (lv && silent_pic_enabled) // half-press shutter to disable power management
            {
                lens_setup_af(AF_DISABLE);
                SW1(1,10);
                SW1(0,50);
                lens_cleanup_af();
                msleep(300);
            }
            #endif
           
        }
        else // intervalometer not running
        #endif // FEATURE_INTERVALOMETER
        {
            #ifdef FEATURE_INTERVALOMETER
            #ifdef FEATURE_BULB_RAMPING
            bramp_init_done = 0;
            bramp_cleanup();
            #endif
            intervalometer_pictures_taken = 0;
            intervalometer_next_shot_time = seconds_clock + MAX(timer_values[interval_start_timer_index], 1);
            #endif

#ifdef FEATURE_AUDIO_REMOTE_SHOT
#if defined(CONFIG_7D)
            /* experimental for 7D now, has to be made generic */
            static int last_audio_release_running = 0;
            
            if(audio_release_running != last_audio_release_running)
            {
                last_audio_release_running = audio_release_running;
                
                if(audio_release_running)
                {
                    void (*SoundDevActiveIn) (uint32_t) = 0xFF0640EC;
                    SoundDevActiveIn(0);
                }
            }
#endif
            if (audio_release_running) 
            {
                static int countdown = 0;
                if (!display_idle()) countdown = 20;
                if (countdown) { countdown--; }

                struct audio_level * audio_levels = get_audio_levels();

                static int avg_prev0 = 1000;
                static int avg_prev1 = 1000;
                static int avg_prev2 = 1000;
                static int avg_prev3 = 1000;
                int current_pulse_level = audio_level_to_db(audio_levels[0].peak_fast) - audio_level_to_db(avg_prev3);
    
                if (countdown == 0)
                {

                    bmp_printf(FONT(FONT_MED, COLOR_FG_NONLV, (lv ? COLOR_BG : bmp_getpixel(AUDIO_REM_SHOT_POS_X-2, AUDIO_REM_SHOT_POS_Y))), (lv ? 2 : AUDIO_REM_SHOT_POS_X),  (lv ? 30 : AUDIO_REM_SHOT_POS_Y), "Audio release ON (%2d / %2d)", current_pulse_level, audio_release_level);

                    if (current_pulse_level > (int)audio_release_level)
                    {
                        remote_shot(1);
                        msleep(100);
                        /* Initial forced sleep is necesarry when using camera self timer,
                         * otherwise remote_shot returns right after the countdown 
                         * and the loop below seems to miss the actual picture taking.
                         * This means we will trigger again on the sound of the shutter
                         * (and again, and again, ...)
                         * TODO: should this be fixed in remote_shot itself? */
                        while (lens_info.job_state && !ml_shutdown_requested) msleep(100);
                        countdown = 20;
                    }
                }
                avg_prev3 = avg_prev2;
                avg_prev2 = avg_prev1;
                avg_prev1 = avg_prev0;
                avg_prev0 = audio_levels[0].avg;
            }
#endif
        }
    }
}

TASK_CREATE( "shoot_task", shoot_task, 0, 0x1a, 0x2000 );

static void shoot_init()
{
    set_maindial_sem = create_named_semaphore("set_maindial_sem", 1);
    seconds_clock_sem = create_named_semaphore("seconds_clock_sem", 1);

    menu_add( "Shoot", shoot_menus, COUNT(shoot_menus) );
    menu_add( "Expo", expo_menus, COUNT(expo_menus) );
    
    //~ menu_add( "Tweaks", vid_menus, COUNT(vid_menus) );

    #ifdef FEATURE_EXPO_OVERRIDE
    extern struct menu_entry expo_override_menus[];
    menu_add( "Expo", expo_override_menus, 1 );
    #endif

    #ifdef FEATURE_EXPSIM
    extern struct menu_entry expo_tweak_menus[];
    menu_add( "Expo", expo_tweak_menus, 1 );
    #endif
}

INIT_FUNC("shoot", shoot_init);

void iso_refresh_display() // in photo mode
{
#ifdef FEATURE_INTERMEDIATE_ISO_PHOTO_DISPLAY
    if (!lv && display_idle())
    {
        if (lens_info.raw_iso % 8 != 0)
        {
            int bg = bmp_getpixel(MENU_DISP_ISO_POS_X, MENU_DISP_ISO_POS_Y-10);
            bmp_fill(bg, MENU_DISP_ISO_POS_X, MENU_DISP_ISO_POS_Y-10, 175, 85);
            char msg[30];
            snprintf(msg, sizeof(msg), "%d ", raw2iso(lens_info.raw_iso));
            int w = bfnt_draw_char(ICON_ISO, MENU_DISP_ISO_POS_X + 5, MENU_DISP_ISO_POS_Y + 10, COLOR_FG_NONLV, bg);
            bfnt_puts(msg, MENU_DISP_ISO_POS_X + w + 10, MENU_DISP_ISO_POS_Y + 10, COLOR_FG_NONLV, bg);
        }
    }
#endif
}