File size: 231,362 Bytes
2923df9
adcbc9f
b114cd4
adcbc9f
 
80ab93c
adcbc9f
 
b114cd4
adcbc9f
b114cd4
 
adcbc9f
80ab93c
adcbc9f
 
 
 
4299f7c
adcbc9f
 
26312c5
4299f7c
b934418
 
cd46d93
 
adcbc9f
b934418
cd46d93
adcbc9f
 
b114cd4
b934418
adcbc9f
 
b934418
adcbc9f
cd46d93
adcbc9f
53409b8
2923df9
951967e
4543735
adcbc9f
b780647
69f25b5
d80a2c7
b114cd4
 
 
1db4ef0
b780647
adcbc9f
2923df9
3888ab7
d80a2c7
3888ab7
22dd15a
 
 
 
 
d050f96
adcbc9f
22dd15a
adcbc9f
 
 
 
 
 
 
 
 
 
 
 
b114cd4
adcbc9f
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
5700ed3
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
d050f96
2dbdd2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
5700ed3
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a00d06
0f9efaa
 
 
 
8229bc2
 
 
 
 
 
 
 
7a65465
d80a2c7
d88d1e3
 
 
 
0676790
 
 
 
d88d1e3
 
 
 
69f25b5
 
487757b
69f25b5
 
 
 
 
 
 
487757b
 
 
8adc333
487757b
 
0676790
 
 
 
 
 
487757b
d80a2c7
 
 
 
5700ed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4c238
1db4ef0
 
 
 
 
2a4c238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1db4ef0
 
 
 
 
d88d1e3
 
 
0676790
 
d88d1e3
 
 
 
 
0676790
 
 
d88d1e3
0676790
 
d88d1e3
 
0676790
d88d1e3
 
 
0676790
 
 
 
 
 
 
 
 
 
 
 
d88d1e3
0676790
d88d1e3
 
0676790
d88d1e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f25b5
 
 
 
 
 
 
 
 
487757b
 
 
 
 
69f25b5
 
 
 
 
 
 
487757b
69f25b5
 
487757b
69f25b5
 
 
 
 
 
 
487757b
69f25b5
 
 
487757b
69f25b5
 
 
 
487757b
 
 
 
69f25b5
487757b
 
 
69f25b5
487757b
 
 
69f25b5
 
487757b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8adc333
487757b
 
 
 
69f25b5
 
 
 
 
 
487757b
 
 
 
 
 
 
69f25b5
487757b
 
69f25b5
487757b
 
 
 
 
 
 
 
69f25b5
487757b
 
 
 
 
22c681c
 
 
 
 
 
 
 
487757b
 
 
69f25b5
487757b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f25b5
487757b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f25b5
 
487757b
 
 
 
 
 
 
 
 
8adc333
487757b
8adc333
487757b
 
8adc333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487757b
 
 
 
 
 
69f25b5
487757b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0676790
487757b
0676790
 
 
487757b
 
 
 
0676790
 
 
 
 
 
487757b
8adc333
 
487757b
 
 
 
 
 
 
 
8adc333
487757b
8adc333
 
 
 
 
 
 
 
 
 
487757b
 
8adc333
487757b
69f25b5
 
 
0676790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adcbc9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b114cd4
adcbc9f
8229bc2
adcbc9f
 
 
80ab93c
b114cd4
 
58195d3
8229bc2
adcbc9f
 
b114cd4
 
2923df9
b114cd4
 
e835c5f
 
 
 
8229bc2
 
 
e835c5f
8229bc2
 
 
b114cd4
69f25b5
 
 
 
 
 
 
e835c5f
69f25b5
e835c5f
69f25b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b114cd4
8229bc2
 
 
 
 
 
e835c5f
 
8229bc2
 
 
58195d3
8229bc2
 
 
 
 
 
 
58195d3
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e835c5f
58195d3
e835c5f
58195d3
 
8229bc2
d80a2c7
 
 
e835c5f
8229bc2
e835c5f
8229bc2
 
 
 
 
7a65465
8229bc2
7a65465
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e835c5f
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
58195d3
d80a2c7
e835c5f
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a00d06
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f9efaa
8229bc2
 
 
 
 
 
 
 
 
 
0f9efaa
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
0f9efaa
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e835c5f
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b114cd4
 
 
 
 
 
2923df9
b114cd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44e9039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b114cd4
 
 
2923df9
b114cd4
 
 
 
 
2923df9
b114cd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4c238
b114cd4
 
 
 
2923df9
b114cd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adcbc9f
b114cd4
 
 
 
 
 
 
 
 
 
 
 
 
adcbc9f
5cb75be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adcbc9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2923df9
adcbc9f
 
 
 
 
 
 
b114cd4
adcbc9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d050f96
adcbc9f
 
 
 
 
 
 
 
 
 
 
 
 
5700ed3
adcbc9f
80ab93c
adcbc9f
 
 
 
 
2923df9
adcbc9f
 
 
 
 
e94f552
adcbc9f
 
 
 
 
 
 
 
5700ed3
adcbc9f
 
 
 
 
 
 
 
29090fa
adcbc9f
 
 
6df655f
8229bc2
adcbc9f
 
 
69f25b5
 
 
 
adcbc9f
 
 
 
 
 
 
 
8d39a27
4543735
adcbc9f
 
2a2c4ee
660b28d
adcbc9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1424ad3
 
adcbc9f
 
fe6e100
d80a2c7
 
 
adcbc9f
4543735
2967e03
adcbc9f
 
 
b101711
 
 
d80a2c7
b101711
 
 
 
 
 
 
 
 
 
 
2fd537d
adcbc9f
 
 
 
 
 
d80a2c7
 
adcbc9f
8ea7c59
b114cd4
adcbc9f
4543735
 
 
4d34e84
 
 
b114cd4
6df655f
 
abb25f7
cf7d19c
4d34e84
 
8d39a27
 
adcbc9f
410f581
6df655f
adcbc9f
d80a2c7
7485e9b
ffdd828
d80a2c7
736f5d9
d80a2c7
24957f5
d80a2c7
c0f9cf2
d80a2c7
1b6bdce
d57ab6a
d80a2c7
c0f9cf2
d80a2c7
884a083
8efd5f1
f2bdfe6
884a083
a967a4d
 
 
 
adcbc9f
8d39a27
6df655f
adcbc9f
d80a2c7
adcbc9f
d80a2c7
adcbc9f
 
d80a2c7
adcbc9f
d80a2c7
 
8b3de7f
d80a2c7
adcbc9f
b114cd4
d80a2c7
d46a61a
9ed302a
adcbc9f
d80a2c7
d46a61a
9ed302a
 
d80a2c7
d46a61a
9ed302a
4299f7c
d80a2c7
4801166
74f5b97
adcbc9f
406db87
74f5b97
adcbc9f
406db87
7a7d25f
adcbc9f
d80a2c7
cf187c8
 
adcbc9f
9a96351
 
74f5b97
9a96351
adcbc9f
9a96351
 
adcbc9f
cf187c8
d80a2c7
 
adcbc9f
d80a2c7
1424ad3
adcbc9f
d80a2c7
e94f552
 
adcbc9f
9a96351
adcbc9f
9a96351
 
8d69657
9a96351
 
 
 
 
598a5c4
adcbc9f
 
67e09bb
adcbc9f
 
 
 
 
 
 
 
d80a2c7
adcbc9f
 
 
 
 
 
57440b4
adcbc9f
 
 
 
 
 
 
f7f27b0
adcbc9f
d80a2c7
f7f27b0
adcbc9f
69f25b5
d80a2c7
69f25b5
adcbc9f
69f25b5
 
 
d88d1e3
69f25b5
 
487757b
 
 
 
 
 
69f25b5
487757b
 
69f25b5
 
487757b
69f25b5
487757b
69f25b5
0676790
69f25b5
0676790
69f25b5
 
 
 
 
0676790
 
 
 
 
 
 
69f25b5
0676790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f25b5
0676790
487757b
 
69f25b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adcbc9f
69f25b5
b114cd4
69f25b5
adcbc9f
 
 
69f25b5
f7f27b0
d80a2c7
adcbc9f
d80a2c7
adcbc9f
 
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
3858291
adcbc9f
 
fd58682
b114cd4
adcbc9f
 
 
 
2a2c4ee
adcbc9f
6df655f
91d5e8a
adcbc9f
 
 
 
fd58682
 
8a1f411
b114cd4
adcbc9f
58195d3
 
 
 
2923df9
58195d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adcbc9f
 
 
 
2923df9
 
d80a2c7
2923df9
 
 
2a4c238
 
 
 
2923df9
 
 
 
 
 
5700ed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
2923df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
5700ed3
 
2923df9
 
 
 
 
 
2a4c238
2923df9
 
2a4c238
2923df9
 
2a4c238
2923df9
 
2a4c238
2923df9
 
 
 
 
 
 
d80a2c7
2a4c238
2923df9
2a4c238
 
2923df9
d80a2c7
 
7339550
adcbc9f
d80a2c7
 
 
7339550
adcbc9f
7339550
 
 
 
 
d80a2c7
 
adcbc9f
 
d80a2c7
7339550
 
 
 
 
d80a2c7
 
 
 
2dbdd2e
2a4c238
 
2923df9
adcbc9f
7339550
 
 
d80a2c7
5cb75be
 
 
 
adcbc9f
2923df9
d050f96
d80a2c7
 
 
7339550
2923df9
 
22dd15a
2923df9
 
 
22dd15a
2923df9
22dd15a
7339550
2923df9
 
d80a2c7
 
 
 
2923df9
 
d80a2c7
 
2923df9
 
d80a2c7
 
 
2923df9
d80a2c7
 
 
 
b114cd4
d050f96
2dbdd2e
 
d050f96
2a4c238
d050f96
 
d80a2c7
d050f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dbdd2e
d050f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dbdd2e
d050f96
 
2dbdd2e
d050f96
 
 
 
 
 
2dbdd2e
d050f96
2dbdd2e
d050f96
2dbdd2e
 
 
 
 
 
 
 
2923df9
d050f96
 
 
2dbdd2e
 
 
 
 
d80a2c7
2dbdd2e
 
 
 
d050f96
 
 
2dbdd2e
 
 
d050f96
2a4c238
2dbdd2e
 
2a4c238
 
 
 
 
2dbdd2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a4c238
 
 
 
 
 
 
 
d80a2c7
 
 
 
2dbdd2e
2923df9
7339550
 
58195d3
 
 
d80a2c7
7339550
58195d3
 
 
d80a2c7
 
 
58195d3
d80a2c7
 
 
 
58195d3
d80a2c7
 
2dbdd2e
7339550
adcbc9f
d80a2c7
 
8229bc2
2dbdd2e
 
 
d050f96
2dbdd2e
 
22dd15a
2dbdd2e
 
 
 
 
 
 
d050f96
 
 
2dbdd2e
d050f96
 
2dbdd2e
 
 
d80a2c7
22dd15a
2dbdd2e
 
22dd15a
2dbdd2e
 
 
 
 
 
22dd15a
d050f96
 
 
 
2dbdd2e
 
 
 
 
 
 
22dd15a
2dbdd2e
22dd15a
2dbdd2e
 
 
22dd15a
2dbdd2e
 
d80a2c7
2dbdd2e
d80a2c7
2dbdd2e
d80a2c7
22dd15a
2dbdd2e
d80a2c7
2dbdd2e
d80a2c7
 
1309ddb
d80a2c7
d050f96
 
d80a2c7
 
2dbdd2e
d80a2c7
 
 
 
1db4ef0
 
 
2a4c238
1db4ef0
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7339550
d80a2c7
 
 
 
 
 
 
 
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
7339550
d80a2c7
7339550
 
d80a2c7
 
 
 
 
 
 
 
58195d3
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7339550
 
8229bc2
 
 
 
 
 
 
 
 
d80a2c7
 
8229bc2
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7339550
d80a2c7
 
 
 
 
7339550
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7339550
 
d80a2c7
 
 
 
 
 
 
 
 
 
58195d3
d80a2c7
 
 
 
 
58195d3
d80a2c7
 
 
 
 
 
 
 
4178195
 
 
 
 
 
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
adcbc9f
 
 
 
 
3888ab7
adcbc9f
 
 
800d0d0
adcbc9f
d050f96
adcbc9f
 
 
800d0d0
adcbc9f
 
 
22dd15a
 
 
 
 
 
 
 
 
 
 
 
d050f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58195d3
 
 
 
e835c5f
 
 
 
 
22dd15a
58195d3
e835c5f
58195d3
 
 
 
 
 
e835c5f
22dd15a
 
 
 
58195d3
 
22dd15a
58195d3
e835c5f
58195d3
e835c5f
58195d3
 
 
 
 
 
e835c5f
22dd15a
 
 
 
58195d3
22dd15a
 
58195d3
e835c5f
22dd15a
 
58195d3
22dd15a
58195d3
22dd15a
 
58195d3
e835c5f
58195d3
e835c5f
58195d3
 
 
 
 
 
e835c5f
22dd15a
 
58195d3
22dd15a
58195d3
22dd15a
 
 
 
 
 
 
 
 
 
 
58195d3
e835c5f
 
 
 
58195d3
 
 
 
 
 
e835c5f
 
 
58195d3
 
 
 
 
 
e835c5f
58195d3
e835c5f
58195d3
 
 
 
 
 
e835c5f
 
 
58195d3
 
 
 
 
 
e835c5f
22dd15a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
22dd15a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e835c5f
 
58195d3
 
 
 
 
 
e835c5f
 
 
58195d3
 
 
 
 
 
e835c5f
 
 
58195d3
 
 
 
 
 
e835c5f
 
 
58195d3
 
 
 
 
 
e835c5f
 
 
58195d3
 
 
 
 
 
e835c5f
22dd15a
e835c5f
 
58195d3
 
 
 
 
 
e835c5f
 
3888ab7
2923df9
 
 
 
 
d80a2c7
 
 
2923df9
 
 
d80a2c7
 
 
2923df9
 
 
 
 
d80a2c7
 
 
2923df9
 
 
d80a2c7
 
 
2923df9
 
 
d80a2c7
 
 
2923df9
 
 
d80a2c7
 
 
2923df9
 
 
d80a2c7
 
 
2923df9
 
 
 
 
d80a2c7
 
 
2923df9
 
 
d80a2c7
 
 
2923df9
 
 
d80a2c7
 
 
2923df9
 
 
d80a2c7
 
 
2923df9
 
 
 
 
d80a2c7
2923df9
22dd15a
d80a2c7
2923df9
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2923df9
 
 
 
 
 
 
 
 
 
d80a2c7
 
 
 
 
 
 
 
2923df9
 
 
 
 
 
 
d80a2c7
 
2923df9
d80a2c7
 
 
 
 
 
2923df9
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
2dbdd2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2923df9
d050f96
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
 
22dd15a
adcbc9f
58195d3
3888ab7
adcbc9f
 
80ab93c
adcbc9f
 
 
22dd15a
d80a2c7
 
 
 
 
 
 
 
 
 
adcbc9f
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adcbc9f
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f9efaa
 
 
d80a2c7
 
 
 
 
0f9efaa
e835c5f
2dbdd2e
d80a2c7
d050f96
2dbdd2e
 
 
 
d050f96
 
 
 
 
 
 
2dbdd2e
d050f96
 
2dbdd2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8229bc2
 
 
 
 
 
 
2dbdd2e
 
 
 
 
 
d88d1e3
d80a2c7
 
 
 
5700ed3
d80a2c7
 
 
 
 
5700ed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
adcbc9f
44e9039
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cb75be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a00d06
5cb75be
 
 
 
 
 
 
 
 
 
 
 
2a00d06
 
 
 
 
5cb75be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a65465
 
 
 
 
 
5cb75be
 
 
 
 
 
 
 
 
 
d80a2c7
0f9efaa
5cb75be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8229bc2
0f9efaa
 
 
69f25b5
0f9efaa
 
 
 
69f25b5
0f9efaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d88d1e3
69f25b5
 
 
 
 
 
 
 
487757b
 
 
 
 
 
 
 
 
69f25b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8adc333
69f25b5
 
 
 
 
 
 
8adc333
 
69f25b5
8adc333
69f25b5
 
8adc333
69f25b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487757b
 
 
 
 
 
 
 
 
 
 
 
 
8adc333
 
 
 
 
 
 
 
 
 
 
 
487757b
 
 
 
 
 
 
 
 
 
 
0676790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f25b5
 
 
d88d1e3
 
69f25b5
d88d1e3
 
 
 
 
 
 
 
 
 
 
 
 
0676790
 
 
 
 
 
 
 
 
 
 
d88d1e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f25b5
 
8229bc2
d88d1e3
8229bc2
 
 
69f25b5
8229bc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80a2c7
 
 
 
 
 
 
 
 
 
 
adcbc9f
d80a2c7
 
 
2923df9
d80a2c7
 
 
e835c5f
d80a2c7
 
 
 
 
58195d3
d80a2c7
 
 
 
adcbc9f
d80a2c7
 
 
 
 
 
 
 
 
adcbc9f
2923df9
d80a2c7
2dbdd2e
22dd15a
2dbdd2e
d80a2c7
2dbdd2e
 
 
d050f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dbdd2e
 
 
 
 
 
 
 
 
 
 
 
22dd15a
d85cb0d
adcbc9f
 
d80a2c7
 
 
adcbc9f
 
d80a2c7
 
 
adcbc9f
d80a2c7
2923df9
 
 
d80a2c7
2923df9
 
e835c5f
d80a2c7
e835c5f
 
d80a2c7
 
e835c5f
2923df9
d80a2c7
 
 
 
 
 
 
 
 
 
 
0f9efaa
 
 
 
 
 
44e9039
 
 
 
 
 
8229bc2
 
 
 
 
 
d88d1e3
 
 
 
 
 
69f25b5
 
 
 
 
 
487757b
 
 
 
 
 
adcbc9f
 
 
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
# =================================================================
#
# Merged and Integrated Script for Audio/MIDI Processing and Rendering (Stereo Enhanced)
#
# This script combines two functionalities:
# 1. Transcribing audio to MIDI using two methods:
#    a) A general-purpose model (basic-pitch by Spotify).
#    b) A model specialized for solo piano (ByteDance).
#    - Includes stereo processing by splitting channels, transcribing independently, and merging MIDI.
# 2. Applying advanced transformations and re-rendering MIDI files using:
#    a) Standard SoundFonts via FluidSynth (produces stereo audio).
#    b) A custom 8-bit style synthesizer for a chiptune sound (updated for stereo output).
#
# The user can upload a Audio (e.g., WAV, MP3), or MIDI file.
# - If an audio file is uploaded, it is first transcribed to MIDI using the selected method.
# - The resulting MIDI (or an uploaded MIDI) can then be processed
#   with various effects and rendered into audio.
#
#================================================================
# Original sources:
# https://huggingface.co/spaces/asigalov61/ByteDance-Solo-Piano-Audio-to-MIDI-Transcription
# https://huggingface.co/spaces/asigalov61/Advanced-MIDI-Renderer
#================================================================
# Packages:
#
#   sudo apt install fluidsynth
#
# =================================================================
# Requirements:
#
#   pip install gradio torch pytz numpy scipy matplotlib networkx scikit-learn
#   pip install piano_transcription_inference huggingface_hub
#   pip install basic-pitch pretty_midi librosa soundfile
#
# =================================================================
# Core modules:
#
#   git clone --depth 1 https://github.com/asigalov61/tegridy-tools
#
# =================================================================

import io
import os
import hashlib
import time as reqtime
import copy
import random
import shutil
import librosa
import pyloudnorm as pyln
import soundfile as sf
from mutagen.flac import FLAC

import torch
import ffmpeg
import gradio as gr
from dataclasses import dataclass, fields # ADDED for the parameter object

# --- Imports for Vocal Separation ---
import torchaudio
from demucs.apply import apply_model
from demucs.pretrained import get_model
from demucs.audio import convert_audio
from audio_separator.separator import Separator

from src.piano_transcription.utils import initialize_app
from piano_transcription_inference  import PianoTranscription, utilities, sample_rate as transcription_sample_rate

# --- Import core transcription and MIDI processing libraries ---
from src import TMIDIX, TPLOTS
from src import MIDI
from src.midi_to_colab_audio import midi_to_colab_audio

# --- Imports for General Purpose Transcription (basic-pitch) ---
import basic_pitch
from basic_pitch.inference import predict
from basic_pitch import ICASSP_2022_MODEL_PATH

# --- Imports for 8-bit Synthesizer & MIDI Merging ---
import pretty_midi
import numpy as np
from scipy import signal

# =================================================================================================
# === Hugging Face SoundFont Downloader ===
# =================================================================================================
from huggingface_hub import hf_hub_download
import glob

# --- Define a constant for the 8-bit synthesizer option ---
SYNTH_8_BIT_LABEL = "None (8-bit Synthesizer)"


# =================================================================================================
# === Central Parameter Object ===
# =================================================================================================

@dataclass
class AppParameters:
    """A dataclass to hold all configurable parameters for the application."""
    # This provides type safety and autocomplete, preventing typos from string keys.
    
    # Input files (not part of the settings panel)
    input_file: str = None
    batch_input_files: list = None

    # Global Settings
    s8bit_preset_selector: str = "Custom"
    separate_vocals: bool = False
    separation_model: str = "Demucs (4-stem)"
    
    # --- Advanced Separation and Merging Controls ---
    enable_advanced_separation: bool = False # Controls visibility of advanced options
    separate_drums: bool = True
    separate_bass: bool = True
    separate_other: bool = True
    
    transcribe_vocals: bool = False
    transcribe_drums: bool = False
    transcribe_bass: bool = False
    transcribe_other_or_accompaniment: bool = True # Default to transcribe 'other' as it's most common
    
    merge_vocals_to_render: bool = False
    merge_drums_to_render: bool = False
    merge_bass_to_render: bool = False
    merge_other_or_accompaniment: bool = False

    enable_stereo_processing: bool = False
    transcription_method: str = "General Purpose"
    basic_pitch_preset_selector: str = "Default (Balanced)"
    
    # Basic Pitch Settings
    onset_threshold: float = 0.5
    frame_threshold: float = 0.3
    minimum_note_length: int = 128
    minimum_frequency: float = 60.0
    maximum_frequency: float = 4000.0
    infer_onsets: bool = True
    melodia_trick: bool = True
    multiple_pitch_bends: bool = False
    
    # Render Settings
    render_type: str = "Render as-is"
    soundfont_bank: str = "None (8-bit Synthesizer)"
    render_sample_rate: str = "44100"
    render_with_sustains: bool = True
    merge_misaligned_notes: int = -1
    custom_render_patch: int = -1
    render_align: str = "Do not align"
    render_transpose_value: int = 0
    render_transpose_to_C4: bool = False
    render_output_as_solo_piano: bool = False
    render_remove_drums: bool = False

    # 8-bit Synthesizer Settings
    s8bit_waveform_type: str = 'Square'
    s8bit_pulse_width: float = 0.5
    s8bit_envelope_type: str = 'Plucky (AD Envelope)'
    s8bit_decay_time_s: float = 0.1
    s8bit_vibrato_rate: float = 5.0
    s8bit_vibrato_depth: float = 0.0
    s8bit_bass_boost_level: float = 0.0
    s8bit_smooth_notes_level: float = 0.0
    s8bit_continuous_vibrato_level: float = 0.0
    s8bit_noise_level: float = 0.0
    s8bit_distortion_level: float = 0.0
    s8bit_fm_modulation_depth: float = 0.0
    s8bit_fm_modulation_rate: float = 0.0
    s8bit_adaptive_decay: bool = False
    s8bit_echo_sustain: bool = False
    s8bit_echo_rate_hz: float = 5.0
    s8bit_echo_decay_factor: float = 0.6
    s8bit_echo_trigger_threshold: float = 2.5
    
    # --- Anti-Aliasing & Quality Parameters ---
    s8bit_enable_anti_aliasing: bool = True               # Main toggle for all new quality features
    s8bit_use_additive_synthesis: bool = False            # High-quality but CPU-intensive waveform generation
    s8bit_edge_smoothing_ms: float = 0.5                  # Mild smoothing for standard waveforms (0 to disable)
    s8bit_noise_lowpass_hz: float = 9000.0                # Lowpass filter frequency for noise
    s8bit_harmonic_lowpass_factor: float = 12.0           # Multiplier for frequency-dependent lowpass filter
    s8bit_final_gain: float = 0.8                         # Final gain/limiter level to prevent clipping
    s8bit_bass_boost_cutoff_hz: float = 200.0             # Parameter for Intelligent Bass Boost

    # --- MIDI Pre-processing to Reduce Harshness ---
    s8bit_enable_midi_preprocessing: bool = True       # Master switch for this feature
    s8bit_high_pitch_threshold: int = 84               # Pitch (C6) above which velocity is scaled
    s8bit_high_pitch_velocity_scale: float = 0.8       # Velocity multiplier for high notes (e.g., 80%)
    # --- Low-pitch management parameters ---
    s8bit_low_pitch_threshold: int = 36                # Low pitch threshold (C2)
    s8bit_low_pitch_velocity_scale: float = 0.9        # Low pitch velocity scale

    s8bit_chord_density_threshold: int = 4             # Min number of notes to be considered a dense chord
    s8bit_chord_velocity_threshold: int = 100          # Min average velocity for a chord to be tamed
    s8bit_chord_velocity_scale: float = 0.75           # Velocity multiplier for loud, dense chords

    # --- Arpeggiator Parameters ---
    s8bit_enable_arpeggiator: bool = False               # Master switch for the arpeggiator
    s8bit_arpeggio_target: str = "Accompaniment Only"    # Target selection for the arpeggiator
    s8bit_arpeggio_velocity_scale: float = 0.7           # Velocity multiplier for arpeggiated notes (0.0 to 1.0)
    s8bit_arpeggio_density: float = 0.5                  # Density factor for rhythmic patterns (0.0 to 1.0)
    s8bit_arpeggio_rhythm: str = "Classic Upbeat (8th)"  # Rhythmic pattern for arpeggiation
    s8bit_arpeggio_pattern: str = "Up"                   # Pattern of the arpeggio (e.g., Up, Down, UpDown)
    s8bit_arpeggio_octave_range: int = 1                 # How many octaves the pattern spans
    s8bit_arpeggio_panning: str = "Stereo"               # Panning mode for arpeggiated notes (Stereo, Left, Right, Center)

    # --- MIDI Delay/Echo Effect Parameters ---
    s8bit_enable_delay: bool = False                   # Master switch for the delay effect
    s8bit_delay_on_melody_only: bool = True            # Apply delay only to the lead melody
    s8bit_delay_division: str = "Dotted 8th Note"
    s8bit_delay_feedback: float = 0.5                  # Velocity scale for each subsequent echo (50%)
    s8bit_delay_repeats: int = 3                       # Number of echoes to generate
    # --- NEW: Low-End Management for Delay ---
    s8bit_delay_highpass_cutoff_hz: int = 100          # High-pass filter frequency for delay echoes (removes low-end rumble from echoes)
    s8bit_delay_bass_pitch_shift: int = 0              # Pitch shift (in semitones) applied to low notes in delay echoes
    # --- High-End Management for Delay ---
    s8bit_delay_lowpass_cutoff_hz: int = 5000          # Lowpass filter frequency for delay echoes (removes harsh high frequencies from echoes)
    s8bit_delay_treble_pitch_shift: int = 0            # Pitch shift (in semitones) applied to high notes in delay echoes

# =================================================================================================
# === Helper Functions ===
# =================================================================================================

def analyze_audio_for_adaptive_params(audio_data: np.ndarray, sample_rate: int):
    """
    Analyzes raw audio data to dynamically determine optimal parameters for basic-pitch.
    
    Args:
        audio_data: The audio signal as a NumPy array (can be stereo).
        sample_rate: The sample rate of the audio.
        
    Returns:
        A dictionary of recommended parameters for basic_pitch.
    """
    print("  - Running adaptive analysis on audio to determine optimal transcription parameters...")
    
    # Ensure audio is mono for most feature extractions
    if audio_data.ndim > 1:
        y_mono = librosa.to_mono(audio_data)
    else:
        y_mono = audio_data

    params = {}

    # 1. Tempo detection with enhanced stability
    try:
        tempo_info = librosa.beat.tempo(y=y_mono, sr=sample_rate, aggregate=np.median)
        
        # Ensure BPM is a scalar float
        bpm = float(np.median(tempo_info))
        
        if bpm <= 0 or np.isnan(bpm):
            raise ValueError("Invalid BPM detected")
        
        # A 64th note is a reasonable shortest note length for most music
        # Duration of a beat (quarter note) in seconds = 60 / BPM
        # Duration of a 64th note = (60 / BPM) / 16
        min_len_s = (60.0 / bpm) / 16.0
        # basic-pitch expects milliseconds
        params['minimum_note_length'] = max(20, int(min_len_s * 1000))
        print(f"    - Detected BPM (median): {bpm:.1f} -> minimum_note_length: {params['minimum_note_length']}ms")
    except Exception as e:
        print(f"    - BPM detection failed, using default minimum_note_length. Error: {e}")

    # 2. Spectral analysis: centroid + rolloff for richer info
    try:
        spectral_centroid = librosa.feature.spectral_centroid(y=y_mono, sr=sample_rate)[0]
        rolloff = librosa.feature.spectral_rolloff(y=y_mono, sr=sample_rate)[0]
        avg_centroid = np.mean(spectral_centroid)
        avg_rolloff = np.mean(rolloff)
        print(f"    - Spectral centroid: {avg_centroid:.1f} Hz, rolloff (85%): {avg_rolloff:.1f} Hz")
        # Simple logic: if the 'center of mass' of the spectrum is low, it's bass-heavy.
        # If it's high, it contains high-frequency content.
        if avg_centroid < 500 and avg_rolloff < 1500:
            params['minimum_frequency'] = 30
            params['maximum_frequency'] = 1200
        elif avg_centroid > 2000 or avg_rolloff > 5000: # Likely bright, high-frequency content (cymbals, flutes)
            params['minimum_frequency'] = 100
            params['maximum_frequency'] = 8000
        else:
            params['minimum_frequency'] = 50
            params['maximum_frequency'] = 4000
    except Exception as e:
        print(f"    - Spectral analysis failed, using default frequencies. Error: {e}")

    # 3. Onset threshold based on percussiveness
    try:
        y_harmonic, y_percussive = librosa.effects.hpss(y_mono)
        percussive_ratio = np.sum(y_percussive**2) / (np.sum(y_harmonic**2) + 1e-10)
        # If the percussive energy is high, we need a higher onset threshold to be stricter
        params['onset_threshold'] = 0.6 if percussive_ratio > 0.5 else 0.45
        print(f"    - Percussive ratio: {percussive_ratio:.2f} -> onset_threshold: {params['onset_threshold']}")
    except Exception as e:
        print(f"    - Percussiveness analysis failed, using default onset_threshold. Error: {e}")

    # 4. Frame threshold from RMS
    try:
        rms = librosa.feature.rms(y=y_mono)[0]
        # Use the 10th percentile of energy as a proxy for the noise floor
        noise_floor_rms = np.percentile(rms, 10)
        # Set the frame_threshold to be slightly above this noise floor
        # The scaling factor here is empirical and can be tuned
        params['frame_threshold'] = max(0.05, min(0.4, noise_floor_rms * 4))
        print(f"    - Noise floor RMS: {noise_floor_rms:.5f} -> frame_threshold: {params['frame_threshold']:.2f}")
    except Exception as e:
        print(f"    - RMS analysis failed, using default frame_threshold. Error: {e}")

    return params


def format_params_for_metadata(params: AppParameters, transcription_log: dict = None) -> str:
    """
    Formats the AppParameters object into a human-readable string
    suitable for embedding as metadata in an audio file.
    """
    import json
    # Start with a clean dictionary of the main parameters
    params_dict = copy.copy(params.__dict__)
    
    # Create a structured dictionary for the final metadata
    structured_metadata = {
        "main_settings": {},
        "transcription_log": transcription_log if transcription_log else "Not Performed",
        "synthesis_settings": {}
    }

    # Separate parameters into logical groups
    transcription_keys = [
        'transcription_method', 'basic_pitch_preset_selector', 'onset_threshold',
        'frame_threshold', 'minimum_note_length', 'minimum_frequency', 'maximum_frequency',
        'infer_onsets', 'melodia_trick', 'multiple_pitch_bends'
    ]
    
    synthesis_keys = [key for key in params_dict.keys() if key.startswith('s8bit_')]

    # Populate the structured dictionary
    for key, value in params_dict.items():
        if key not in transcription_keys and key not in synthesis_keys:
            structured_metadata["main_settings"][key] = value

    for key in synthesis_keys:
        structured_metadata["synthesis_settings"][key] = params_dict[key]

    # If transcription log is empty, we still want to record the UI settings for transcription
    if not transcription_log:
        structured_metadata["transcription_log"] = {
            "ui_settings": {key: params_dict[key] for key in transcription_keys}
        }

    # Use json.dumps for clean, well-formatted, multi-line string representation
    # indent=2 makes it look nice when read back
    return json.dumps(params_dict, indent=2)


def preprocess_midi_for_harshness(midi_data: pretty_midi.PrettyMIDI, params: AppParameters):
    """
    Analyzes and modifies a PrettyMIDI object in-place to reduce characteristics
    that can cause harshness or muddiness in simple synthesizers.
    Now includes both high and low pitch attenuation.
    
    Args:
        midi_data: The PrettyMIDI object to process.
        params: The AppParameters object containing the control thresholds.
    """
    print("Running MIDI pre-processing to reduce harshness and muddiness...")
    high_notes_tamed = 0
    low_notes_tamed = 0
    chords_tamed = 0
    
    # Rule 1 & 2: High and Low Pitch Attenuation
    for instrument in midi_data.instruments:
        for note in instrument.notes:
            # Tame very high notes to reduce harshness/aliasing
            if note.pitch > params.s8bit_high_pitch_threshold:
                note.velocity = int(note.velocity * params.s8bit_high_pitch_velocity_scale)
                if note.velocity < 1: note.velocity = 1
                high_notes_tamed += 1
            
            # Tame very low notes to reduce muddiness/rumble
            if note.pitch < params.s8bit_low_pitch_threshold:
                note.velocity = int(note.velocity * params.s8bit_low_pitch_velocity_scale)
                if note.velocity < 1: note.velocity = 1
                low_notes_tamed += 1

    if high_notes_tamed > 0:
        print(f"  - Tamed {high_notes_tamed} individual high-pitched notes.")
    if low_notes_tamed > 0:
        print(f"  - Tamed {low_notes_tamed} individual low-pitched notes.")

    # Rule 3: Chord Compression
    # This is a simplified approach: group notes by near-simultaneous start times
    all_notes = sorted([note for instrument in midi_data.instruments for note in instrument.notes], key=lambda x: x.start)

    time_window = 0.02  # 20ms window to group notes into a chord
    i = 0
    while i < len(all_notes):
        current_chord = [all_notes[i]]
        # Find other notes within the time window
        j = i + 1
        while j < len(all_notes) and (all_notes[j].start - all_notes[i].start) < time_window:
            current_chord.append(all_notes[j])
            j += 1
        
        # Analyze and potentially tame the chord
        if len(current_chord) >= params.s8bit_chord_density_threshold:
            avg_velocity = sum(n.velocity for n in current_chord) / len(current_chord)
            if avg_velocity > params.s8bit_chord_velocity_threshold:
                chords_tamed += 1
                for note in current_chord:
                    note.velocity = int(note.velocity * params.s8bit_chord_velocity_scale)
                    if note.velocity < 1: note.velocity = 1
        
        # Move index past the current chord
        i = j
        
    if chords_tamed > 0:
        print(f"  - Tamed {chords_tamed} loud, dense chords.")
        
    return midi_data # Return the modified object


def arpeggiate_midi(midi_data: pretty_midi.PrettyMIDI, params: AppParameters):
    """
    Applies a tempo-synced, rhythmic arpeggiator effect. It can generate
    various rhythmic patterns (not just continuous notes) to create a more
    musical and less "stiff" accompaniment.
    Improved rhythmic arpeggiator with dynamic density, stereo layer splitting,
    micro-randomization, and cross-beat continuity.
    
    Applies a highly configurable arpeggiator with selectable targets:
    - Accompaniment Only: The classic approach, arpeggiates harmony.
    - Melody Only: A modern approach, adds flair to the lead melody.
    - Full Mix: Applies the effect to all notes.

    Args:
        midi_data: The original PrettyMIDI object.
        params: AppParameters containing arpeggiator settings.
        
    Returns:
        A new PrettyMIDI object with arpeggiated chords.
    """
    print(f"Applying arpeggiator with target: {params.s8bit_arpeggio_target}...")
    processed_midi = copy.deepcopy(midi_data)

    # --- Step 1: Global analysis to identify lead vs. harmony notes ---
    all_notes = []
    # We need to keep track of which instrument each note belongs to
    for i, instrument in enumerate(processed_midi.instruments):
        if not instrument.is_drum:
            for note in instrument.notes:
                # Use a simple object or tuple to store note and its origin
                all_notes.append({'note': note, 'instrument_idx': i})
    
    if not all_notes:
        return processed_midi
    all_notes.sort(key=lambda x: x['note'].start)
    
    # --- Lead / Harmony separation ---
    lead_note_objects = set()
    harmony_note_objects = set()

    note_idx = 0
    while note_idx < len(all_notes):
        current_slice_start = all_notes[note_idx]['note'].start
        notes_in_slice = [item for item in all_notes[note_idx:] if (item['note'].start - current_slice_start) < 0.02]

        if not notes_in_slice:
            note_idx += 1
            continue

        notes_in_slice.sort(key=lambda x: x['note'].pitch, reverse=True)
        lead_note_objects.add(notes_in_slice[0]['note'])
        for item in notes_in_slice[1:]:
            harmony_note_objects.add(item['note'])

        note_idx += len(notes_in_slice)

    # --- Step 2: Determine which set of notes to process based on the target ---
    notes_to_arpeggiate = set()
    notes_to_keep_original = set()

    if params.s8bit_arpeggio_target == "Accompaniment Only":
        print("  - Arpeggiating harmony notes.")
        notes_to_arpeggiate = harmony_note_objects
        notes_to_keep_original = lead_note_objects
    elif params.s8bit_arpeggio_target == "Melody Only":
        print("  - Arpeggiating lead melody notes.")
        notes_to_arpeggiate = lead_note_objects
        notes_to_keep_original = harmony_note_objects
    else: # Full Mix
        print("  - Arpeggiating all non-drum notes.")
        notes_to_arpeggiate = lead_note_objects.union(harmony_note_objects)
        notes_to_keep_original = set()

    # --- Step 3: Estimate Tempo and prepare for generation ---
    try:
        bpm = midi_data.estimate_tempo()
    except:
        bpm = 120.0
    beat_duration_s = 60.0 / bpm
    
    rhythm_patterns = {
        "Continuous 16ths": [(0.0, 0.25), (0.25, 0.25), (0.5, 0.25), (0.75, 0.25)],
        "Classic Upbeat (8th)": [(0.5, 0.25), (0.75, 0.25)],
        "Pulsing 8ths": [(0.0, 0.5), (0.5, 0.5)],
        "Pulsing 4ths": [(0.0, 0.5)],
        "Galloping": [(0.0, 0.75), (0.75, 0.25)],
        "Simple Quarter Notes": [(0.0, 1.0)],
        "Triplet 8ths": [(0.0, 1/3), (1/3, 1/3), (2/3, 1/3)],
    }
    selected_rhythm = rhythm_patterns.get(params.s8bit_arpeggio_rhythm, rhythm_patterns["Classic Upbeat (8th)"])

    # --- Step 4: Rebuild instruments with the new logic ---
    for instrument in processed_midi.instruments:
        if instrument.is_drum:
            continue

        new_note_list = []
        
        # Add back all notes that are designated to be kept original for this track
        inst_notes_to_keep = [n for n in instrument.notes if n in notes_to_keep_original]
        new_note_list.extend(inst_notes_to_keep)
        
        # Process only the notes targeted for arpeggiation within this instrument
        inst_notes_to_arp = [n for n in instrument.notes if n in notes_to_arpeggiate]
        processed_arp_notes = set()

        for note1 in inst_notes_to_arp:
            if note1 in processed_arp_notes:
                continue

            # Group notes into chords from the target list.
            # For melody, each note is its own "chord".
            chord_notes = [note1]
            if params.s8bit_arpeggio_target != "Melody Only":
                chord_notes.extend([n2 for n2 in inst_notes_to_arp if n2 != note1 and n2 not in processed_arp_notes and abs(n2.start - note1.start) < 0.02])
            
            # --- Arpeggiate the identified group (which could be a single note or a chord) ---
            for n in chord_notes:
                processed_arp_notes.add(n)
            
            chord_start_time = min(n.start for n in chord_notes)
            chord_end_time = max(n.end for n in chord_notes)
            avg_velocity = int(np.mean([n.velocity for n in chord_notes]))
            
            # --- Apply an exponential curve to the velocity scale ---
            # This makes the slider much more sensitive at lower values,
            # allowing for true background-level arpeggios.
            scale = params.s8bit_arpeggio_velocity_scale
            # We use a power of 2 here, but could be tuned (e.g., 1.5, 2.5, 3.0)
            # A higher power makes the attenuation at low scale values even more aggressive.
            final_velocity_base = int(avg_velocity * (scale ** 2.5))
            
            if final_velocity_base < 1:
                final_velocity_base = 1

            # --- Pitch Pattern Generation ---
            base_pitches = sorted([n.pitch for n in chord_notes])
            
            # For "Melody Only" mode, auto-generate a simple chord from the single melody note
            if params.s8bit_arpeggio_target == "Melody Only" and len(base_pitches) == 1:
                # This is a very simple major chord generator, can be expanded later
                # Auto-generate a major chord from the single melody note
                root = base_pitches[0]
                base_pitches = [root, root + 4, root + 7]

            pattern = []
            for octave in range(params.s8bit_arpeggio_octave_range):
                octave_pitches = [p + (12 * octave) for p in base_pitches]
                if params.s8bit_arpeggio_pattern == "Up":
                    pattern.extend(octave_pitches)
                elif params.s8bit_arpeggio_pattern == "Down":
                    pattern.extend(reversed(octave_pitches))
                elif params.s8bit_arpeggio_pattern == "UpDown":
                    pattern.extend(octave_pitches)
                    if len(octave_pitches) > 2:
                        pattern.extend(reversed(octave_pitches[1:-1]))
            
            if not pattern:
                continue
            
            # --- Rhythmic Note Generation ---
            note_base_density = getattr(params, "s8bit_arpeggio_density", 0.6)
            chord_duration = chord_end_time - chord_start_time
            note_duration_factor = min(1.0, chord_duration / (2 * beat_duration_s)) if beat_duration_s > 0 else 1.0
            note_density_factor = note_base_density * note_duration_factor
            
            current_beat = chord_start_time / beat_duration_s if beat_duration_s > 0 else 0
            current_time = chord_start_time
            pattern_index = 0
            while current_time < chord_end_time:
                # Lay down the rhythmic pattern for the current beat
                current_beat_start_time = np.floor(current_beat) * beat_duration_s
                
                for start_offset, duration_beats in selected_rhythm:
                    note_start_time = current_beat_start_time + (start_offset * beat_duration_s)
                    note_duration_s = duration_beats * beat_duration_s * note_density_factor
                    
                    # Ensure the note does not exceed the chord's total duration
                    if note_start_time >= chord_end_time:
                        break

                    pitch = pattern[pattern_index % len(pattern)]
                    
                    # Micro-randomization
                    rand_offset = random.uniform(-0.01, 0.01)  # ±10ms
                    final_velocity = max(1, min(127, final_velocity_base + random.randint(-5, 5)))

                    new_note = pretty_midi.Note(
                        velocity=final_velocity,
                        pitch=pitch,
                        start=max(0.0, note_start_time + rand_offset),
                        end=min(chord_end_time, note_start_time + note_duration_s)
                    )
                    new_note_list.append(new_note)
                    pattern_index += 1
                
                current_beat += 1.0
                current_time = current_beat * beat_duration_s if beat_duration_s > 0 else float('inf')
        
        # Replace the instrument's original note list with the new, processed one
        instrument.notes = new_note_list

    print("Targeted arpeggiator finished.")
    return processed_midi


def create_delay_effect(midi_data: pretty_midi.PrettyMIDI, params: AppParameters):
    """
    Creates a delay/echo effect by duplicating notes with delayed start times
    and scaled velocities. Can be configured to apply only to the lead melody.
    based on the MIDI's estimated BPM and the user's selected musical division.
    """
    print("Applying tempo-synced MIDI delay/echo effect...")
    # Work on a deep copy to ensure the original MIDI object is not mutated.
    processed_midi = copy.deepcopy(midi_data)
    
    # --- Step 1: Estimate Tempo and Calculate Delay Time in Seconds ---
    try:
        bpm = midi_data.estimate_tempo()
    except:
        bpm = 120.0
    print(f"  - Delay using tempo: {bpm:.2f} BPM")
    
    # This map defines the duration of each note division as a multiplier of a quarter note (a beat).
    division_map = {
        "Quarter Note": 1.0,
        "Dotted 8th Note": 0.75,
        "8th Note": 0.5,
        "Triplet 8th Note": 1.0 / 3.0,
        "16th Note": 0.25
    }
    beat_duration_s = 60.0 / bpm
    division_multiplier = division_map.get(params.s8bit_delay_division, 0.75)
    delay_time_s = beat_duration_s * division_multiplier
    
    print(f"  - Delay set to {params.s8bit_delay_division}, calculated time: {delay_time_s:.3f}s")
    
    # --- Step 2: Identify the notes that should receive the echo effect ---
    notes_to_echo = []
    
    if params.s8bit_delay_on_melody_only:
        print("  - Delay will be applied to lead melody notes only.")
        all_notes = [note for inst in processed_midi.instruments if not inst.is_drum for note in inst.notes]
        all_notes.sort(key=lambda n: n.start)
        
        note_idx = 0
        while note_idx < len(all_notes):
            current_slice_start = all_notes[note_idx].start
            notes_in_slice = [n for n in all_notes[note_idx:] if (n.start - current_slice_start) < 0.02]
            if not notes_in_slice:
                note_idx += 1
                continue
            
            # The highest note in the slice is considered the lead note
            notes_in_slice.sort(key=lambda n: n.pitch, reverse=True)
            notes_to_echo.append(notes_in_slice[0])
            note_idx += len(notes_in_slice)
    else:
        print("  - Delay will be applied to all non-drum notes.")
        notes_to_echo = [note for inst in processed_midi.instruments if not inst.is_drum for note in inst.notes]

    if not notes_to_echo:
        print("  - No notes found to apply delay to. Skipping.")
        return processed_midi

    # --- Step 3: Generate echo notes with optional octave shift using the calculated delay time ---
    echo_notes = []
    bass_note_threshold = 48 # MIDI note for C3
    treble_note_threshold = 84 # MIDI note for C6

    for i in range(1, params.s8bit_delay_repeats + 1):
        for original_note in notes_to_echo:
            # Create a copy of the note for the echo
            echo_note = copy.copy(original_note)

            # --- Octave Shift Logic for both Bass and Treble ---
            if params.s8bit_delay_bass_pitch_shift and original_note.pitch < bass_note_threshold:
                echo_note.pitch += params.s8bit_delay_bass_pitch_shift
            elif params.s8bit_delay_treble_pitch_shift and original_note.pitch > treble_note_threshold:
                echo_note.pitch += params.s8bit_delay_treble_pitch_shift
            
            # Use the tempo-synced time and velocity
            time_offset = i * delay_time_s
            echo_note.start += time_offset
            echo_note.end += time_offset
            echo_note.velocity = int(echo_note.velocity * (params.s8bit_delay_feedback ** i))

            # Only add the echo if its velocity is still audible
            if echo_note.velocity > 1:
                echo_notes.append(echo_note)

    # --- Step 4: Add the echo notes to a new, dedicated instrument track ---
    if echo_notes:
        # Inherit the program from the first non-drum instrument
        # This ensures the echo has the same timbral character as the original sound,
        # preventing perceived pitch shifts caused by different harmonic structures.
        base_program = 0 # Default to piano if no instruments are found
        for inst in midi_data.instruments:
            if not inst.is_drum:
                base_program = inst.program
                break # Use the program of the first non-drum track we find
        
        echo_instrument = pretty_midi.Instrument(program=base_program, is_drum=False, name="Echo Layer")
        echo_instrument.notes.extend(echo_notes)
        processed_midi.instruments.append(echo_instrument)
        print(f"  - Generated {len(echo_notes)} tempo-synced echo notes on a new track with program {base_program}.")

    return processed_midi


def butter_highpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = signal.butter(order, normal_cutoff, btype='high', analog=False)
    return b, a

def apply_butter_highpass_filter(data, cutoff, fs, order=5):
    """Applies a Butterworth highpass filter to a stereo audio signal."""
    if cutoff <= 0:
        return data
    b, a = butter_highpass(cutoff, fs, order=order)
    # Apply filter to each channel independently
    filtered_data = np.zeros_like(data)
    for channel in range(data.shape[1]):
        filtered_data[:, channel] = signal.lfilter(b, a, data[:, channel])
    return filtered_data


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = signal.butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def apply_butter_lowpass_filter(data, cutoff, fs, order=5):
    """Applies a Butterworth lowpass filter to a stereo audio signal."""
    # A cutoff at or above Nyquist frequency is pointless
    if cutoff >= fs / 2:
        return data
    b, a = butter_lowpass(cutoff, fs, order=order)
    filtered_data = np.zeros_like(data)
    for channel in range(data.shape[1]):
        filtered_data[:, channel] = signal.lfilter(b, a, data[:, channel])
    return filtered_data


def one_pole_lowpass(x, cutoff_hz, fs):
    """Simple one-pole lowpass filter (causal), stable and cheap."""
    if cutoff_hz <= 0 or cutoff_hz >= fs/2:
        return x
    dt = 1.0 / fs
    rc = 1.0 / (2 * np.pi * cutoff_hz)
    alpha = dt / (rc + dt)
    y = np.empty_like(x)
    y[0] = alpha * x[0]
    for n in range(1, len(x)):
        y[n] = y[n-1] + alpha * (x[n] - y[n-1])
    return y

def smooth_square_or_saw(note_waveform, fs, smooth_ms=0.6):
    """Short triangular smoothing to soften sharp edges (simple anti-alias-ish)."""
    if smooth_ms <= 0:
        return note_waveform
    kernel_len = max(1, int(fs * (smooth_ms/1000.0)))
    # triangular kernel
    k = np.convolve(np.ones(kernel_len), np.ones(kernel_len))  # triangle shape length=2*kernel_len-1
    k = k / k.sum()
    # pad and convolve
    y = np.convolve(note_waveform, k, mode='same')
    return y

def additive_bandlimited_waveform(wave_type, freq, t, fs, max_harmonics_cap=200):
    """
    Simple additive band-limited generator:
      - saw: sum_{n=1..N} sin(2π n f t)/n
      - square: sum odd harmonics sin(2π n f t)/n
    N chosen so n*f < fs/2.
    This is heavier but yields much less aliasing.
    """
    nyq = fs / 2.0
    max_n = int(nyq // freq)
    if max_n < 1:
        return np.zeros_like(t)
    max_n = min(max_n, max_harmonics_cap)
    y = np.zeros_like(t)
    if wave_type == 'Sawtooth':
        # saw via Fourier series
        for n in range(1, max_n + 1):
            y += np.sin(2*np.pi * n * freq * t) / n
        # normalization to [-1,1]
        y = - (2/np.pi) * y
    else:  # square
        n = 1
        while n <= max_n:
            y += np.sin(2*np.pi * n * freq * t) / n
            n += 2
        y = (4/np.pi) * y
    # clip tiny numerical overshoot
    y = np.clip(y, -1.0, 1.0)
    return y

def safe_tanh_distortion(x, strength):
    """Milder soft clipping: scale then tanh, with adjustable drive."""
    # make strength between 0..1 typical; map to drive factor
    drive = 1.0 + strength * 4.0
    return np.tanh(x * drive) / np.tanh(drive)

def prepare_soundfonts():
    """
    Ensures a default set of SoundFonts are downloaded, then scans the 'src/sf2'
    directory recursively for all .sf2 files.
    Returns a dictionary mapping a user-friendly name to its full file path, with
    default soundfonts listed first in their specified order.

    Downloads soundfont files from the specified Hugging Face Space repository
    to a local 'src/sf2' directory if they don't already exist.
    Returns a list of local paths to the soundfont files.
    """
    SF2_REPO_ID = "asigalov61/Advanced-MIDI-Renderer"
    SF2_DIR = "src/sf2"
    # This list is now just for ensuring default files exist
    # {"Super GM": 0, "Orpheus GM": 1, "Live HQ GM": 2, "Nice Strings + Orchestra": 3, "Real Choir": 4, "Super Game Boy": 5, "Proto Square": 6}
    DEFAULT_SF2_FILENAMES = [
        "SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2",
        "Orpheus_18.06.2020.sf2",
        "Live HQ Natural SoundFont GM.sf2",
        "Nice-Strings-PlusOrchestra-v1.6.sf2",
        "KBH-Real-Choir-V2.5.sf2",
        "SuperGameBoy.sf2",
        "ProtoSquare.sf2"
    ]

    # Create the target directory if it doesn't exist
    os.makedirs(SF2_DIR, exist_ok=True)
    
    # --- Step 1: Ensure default SoundFonts are available ---
    print("Checking for SoundFont files...")
    for filename in DEFAULT_SF2_FILENAMES:
        local_path = os.path.join(SF2_DIR, filename)
        
        # Check if the file already exists locally to avoid re-downloading
        if not os.path.exists(local_path):
            print(f"Downloading '{filename}' from Hugging Face Hub...")
            try:
                # Use hf_hub_download to get the file
                # It will be downloaded to the specified local directory
                hf_hub_download(
                    repo_id=SF2_REPO_ID,
                    repo_type='space',  # Specify that the repository is a Space
                    filename=f"{filename}",  # The path to the file within the repository
                    local_dir=SF2_DIR,
                    # local_dir_use_symlinks=False  # Copy file to the dir for a clean folder structure
                )
                print(f"'{filename}' downloaded successfully.")
            except Exception as e:
                print(f"Error downloading {filename}: {e}")
                # If download fails, we might not be able to use this soundfont

    # --- Step 2: Scan the entire directory for all .sf2 files ---
    print(f"Scanning '{SF2_DIR}' for all .sf2 files...")
    all_sfs_map = {}
    # Use glob with recursive=True to find all .sf2 files in subdirectories
    search_pattern = os.path.join(SF2_DIR, '**', '*.sf2')
    for full_path in glob.glob(search_pattern, recursive=True):
        # Create a user-friendly display name, including subfolder if it exists
        relative_path = os.path.relpath(full_path, SF2_DIR)
        display_name = os.path.splitext(relative_path)[0].replace("\\", "/") # Use forward slashes for consistency
        all_sfs_map[display_name] = full_path
        
    # --- Step 3: Create the final ordered dictionary based on priority ---
    ordered_soundfont_map = {}

    # Create display names for default files (filename without extension)
    default_display_names = [os.path.splitext(f)[0] for f in DEFAULT_SF2_FILENAMES]
    
    # Separate other files from the default ones
    other_display_names = [name for name in all_sfs_map.keys() if name not in default_display_names]
    other_display_names.sort() # Sort the rest alphabetically

    # Add default soundfonts first, maintaining the order from DEFAULT_SF2_FILENAMES
    for name in default_display_names:
        if name in all_sfs_map: # Check if the file was actually found by the scanner
            ordered_soundfont_map[name] = all_sfs_map[name]
            
    # Add all other soundfonts after the default ones
    for name in other_display_names:
        ordered_soundfont_map[name] = all_sfs_map[name]

    return ordered_soundfont_map

# =================================================================================================
# === 8-bit Style Synthesizer (Stereo Enabled) ===
# =================================================================================================
def synthesize_8bit_style(*, midi_data: pretty_midi.PrettyMIDI,  fs: int, params: AppParameters, progress: gr.Progress = None):
    """
    Synthesizes an 8-bit style audio waveform from a PrettyMIDI object.
    This function generates waveforms manually instead of using a synthesizer like FluidSynth.
    Includes an optional sub-octave bass booster with adjustable level.
    Instruments are panned based on their order in the MIDI file.
    Instrument 1 -> Left, Instrument 2 -> Right.
    Now supports graded levels for smoothing and vibrato continuity.
    This enhanced version includes advanced anti-aliasing and quality features to produce a cleaner, less harsh sound.
    """
    total_duration = midi_data.get_end_time()
    # Initialize a stereo waveform buffer (2 channels: Left, Right)
    waveform = np.zeros((2, int(total_duration * fs) + fs))
    
    num_instruments = len(midi_data.instruments)

    # Phase tracking: main oscillator phase for each instrument
    osc_phase = {}
    # Vibrato phase tracking
    vibrato_phase = 0.0
    
    # Retrieve anti-aliasing settings, using getattr for backward compatibility
    use_aa = getattr(params, 's8bit_enable_anti_aliasing', False)

    # --- Move progress tracking to the note level ---
    # 1. First, collect all notes from all instruments into a single list.
    all_notes_with_instrument_info = []
    for i, instrument in enumerate(midi_data.instruments):
        # --- Panning Logic (with override for arpeggiator layer) ---
        panning_override = getattr(params, '_temp_panning_override', None)
        
        if panning_override:
            if panning_override == "Center":
                pan_l, pan_r = 0.707, 0.707
            elif panning_override == "Left":
                pan_l, pan_r = 1.0, 0.0
            elif panning_override == "Right":
                pan_l, pan_r = 0.0, 1.0
            else: # Default to Stereo for the arp layer
                # Wide stereo: pan instruments alternating left and right
                if i % 2 == 0:
                    pan_l, pan_r = 1.0, 0.0 # Even instruments to the left
                else:
                    pan_l, pan_r = 0.0, 1.0          # Odd instruments to the right
        else: # Standard panning logic for the main layer
            # --- Panning Logic ---
            # Default to center-panned mono
            pan_l, pan_r = 0.707, 0.707
            if num_instruments == 2:
                if i == 0:  # First instrument panned left
                    pan_l, pan_r = 1.0, 0.0
                elif i == 1:  # Second instrument panned right
                    pan_l, pan_r = 0.0, 1.0
            elif num_instruments > 2:
                if i == 0:  # Left
                    pan_l, pan_r = 1.0, 0.0
                elif i == 1: # Right
                    pan_l, pan_r = 0.0, 1.0
            # Other instruments remain centered
        
        # Store each note along with its parent instrument index and panning info
        for note in instrument.notes:
            all_notes_with_instrument_info.append({'note': note, 'instrument_index': i, 'pan_l': pan_l, 'pan_r': pan_r})
        
        # Initialize oscillator phase for each instrument
        osc_phase[i] = 0.0  # Independent phase tracking for each instrument

    # 2. Create an iterable for the main note-processing loop.
    notes_iterable = all_notes_with_instrument_info
    total_notes = len(notes_iterable)

    # 3. Wrap this new iterable with tqdm if a progress object is available.
    if progress and hasattr(progress, 'tqdm'):
        notes_iterable = progress.tqdm(
            notes_iterable, 
            desc="Synthesizing Notes...",
            total=total_notes
        )

    # 4. The main loop now iterates over individual notes, not instruments.
    for item in notes_iterable:
        note = item['note']
        i = item['instrument_index']
        pan_l = item['pan_l']
        pan_r = item['pan_r']

        freq = pretty_midi.note_number_to_hz(note.pitch)
        note_duration = note.end - note.start
        num_samples = int(note_duration * fs)
        if num_samples <= 0:
            continue

        t = np.arange(num_samples) / fs

        # --- Graded Continuous Vibrato ---
        # This now interpolates between a fully reset vibrato and a fully continuous one.
        # Use accumulated phase to avoid vibrato reset per note
        vib_phase_inc = 2 * np.pi * params.s8bit_vibrato_rate / fs
        per_note_vib_phase = 2 * np.pi * params.s8bit_vibrato_rate * t
        continuous_vib_phase = vibrato_phase + np.arange(num_samples) * vib_phase_inc
        
        # Weighted average of the two phase types
        final_vib_phase = (
            per_note_vib_phase * (1 - params.s8bit_continuous_vibrato_level) + 
            continuous_vib_phase * params.s8bit_continuous_vibrato_level
        )
        vibrato_lfo = params.s8bit_vibrato_depth * np.sin(final_vib_phase)
        
        # Update the global vibrato phase for the next note
        if num_samples > 0:
            vibrato_phase = (continuous_vib_phase[-1] + vib_phase_inc) % (2 * np.pi)

        # --- Waveform Generation with FM ---
        fm_lfo = params.s8bit_fm_modulation_depth * np.sin(2 * np.pi * params.s8bit_fm_modulation_rate * t)
        modulated_freq = freq * (1 + fm_lfo)

        # --- Waveform Generation (with Anti-Aliasing options) ---
        use_additive = use_aa and getattr(params, 's8bit_use_additive_synthesis', False)
        if use_additive and params.s8bit_waveform_type in ['Square', 'Sawtooth']:
            note_waveform = additive_bandlimited_waveform(params.s8bit_waveform_type, freq, t, fs)
        else:
            # --- Waveform Generation (Main Oscillator with phase continuity) ---
            phase_inc = 2 * np.pi * (modulated_freq + vibrato_lfo) / fs
            phase = osc_phase[i] + np.cumsum(phase_inc)
            if num_samples > 0:
                osc_phase[i] = phase[-1] % (2 * np.pi)  # Store last phase
            
            if params.s8bit_waveform_type == 'Square':
                note_waveform = signal.square(phase, duty=params.s8bit_pulse_width)
            elif params.s8bit_waveform_type == 'Sawtooth':
                note_waveform = signal.sawtooth(phase)
            else: # Triangle (less prone to aliasing)
                note_waveform = signal.sawtooth(phase, width=0.5)

            if use_aa and params.s8bit_waveform_type in ['Square', 'Sawtooth']:
                edge_smooth_ms = getattr(params, 's8bit_edge_smoothing_ms', 0.5)
                note_waveform = smooth_square_or_saw(note_waveform, fs, smooth_ms=edge_smooth_ms)

        # --- Intelligent Bass Boost (Frequency-Dependent) ---
        if params.s8bit_bass_boost_level > 0:
            # --- Step 1: Calculate the dynamic boost level for this specific note ---
            cutoff_hz = getattr(params, 's8bit_bass_boost_cutoff_hz', 200.0)
            
            # Create a smooth fade-out curve for the boost effect.
            # The effect is at 100% strength at the cutoff frequency,
            # and fades to 0% at half the cutoff frequency.
            # `clip` ensures the value is between 0 and 1.
            dynamic_boost_scale = np.clip((freq - (cutoff_hz / 2)) / (cutoff_hz / 2), 0, 1)
            
            # The final boost level is the user's setting multiplied by our dynamic scale.
            final_boost_level = params.s8bit_bass_boost_level * dynamic_boost_scale
            
            # --- Step 2: Apply the boost only if it's still audible ---
            if final_boost_level > 0.01: # A small threshold to avoid unnecessary computation
                bass_freq = freq / 2.0
                # Only add bass if the frequency is reasonably audible
                if bass_freq > 20:
                    # Bass uses a simple square wave, no vibrato, for stability
                    bass_phase_inc = 2 * np.pi * bass_freq / fs
                    bass_phase = np.cumsum(np.full(num_samples, bass_phase_inc))
                    bass_sub_waveform = signal.square(bass_phase, duty=0.5)
                    
                    # The ducking amount is now also dynamic.
                    main_level = 1.0 - (0.5 * final_boost_level)
                    note_waveform = (note_waveform * main_level) + (bass_sub_waveform * final_boost_level)
                
        # --- Noise & Distortion (Reordered and Improved) ---
        if params.s8bit_noise_level > 0:
            raw_noise = np.random.uniform(-1, 1, num_samples) * params.s8bit_noise_level
            if use_aa:
                noise_cutoff = getattr(params, 's8bit_noise_lowpass_hz', 9000.0)
                raw_noise = one_pole_lowpass(raw_noise, cutoff_hz=noise_cutoff, fs=fs)
            note_waveform += raw_noise
        
        # --- Distortion (Wave Shaping) ---
        if params.s8bit_distortion_level > 0:
            if use_aa:
                note_waveform = safe_tanh_distortion(note_waveform, params.s8bit_distortion_level)
            else: # Original harsher distortion
                # Using a tanh function for a smoother, "warmer" distortion
                note_waveform = np.tanh(note_waveform * (1 + params.s8bit_distortion_level * 5))

        # --- ADSR Envelope Generation (with improvements) ---
        start_amp = note.velocity / 127.0
        envelope = np.zeros(num_samples)
        
        min_attack_s = 0.001 # 1 ms minimum attack to prevent clicks
        if params.s8bit_envelope_type == 'Plucky (AD Envelope)':
            attack_samples = max(int(min_attack_s * fs), min(int(0.005 * fs), num_samples))
            
            # --- Adaptive Decay Logic ---
            # This ensures short staccato notes have the same initial decay rate
            # as long notes, fixing the perceived low volume issue.
            if params.s8bit_adaptive_decay:
                # 1. Calculate the "ideal" number of decay samples based on the user's setting.
                ideal_decay_samples = int(params.s8bit_decay_time_s * fs)
                if ideal_decay_samples <= 0:
                    ideal_decay_samples = 1 # Avoid division by zero.

                # 2. Create the full, "ideal" decay curve from peak to zero.
                ideal_decay_curve = np.linspace(start_amp, 0, ideal_decay_samples)

                # 3. Determine how many decay samples can actually fit in this note's duration.
                actual_decay_samples = num_samples - attack_samples

                if actual_decay_samples > 0:
                    # 4. Take the initial part of the ideal curve, sized to fit the note.
                    num_samples_to_take = min(len(ideal_decay_curve), actual_decay_samples)
                    
                    # Apply the attack portion.
                    envelope[:attack_samples] = np.linspace(0, start_amp, attack_samples)
                    # Apply the truncated decay curve.
                    envelope[attack_samples : attack_samples + num_samples_to_take] = ideal_decay_curve[:num_samples_to_take]

            # --- Original Decay Logic (Fallback) ---
            else:
                decay_samples = min(int(params.s8bit_decay_time_s * fs), num_samples - attack_samples)
                envelope[:attack_samples] = np.linspace(0, start_amp, attack_samples)
                if decay_samples > 0:
                    envelope[attack_samples:attack_samples+decay_samples] = np.linspace(start_amp, 0, decay_samples)

        else: # Sustained
            envelope = np.linspace(start_amp, 0, num_samples)
            if use_aa and num_samples > 20: # Add a tiny release fade to prevent clicks
                release_samples = int(min(0.005*fs, num_samples // 10))
                if release_samples > 0:
                    envelope[-release_samples:] *= np.linspace(1.0, 0.0, release_samples)

        # --- Hybrid Note Smoothing (Proportional with an Absolute Cap) ---
        # This improved logic calculates the fade duration as a percentage of the note's
        # length but caps it at a fixed maximum duration. This provides the best of both worlds:
        # it preserves volume on short notes while ensuring long notes have a crisp attack.
        if params.s8bit_smooth_notes_level > 0 and num_samples > 10:
            # 1. Define the maximum allowable fade time in seconds (e.g., 30ms).
            #    This prevents fades from becoming too long on sustained notes.
            max_fade_duration_s = 0.03

            # 2. Calculate the proportional fade length based on the note's duration.
            #    At level 1.0, this is 10% of the note's start and 10% of its end.
            fade_percentage = 0.1 * params.s8bit_smooth_notes_level
            proportional_fade_samples = int(num_samples * fade_percentage)

            # 3. Calculate the absolute maximum fade length in samples.
            absolute_max_fade_samples = int(fs * max_fade_duration_s)

            # 4. The final fade_samples is the SMALLEST of the three constraints:
            #    a) The proportional length.
            #    b) The absolute maximum length.
            #    c) Half the note's total length (to prevent overlap).
            fade_samples = min(proportional_fade_samples, absolute_max_fade_samples, num_samples // 2)

            if fade_samples > 0:
                # Apply a fade-in to the attack portion of the envelope.
                envelope[:fade_samples] *= np.linspace(0.5, 1.0, fade_samples)
                # Apply a fade-out to the tail portion of the envelope.
                envelope[-fade_samples:] *= np.linspace(1.0, 0.0, fade_samples)

        # Apply envelope to the (potentially combined) waveform
        note_waveform *= envelope

        # =========================================================================
        # === Echo Sustain Logic for Long Plucky Notes (Now works correctly) ===
        # =========================================================================
        # This feature fills the silent tail of long notes with decaying echoes.
        # It is applied only for Plucky envelopes and after the main envelope has been applied.
        if params.s8bit_envelope_type == 'Plucky (AD Envelope)' and params.s8bit_echo_sustain and num_samples > 0:
        
            # The duration of the initial pluck is determined by its decay time.
            initial_pluck_duration_s = params.s8bit_decay_time_s
            initial_pluck_samples = int(initial_pluck_duration_s * fs)
            
            # Check if the note is long enough to even need echoes.
            if num_samples > initial_pluck_samples * params.s8bit_echo_trigger_threshold: # Only trigger if there's significant empty space.
            
                # Calculate the properties of the echoes.
                echo_delay_samples = int(fs / params.s8bit_echo_rate_hz)
                if echo_delay_samples > 0: # Prevent infinite loops
                    echo_amplitude = start_amp * params.s8bit_echo_decay_factor
            
                    # Start placing echoes after the first pluck has finished.
                    current_sample_offset = initial_pluck_samples

                    while current_sample_offset < num_samples:
                        # Ensure there's space for a new echo.
                        if current_sample_offset + echo_delay_samples <= num_samples:
                            
                            # Create a very short, plucky envelope for the echo.
                            echo_attack_samples = min(int(0.002 * fs), echo_delay_samples) # 2ms attack
                            echo_decay_samples = echo_delay_samples - echo_attack_samples

                            if echo_decay_samples > 0:
                                # Create the small echo envelope shape.
                                echo_envelope = np.zeros(echo_delay_samples)
                                echo_envelope[:echo_attack_samples] = np.linspace(0, echo_amplitude, echo_attack_samples)
                                echo_envelope[echo_attack_samples:] = np.linspace(echo_amplitude, 0, echo_decay_samples)
                                
                                # Create a temporary waveform for the echo and apply the envelope.
                                # It reuses the main note's frequency and oscillator phase.
                                # Re-calculating phase here is simpler than tracking, for additive synthesis
                                phase_inc_echo = 2 * np.pi * freq / fs
                                phase_echo = np.cumsum(np.full(echo_delay_samples, phase_inc_echo))

                                if params.s8bit_waveform_type == 'Square':
                                    echo_waveform_segment = signal.square(phase_echo, duty=params.s8bit_pulse_width)
                                elif params.s8bit_waveform_type == 'Sawtooth':
                                    echo_waveform_segment = signal.sawtooth(phase_echo)
                                else: # Triangle
                                    echo_waveform_segment = signal.sawtooth(phase_echo, width=0.5)
                                
                                # Add the enveloped echo on top of the already-enveloped main waveform
                                note_waveform[current_sample_offset : current_sample_offset + echo_delay_samples] += echo_waveform_segment * echo_envelope

                                # Prepare for the next echo.
                                echo_amplitude *= params.s8bit_echo_decay_factor

                        current_sample_offset += echo_delay_samples
        # --- END of Echo Sustain Logic ---

        # --- Final Processing Stage (Per-Note) ---
        if use_aa:
            # 1. Frequency-dependent lowpass filter
            harm_limit = getattr(params, 's8bit_harmonic_lowpass_factor', 12.0)
            cutoff = min(fs * 0.45, max(3000.0, freq * harm_limit))
            note_waveform = one_pole_lowpass(note_waveform, cutoff_hz=cutoff, fs=fs)
            
            # 2. Final Gain and Soft Limiter
            final_gain = getattr(params, 's8bit_final_gain', 0.8)
            note_waveform *= final_gain
            note_waveform = np.tanh(note_waveform) # Soft clip/limit
            
        # --- Add to main waveform buffer ---
        start_sample = int(note.start * fs)
        end_sample = start_sample + num_samples
        if end_sample > waveform.shape[1]:
            end_sample = waveform.shape[1]
            note_waveform = note_waveform[:end_sample-start_sample]

        # Add the mono note waveform to the stereo buffer with panning
        waveform[0, start_sample:end_sample] += note_waveform * pan_l
        waveform[1, start_sample:end_sample] += note_waveform * pan_r
        
    return waveform # Returns a (2, N) numpy array


def analyze_midi_velocity(midi_path):
    midi = pretty_midi.PrettyMIDI(midi_path)
    all_velocities = []
    
    print(f"Analyzing velocity for MIDI: {midi_path}")
    for i, instrument in enumerate(midi.instruments):
        velocities = [note.velocity for note in instrument.notes]
        all_velocities.extend(velocities)

        if velocities:
            print(f"Instrument {i} ({instrument.name}):")
            print(f"  Notes count: {len(velocities)}")
            print(f"  Velocity min: {min(velocities)}")
            print(f"  Velocity max: {max(velocities)}")
            print(f"  Velocity mean: {np.mean(velocities):.2f}")
        else:
            print(f"Instrument {i} ({instrument.name}): no notes found.")

    if all_velocities:
        print("\nOverall MIDI velocity stats:")
        print(f"  Total notes: {len(all_velocities)}")
        print(f"  Velocity min: {min(all_velocities)}")
        print(f"  Velocity max: {max(all_velocities)}")
        print(f"  Velocity mean: {np.mean(all_velocities):.2f}")
    else:
        print("No notes found in this MIDI.")


def preview_sound_source(sound_source_name: str, *args):
    """
    Generates a short audio preview for either a selected SoundFont or the
    8-bit Synthesizer, using the Super Mario Bros. theme as a test melody.
    
    This function acts as a router:
    - If a SoundFont is selected, it uses FluidSynth.
    - If the 8-bit Synthesizer is selected, it uses the internal `synthesize_8bit_style`
      function, capturing the current UI settings for an accurate preview.
    
    Args:
        sound_source_name (str): The name of the SoundFont or the 8-bit synth label.
        *args: Captures all current UI settings, which are passed to build an
               AppParameters object for the 8-bit synth preview.
        
    Returns:
        A Gradio-compatible audio tuple (sample_rate, numpy_array).
    """
    srate = 44100  # Use a standard sample rate for all previews.

    # 1. Create a MIDI object in memory.
    preview_midi = pretty_midi.PrettyMIDI()
        
    # Use a lead instrument. Program 81 (Lead 2, sawtooth) is a good, bright default.
    instrument = pretty_midi.Instrument(program=81, is_drum=False, name="Preview Lead")

    # 2. Define the melody: Super Mario Bros. theme intro
    #    - tempo: A brisk 200 BPM, so each 0.15s step is a 16th note.
    #    - notes: A list of tuples (pitch, duration_in_steps)
    tempo = 200.0
    time_per_step = 60.0 / tempo / 2 # 16th note duration at this tempo
        
        # (Pitch, Duration in steps)
        # MIDI Pitch 60 = C4 (Middle C)
    melody_data = [
        (76, 1), (76, 2), (76, 2), (72, 1), (76, 2), # E E E C E
        (79, 4), (67, 4)                              # G G(low)
    ]
        
    current_time = 0.0
    for pitch, duration_steps in melody_data:
        start_time = current_time
        end_time = start_time + (duration_steps * time_per_step)
            
        # Add a tiny gap between notes to ensure they re-trigger clearly
        note_end_time = end_time - 0.01

        note = pretty_midi.Note(
            velocity=120, # Use a high velocity for a bright, clear sound
            pitch=pitch,
            start=start_time,
            end=note_end_time
        )
        instrument.notes.append(note)
        current_time = end_time

    preview_midi.instruments.append(instrument)

    # --- ROUTING LOGIC: Decide which synthesizer to use ---
    
    # CASE 1: 8-bit Synthesizer Preview
    if sound_source_name == SYNTH_8_BIT_LABEL:
        print("Generating preview for: 8-bit Synthesizer")
        try:
            # Create a temporary AppParameters object from the current UI settings
            params = AppParameters(**dict(zip(ALL_PARAM_KEYS, args)))
            
            # Use the internal synthesizer to render the preview MIDI
            audio_waveform = synthesize_8bit_style(midi_data=preview_midi, fs=srate, params=params)
            
            # Normalize and prepare for Gradio
            peak_val = np.max(np.abs(audio_waveform))
            if peak_val > 0:
                audio_waveform /= peak_val
            
            # The synth returns (channels, samples), Gradio needs (samples, channels)
            audio_out = (audio_waveform.T * 32767).astype(np.int16)
            
            print("8-bit preview generated successfully.")
            return (srate, audio_out)

        except Exception as e:
            print(f"An error occurred during 8-bit preview generation: {e}")
            return None

    # CASE 2: SoundFont Preview
    else:
        soundfont_path = soundfonts_dict.get(sound_source_name)
        if not soundfont_path or not os.path.exists(soundfont_path):
            print(f"Preview failed: SoundFont file not found at '{soundfont_path}'")
            raise gr.Error(f"Could not find the SoundFont file for '{sound_source_name}'.")
        
        try:
            print(f"Generating preview for: {sound_source_name}")
            # Convert the in-memory MIDI object to a binary stream.
            midi_io = io.BytesIO()
            preview_midi.write(midi_io)
            midi_data = midi_io.getvalue()
            
            # Use the existing rendering function to generate the audio.
            # Ensure the output is a tuple (sample_rate, numpy_array)
            audio_out = midi_to_colab_audio(
                midi_data,
                soundfont_path=soundfont_path,
                sample_rate=srate,
                output_for_gradio=True
            )
            
            # Ensure the returned value is exactly what Gradio expects.
            # The function `midi_to_colab_audio` should return a NumPy array.
            # We must wrap it in a tuple with the sample rate.
            if isinstance(audio_out, np.ndarray):
                print("SoundFont preview generated successfully.")
                return (srate, audio_out)
            else:
                # If the rendering function fails, it might return something else.
                # We handle this to prevent the Gradio error.
                print("Preview failed: Rendering function did not return valid audio data.")
                return None

        except Exception as e:
            # Catch any other errors, including from FluidSynth, and report them.
            print(f"An error occurred during SoundFont preview generation: {e}")
            # It's better to return None than to crash the UI.
            # The error will be visible in the console.
            return None


def scale_instrument_velocity(instrument, scale=0.8):
    for note in instrument.notes:
        note.velocity = max(1, min(127, int(note.velocity * scale)))
    

def normalize_loudness(audio_data, sample_rate, target_lufs=-23.0):
    """
    Normalizes the audio data to a target integrated loudness (LUFS).
    This provides more consistent perceived volume than peak normalization.
    
    Args:
        audio_data (np.ndarray): The audio signal.
        sample_rate (int): The sample rate of the audio.
        target_lufs (float): The target loudness in LUFS. Defaults to -23.0,
                             a common standard for broadcast.

    Returns:
        np.ndarray: The loudness-normalized audio data.
    """
    try:
        # 1. Measure the integrated loudness of the input audio
        meter = pyln.Meter(sample_rate) # create meter
        loudness = meter.integrated_loudness(audio_data)

        # 2. Calculate the gain needed to reach the target loudness
        # The gain is applied in the linear domain, so we convert from dB
        loudness_gain_db = target_lufs - loudness
        loudness_gain_linear = 10.0 ** (loudness_gain_db / 20.0)

        # 3. Apply the gain
        normalized_audio = audio_data * loudness_gain_linear

        # 4. Final safety check: peak normalize to prevent clipping, just in case
        # the loudness normalization results in peaks > 1.0
        peak_val = np.max(np.abs(normalized_audio))
        if peak_val > 1.0:
            normalized_audio /= peak_val
            print(f"Warning: Loudness normalization resulted in clipping. Audio was peak-normalized as a safeguard.")
        
        print(f"Audio normalized from {loudness:.2f} LUFS to target {target_lufs} LUFS.")
        return normalized_audio

    except Exception as e:
        print(f"Loudness normalization failed: {e}. Falling back to original audio.")
        return audio_data


# =================================================================================================
# === MIDI Merging Function ===
# =================================================================================================
def merge_midis(midi_path_left: str, midi_path_right: str, output_path: str):
    """
    Merges two MIDI files into a single MIDI file. This robust version iterates
    through ALL instruments in both MIDI files, ensuring no data is lost if the
    source files are multi-instrumental.
    
    It applies hard-left panning (Pan=0) to every instrument from the left MIDI
    and hard-right panning (Pan=127) to every instrument from the right MIDI.
    """
    try:
        analyze_midi_velocity(midi_path_left)
        analyze_midi_velocity(midi_path_right)
        midi_left = pretty_midi.PrettyMIDI(midi_path_left)
        midi_right = pretty_midi.PrettyMIDI(midi_path_right)
        
        merged_midi = pretty_midi.PrettyMIDI()

        # --- Process ALL instruments from the left channel MIDI ---
        if midi_left.instruments:
            print(f"Found {len(midi_left.instruments)} instrument(s) in the left channel MIDI.")
            # Use a loop to iterate through every instrument
            for instrument in midi_left.instruments:
                scale_instrument_velocity(instrument, scale=0.8)
                # To avoid confusion, we can prefix the instrument name
                instrument.name = f"Left - {instrument.name if instrument.name else 'Instrument'}"
                
                # Create and add the Pan Left control change
                # Create a Control Change event for Pan (controller number 10).
                # Set its value to 0 for hard left panning.
                # Add it at the very beginning of the track (time=0.0).
                pan_left = pretty_midi.ControlChange(number=10, value=0, time=0.0)
                # Use insert() to ensure the pan event is the very first one
                instrument.control_changes.insert(0, pan_left)
                
                # Append the fully processed instrument to the merged MIDI
                merged_midi.instruments.append(instrument)
            
        # --- Process ALL instruments from the right channel MIDI ---
        if midi_right.instruments:
            print(f"Found {len(midi_right.instruments)} instrument(s) in the right channel MIDI.")
            # Use a loop here as well
            for instrument in midi_right.instruments:
                scale_instrument_velocity(instrument, scale=0.8)
                instrument.name = f"Right - {instrument.name if instrument.name else 'Instrument'}"
                
                # Create and add the Pan Right control change
                # Create a Control Change event for Pan (controller number 10).
                # Set its value to 127 for hard right panning.
                # Add it at the very beginning of the track (time=0.0).
                pan_right = pretty_midi.ControlChange(number=10, value=127, time=0.0)
                instrument.control_changes.insert(0, pan_right)
                
                merged_midi.instruments.append(instrument)
            
        merged_midi.write(output_path)
        print(f"Successfully merged all instruments and panned into '{os.path.basename(output_path)}'")
        analyze_midi_velocity(output_path)
        return output_path
        
    except Exception as e:
        print(f"Error merging MIDI files: {e}")
        # Fallback logic remains the same
        if os.path.exists(midi_path_left):
            print("Fallback: Using only the left channel MIDI.")
            return midi_path_left
        return None


def is_stereo_midi(midi_path: str) -> bool:
    """
    Checks if a MIDI file contains the specific stereo panning control changes
    (hard left and hard right) created by the merge_midis function.

    Args:
        midi_path (str): The file path to the MIDI file.

    Returns:
        bool: True if both hard-left (0) and hard-right (127) pan controls are found, False otherwise.
    """
    try:
        midi_data = pretty_midi.PrettyMIDI(midi_path)
        
        found_left_pan = False
        found_right_pan = False

        for instrument in midi_data.instruments:
            for control_change in instrument.control_changes:
                # MIDI Controller Number 10 is for Panning.
                if control_change.number == 10:
                    if control_change.value == 0:
                        found_left_pan = True
                    elif control_change.value == 127:
                        found_right_pan = True
            
            # Optimization: If we've already found both, no need to check further.
            if found_left_pan and found_right_pan:
                return True

        return found_left_pan and found_right_pan

    except Exception as e:
        # If the MIDI file is invalid or another error occurs, assume it's not our special stereo format.
        print(f"Could not analyze MIDI for stereo info: {e}")
        return False


# =================================================================================================
# === Stage 1: Audio to MIDI Transcription Functions ===
# =================================================================================================

def TranscribePianoAudio(input_file):
    """
    Transcribes a WAV or MP3 audio file of a SOLO PIANO performance into a MIDI file.
    This uses the ByteDance model.
    Args:
        input_file_path (str): The path to the input audio file.
    Returns:
        str: The file path of the generated MIDI file.
    """
    print('=' * 70)
    print('STAGE 1: Starting Piano-Specific Transcription')
    print('=' * 70)
    
    # Generate a unique output filename for the MIDI
    fn = os.path.basename(input_file)
    fn1 = fn.split('.')[0]

    # Use os.path.join to create a platform-independent directory path
    output_dir = os.path.join("output", "transcribed_piano_")
    out_mid_path = os.path.join(output_dir, fn1 + '.mid')
    
    # Check for the directory's existence and create it if necessary
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    print('-' * 70)
    print(f'Input file name: {fn}')
    print(f'Output MIDI path: {out_mid_path}')
    print('-' * 70)
    
    # Load audio using the utility function
    print('Loading audio...')
    (audio, _) = utilities.load_audio(input_file, sr=transcription_sample_rate, mono=True)
    print('Audio loaded successfully.')
    print('-' * 70)
    
    # Initialize the transcription model
    # Use 'cuda' if a GPU is available and configured, otherwise 'cpu'
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    print(f'Loading transcriptor model... device= {device}')
    transcriptor = PianoTranscription(device=device, checkpoint_path=os.path.join("src", "models", "CRNN_note_F1=0.9677_pedal_F1=0.9186.pth"))
    print('Transcriptor loaded.')
    print('-' * 70)
    
    # Perform transcription
    print('Transcribing audio to MIDI (Piano-Specific)...')
    # This function call saves the MIDI file to the specified path
    transcriptor.transcribe(audio, out_mid_path)
    print('Piano transcription complete.')
    print('=' * 70)
    
    # Return the path to the newly created MIDI file
    return out_mid_path

def TranscribeGeneralAudio(input_file, **kwargs):
    """
    Transcribes a general audio file into a MIDI file using basic-pitch.
    This is suitable for various instruments and vocals.
    """
    print('=' * 70)
    print('STAGE 1: Starting General Purpose Transcription')
    print('=' * 70)
    
    fn = os.path.basename(input_file)
    fn1 = fn.split('.')[0]
    output_dir = os.path.join("output", "transcribed_general_")
    out_mid_path = os.path.join(output_dir, fn1 + '.mid')
    os.makedirs(output_dir, exist_ok=True)

    print(f'Input file: {fn}\nOutput MIDI: {out_mid_path}')
    
    # --- Perform transcription using basic-pitch ---
    print('Transcribing audio to MIDI (General Purpose)...')
    # The predict function handles audio loading internally
    model_output, midi_data, note_events = basic_pitch.inference.predict(
        audio_path=input_file,
        model_or_model_path=ICASSP_2022_MODEL_PATH,
        **kwargs
    )
    
    # --- Save the MIDI file ---
    midi_data.write(out_mid_path)
    print('General transcription complete.')
    print('=' * 70)
    
    return out_mid_path

# =================================================================================================
# === Stage 2: MIDI Transformation and Rendering Function ===
# =================================================================================================

def Render_MIDI(*, input_midi_path: str, params: AppParameters, progress: gr.Progress = None):
    """
    Processes and renders a MIDI file according to user-defined settings.
    Can render using SoundFonts or a custom 8-bit synthesizer.

    This version supports a parallel arpeggiator workflow, where the original MIDI 
    and an arpeggiated version are synthesized separately and then mixed together.

    Args:
        input_midi_path (str): The path to the input MIDI file.
        All other arguments are rendering options from the Gradio UI.
    Returns:
        A tuple containing all the output elements for the Gradio UI.
    """
    print('*' * 70)
    print('STAGE 2: Starting MIDI Rendering')
    print('*' * 70)

    # --- File and Settings Setup ---
    fn = os.path.basename(input_midi_path)
    fn1 = fn.split('.')[0]
    
    # Use os.path.join to create a platform-independent directory path
    output_dir = os.path.join("output", "rendered_midi")
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # Now, join the clean directory path with the filename
    new_fn_path = os.path.join(output_dir, fn1 + '_rendered.mid')

    try:
        with open(input_midi_path, 'rb') as f:
            fdata = f.read()
        input_midi_md5hash = hashlib.md5(fdata).hexdigest()
    except FileNotFoundError:
        # Handle cases where the input file might not exist
        print(f"Error: Input MIDI file not found at {input_midi_path}")
        return [None] * 7 # Return empty values for all outputs

    print('=' * 70)
    print('Requested settings:')
    print(f'Input MIDI file name: {fn}')
    print(f'Input MIDI md5 hash: {input_midi_md5hash}')
    print('-' * 70)
    print(f"Render type: {params.render_type}")
    print(f"Soundfont bank: {params.soundfont_bank}")
    print(f"Audio render sample rate: {params.render_sample_rate}")
    # ... (add other print statements for settings if needed)
    print('=' * 70)
    
    # --- MIDI Processing using TMIDIX ---
    print('Processing MIDI... Please wait...')
    raw_score = MIDI.midi2single_track_ms_score(fdata)
    # call the function and store the returned list in a variable.
    processed_scores = TMIDIX.advanced_score_processor(raw_score, 
                                                   return_enhanced_score_notes=True, 
                                                   apply_sustain=params.render_with_sustains)
    # check if the returned list is empty. This happens when transcription finds no notes.
    # This check prevents the 'IndexError: list index out of range'.
    if not processed_scores:
        # If it is empty, print a warning and return a user-friendly error message.
        print("Warning: MIDI file contains no processable notes.")
        # The number of returned values must match the function's expected output.
        # We return a tuple with empty or placeholder values for all 7 output components.
        return ("N/A", fn1, "MIDI file contains no notes.", None, None, None, "No notes found.")

    # If the list is not empty, it is now safe to get the first element.
    escore = processed_scores[0]

    # Handle cases where the MIDI might not contain any notes
    if not escore:
        print("Warning: MIDI file contains no processable notes.")
        return ("N/A", fn1, "MIDI file contains no notes.",None, None, None, "No notes found.")

    # This line will now work correctly because merge_misaligned_notes is guaranteed to be an integer.
    if params.merge_misaligned_notes > 0:
        escore = TMIDIX.merge_escore_notes(escore, merge_threshold=params.merge_misaligned_notes)
        
    escore = TMIDIX.augment_enhanced_score_notes(escore, timings_divider=1)

    first_note_index = [e[0] for e in raw_score[1]].index('note')
    cscore = TMIDIX.chordify_score([1000, escore])

    meta_data = raw_score[1][:first_note_index] + [escore[0]] + [escore[-1]] + [raw_score[1][-1]]

    aux_escore_notes = TMIDIX.augment_enhanced_score_notes(escore, sort_drums_last=True)
    song_description = TMIDIX.escore_notes_to_text_description(aux_escore_notes)
    
    print('Done!')
    print('=' * 70)
    print('Input MIDI metadata:', meta_data[:5])
    print('=' * 70)
    print('Input MIDI song description:', song_description)
    print('=' * 70)
    print('Processing...Please wait...')

    # A deep copy of the score to be modified
    output_score = copy.deepcopy(escore)

    # Apply transformations based on render_type
    if params.render_type == "Extract melody":
        output_score = TMIDIX.add_melody_to_enhanced_score_notes(escore, return_melody=True)
        output_score = TMIDIX.recalculate_score_timings(output_score)
    elif params.render_type == "Flip":
        output_score = TMIDIX.flip_enhanced_score_notes(escore)
    elif params.render_type == "Reverse":
        output_score = TMIDIX.reverse_enhanced_score_notes(escore)
    elif params.render_type == 'Repair Durations':
        output_score = TMIDIX.fix_escore_notes_durations(escore, min_notes_gap=0)
    elif params.render_type == 'Repair Chords':
        fixed_cscore = TMIDIX.advanced_check_and_fix_chords_in_chordified_score(cscore)[0]
        output_score = TMIDIX.flatten(fixed_cscore)
    elif params.render_type == 'Remove Duplicate Pitches':
        output_score = TMIDIX.remove_duplicate_pitches_from_escore_notes(escore)
    elif params.render_type == "Add Drum Track":
        nd_escore = [e for e in escore if e[3] != 9]
        nd_escore = TMIDIX.augment_enhanced_score_notes(nd_escore)
        output_score = TMIDIX.advanced_add_drums_to_escore_notes(nd_escore)

        for e in output_score:
            e[1] *= 16
            e[2] *= 16

    print('MIDI processing complete.')
    print('=' * 70)

    # --- Final Processing and Patching ---
    if params.render_type != "Render as-is":
        print('Applying final adjustments (transpose, align, patch)...')
        if params.custom_render_patch != -1: # -1 indicates no change
            for e in output_score:
                if e[3] != 9: # not a drum channel
                    e[6] = params.custom_render_patch
    
        if params.render_transpose_value != 0:
            output_score = TMIDIX.transpose_escore_notes(output_score, params.render_transpose_value)

        if params.render_transpose_to_C4:
            output_score = TMIDIX.transpose_escore_notes_to_pitch(output_score, 60) # C4 is MIDI pitch 60
        
        if params.render_align == "Start Times":
            output_score = TMIDIX.recalculate_score_timings(output_score)
            output_score = TMIDIX.align_escore_notes_to_bars(output_score)

        elif params.render_align == "Start Times and Durations":
            output_score = TMIDIX.recalculate_score_timings(output_score)
            output_score = TMIDIX.align_escore_notes_to_bars(output_score, trim_durations=True)
    
        elif params.render_align == "Start Times and Split Durations":
            output_score = TMIDIX.recalculate_score_timings(output_score)
            output_score = TMIDIX.align_escore_notes_to_bars(output_score, split_durations=True)

        if params.render_type == "Longest Repeating Phrase":
            zscore = TMIDIX.recalculate_score_timings(output_score)
            lrno_score = TMIDIX.escore_notes_lrno_pattern_fast(zscore)
    
            if lrno_score is not None:
                output_score = lrno_score
    
            else:
                output_score = TMIDIX.recalculate_score_timings(TMIDIX.escore_notes_middle(output_score, 50))
    
        if params.render_type == "Multi-Instrumental Summary":
            zscore = TMIDIX.recalculate_score_timings(output_score)
            c_escore_notes = TMIDIX.compress_patches_in_escore_notes_chords(zscore)
        
            if len(c_escore_notes) > 128:
                cmatrix = TMIDIX.escore_notes_to_image_matrix(c_escore_notes, filter_out_zero_rows=True, filter_out_duplicate_rows=True)
                smatrix = TPLOTS.square_image_matrix(cmatrix, num_pca_components=max(1, min(5, len(c_escore_notes) // 128)))
                output_score = TMIDIX.image_matrix_to_original_escore_notes(smatrix)
            
                for o in output_score:
                    o[1] *= 250
                    o[2] *= 250

        if params.render_output_as_solo_piano:
            output_score = TMIDIX.solo_piano_escore_notes(output_score, keep_drums=(not params.render_remove_drums))
        
        if params.render_remove_drums and not params.render_output_as_solo_piano:
            output_score = TMIDIX.strip_drums_from_escore_notes(output_score)
          
        if params.render_type == "Solo Piano Summary":
            sp_escore_notes = TMIDIX.solo_piano_escore_notes(output_score, keep_drums=False)
            zscore = TMIDIX.recalculate_score_timings(sp_escore_notes)
    
            if len(zscore) > 128:
            
                bmatrix = TMIDIX.escore_notes_to_binary_matrix(zscore)
                cmatrix = TMIDIX.compress_binary_matrix(bmatrix, only_compress_zeros=True)
                smatrix = TPLOTS.square_binary_matrix(cmatrix, interpolation_order=max(1, min(5, len(zscore) // 128)))
                output_score = TMIDIX.binary_matrix_to_original_escore_notes(smatrix)
    
                for o in output_score:
                    o[1] *= 200
                    o[2] *= 200

        print('Final adjustments complete.')
        print('=' * 70)
        
    # --- Saving Processed MIDI File ---
        # Save the transformed MIDI data
        SONG, patches, _ = TMIDIX.patch_enhanced_score_notes(output_score)
        
        # The underlying function mistakenly adds a '.mid' extension.
        # We must pass the path without the extension to compensate.
        path_without_ext = new_fn_path.rsplit('.mid', 1)[0]

        MIDI.Tegridy_ms_SONG_to_MIDI_Converter(SONG,
                                                  output_signature = 'Integrated-MIDI-Processor',
                                                  output_file_name = path_without_ext,
                                                  track_name='Processed Track',
                                                  list_of_MIDI_patches=patches
                                                  )
        midi_to_render_path = new_fn_path
    else:
        # If "Render as-is", use the original MIDI data
        with open(new_fn_path, 'wb') as f:
            f.write(fdata)
        midi_to_render_path = new_fn_path

    # --- Audio Rendering ---
    print('Rendering final audio...')

    # Select sample rate
    srate = int(params.render_sample_rate)
    
    # --- Conditional Rendering Logic ---
    # --- 8-BIT SYNTHESIZER WORKFLOW ---
    if params.soundfont_bank == SYNTH_8_BIT_LABEL:
        print("Using 8-bit style synthesizer with parallel processing workflow...")
        try:
            # --- Step 1: Prepare MIDI data, load the MIDI file with pretty_midi for manual synthesis
            base_midi = pretty_midi.PrettyMIDI(midi_to_render_path)
            # Pre-process the base MIDI for harshness if enabled. This affects BOTH layers.
            if getattr(params, 's8bit_enable_midi_preprocessing', False):
                base_midi = preprocess_midi_for_harshness(base_midi, params)
                
            # --- Apply Delay/Echo effect to the base MIDI if enabled ---
            # This is done BEFORE the arpeggiator, so the clean base_midi
            # (which contains the lead melody) gets the delay.
            if getattr(params, 's8bit_enable_delay', False):
                base_midi = create_delay_effect(base_midi, params)
                
            # --- Apply Arpeggiator if enabled ---
            # The arpeggiator will now correctly ignore the new echo track
            # because the echo notes are on a separate instrument.
            arpeggiated_midi = None
            if getattr(params, 's8bit_enable_arpeggiator', False):
                # We arpeggiate the (now possibly delayed) base_midi
                arpeggiated_midi = arpeggiate_midi(base_midi, params)

            # --- Step 2: Render the main (original) layer ---
            print("  - Rendering main synthesis layer (including echoes)...")
            # Synthesize the waveform, passing new FX parameters to the synthesis function
            main_and_echo_waveform = synthesize_8bit_style(
                midi_data=base_midi,
                fs=srate,
                params=params,
                progress=progress
            )

            # --- Isolate and filter the echo part if it exists ---
            echo_instrument = None
            for inst in base_midi.instruments:
                if inst.name == "Echo Layer":
                    echo_instrument = inst
                    break
            
            # --- Step 3: Render the delay layers (if enabled) ---
            if echo_instrument:
                print("  - Processing echo layer audio effects...")
                # Create a temporary MIDI object with ONLY the echo instrument
                echo_only_midi = pretty_midi.PrettyMIDI()
                echo_only_midi.instruments.append(echo_instrument)
                
                # Render ONLY the echo layer to an audio waveform
                echo_waveform_raw = synthesize_8bit_style(midi_data=echo_only_midi, fs=srate, params=params)
                
                # --- Start of the Robust Filtering Block ---
                # Apply both High-Pass and Low-Pass filters
                unfiltered_echo = echo_waveform_raw
                filtered_echo = echo_waveform_raw
                
                # --- Apply Filters if requested ---
                # Convert to a format filter function expects (samples, channels)
                # This is inefficient, we should only do it once.
                # Let's assume the filter functions are adapted to take (channels, samples)
                # For now, we'll keep the transpose for simplicity.
                # We will apply filters on a temporary copy to avoid chaining issues.
                temp_filtered_echo = echo_waveform_raw.T
                
                should_filter = False
                # Apply High-Pass Filter
                if params.s8bit_delay_highpass_cutoff_hz > 0:
                    print(f"    - Applying high-pass filter at {params.s8bit_delay_highpass_cutoff_hz} Hz...")
                    temp_filtered_echo = apply_butter_highpass_filter(temp_filtered_echo, params.s8bit_delay_highpass_cutoff_hz, srate)
                    should_filter = True

                # Apply Low-Pass Filter
                if params.s8bit_delay_lowpass_cutoff_hz < srate / 2:
                     print(f"    - Applying low-pass filter at {params.s8bit_delay_lowpass_cutoff_hz} Hz...")
                     temp_filtered_echo = apply_butter_lowpass_filter(temp_filtered_echo, params.s8bit_delay_lowpass_cutoff_hz, srate)
                     should_filter = True
                     
                # Convert back and get the difference
                if should_filter:
                    filtered_echo = temp_filtered_echo.T

                # To avoid re-rendering, we subtract the unfiltered echo and add the filtered one
                # Ensure all waveforms have the same length before math ---
                target_length = main_and_echo_waveform.shape[1]

                # Pad the unfiltered echo if it's shorter
                len_unfiltered = unfiltered_echo.shape[1]
                if len_unfiltered < target_length:
                    unfiltered_echo = np.pad(unfiltered_echo, ((0, 0), (0, target_length - len_unfiltered)))
            
                # Pad the filtered echo if it's shorter
                len_filtered = filtered_echo.shape[1]
                if len_filtered < target_length:
                    filtered_echo = np.pad(filtered_echo, ((0, 0), (0, target_length - len_filtered)))

                # Now that all shapes are guaranteed to be identical, perform the operation.
                main_and_echo_waveform -= unfiltered_echo[:, :target_length]
                main_and_echo_waveform += filtered_echo[:, :target_length]

            final_waveform = main_and_echo_waveform
            
            # --- Step 4: Render the arpeggiator layer (if enabled) ---
            if arpeggiated_midi and arpeggiated_midi.instruments:
                print("  - Rendering and mixing arpeggiator layer...")
                # Temporarily override panning for the arpeggiator synth call
                arp_params = copy.copy(params)
                
                # The synthesize_8bit_style function needs to know how to handle this new panning parameter
                # We will pass it via a temporary attribute.
                setattr(arp_params, '_temp_panning_override', params.s8bit_arpeggio_panning)
                
                arpeggiated_waveform = synthesize_8bit_style(
                    midi_data=arpeggiated_midi,
                    fs=srate,
                    params=arp_params,
                    progress=None # Don't show a second progress bar
                )
                
                # --- Step 4: Mix the layers together ---
                # Ensure waveforms have the same length
                len_main = final_waveform.shape[1]
                len_arp = arpeggiated_waveform.shape[1]
                if len_arp > len_main:
                    final_waveform = np.pad(final_waveform, ((0, 0), (0, len_arp - len_main)))
                elif len_main > len_arp:
                    arpeggiated_waveform = np.pad(arpeggiated_waveform, ((0, 0), (0, len_main - len_arp)))
                
                final_waveform += arpeggiated_waveform
                
            # --- Step 5: Finalize audio for Gradio, normalize and prepare for Gradio
            peak_val = np.max(np.abs(final_waveform))
            if peak_val > 0:
                final_waveform /= peak_val
            # Transpose from (2, N) to (N, 2) and convert to int16 for Gradio
            audio_out = (final_waveform.T * 32767).astype(np.int16)
        except Exception as e:
            print(f"Error during 8-bit synthesis: {e}")
            return [None] * 7
    # --- SOUNDFONT WORKFLOW ---
    else:
        print(f"Using SoundFont: {params.soundfont_bank}")
        # Get the full path from the global dictionary
        soundfont_path = soundfonts_dict.get(params.soundfont_bank)

        # Select soundfont
        if not soundfont_path or not os.path.exists(soundfont_path):
            # If the selected soundfont is not found, inform the user directly via the UI.
            raise gr.Error(f"SoundFont file '{params.soundfont_bank}' could not be found. Please check your 'src/sf2' directory or select another SoundFont.")
            # # Error handling in case the selected file is not found
            # error_msg = f"SoundFont '{params.soundfont_bank}' not found!"
            # print(f"ERROR: {error_msg}")
            # # Fallback to the first available soundfont if possible
            # if soundfonts_dict:
            #     fallback_key = list(soundfonts_dict.keys())[0]
            #     soundfont_path = soundfonts_dict[fallback_key]
            #     print(f"Falling back to '{fallback_key}'.")
            # else:
            #     # If no soundfonts are available at all, raise an error
            #     raise gr.Error("No SoundFonts are available for rendering!")

        with open(midi_to_render_path, 'rb') as f:
            midi_file_content = f.read()

        audio_out = midi_to_colab_audio(midi_file_content, 
                                    soundfont_path=soundfont_path, # Use the dynamically found path
                                    sample_rate=srate,
                                    output_for_gradio=True
                                    )
    
    print('Audio rendering complete.')
    print('=' * 70)

    # --- Preparing Outputs for Gradio ---
    with open(midi_to_render_path, 'rb') as f:
        new_md5_hash = hashlib.md5(f.read()).hexdigest()
    output_plot = TPLOTS.plot_ms_SONG(output_score, plot_title=f"Score of {fn1}", return_plt=True)

    output_midi_summary = str(meta_data)
    
    return new_md5_hash, fn1, output_midi_summary, midi_to_render_path, (srate, audio_out), output_plot, song_description


def analyze_midi_features(midi_data):
    """
    Analyzes a PrettyMIDI object to extract musical features for parameter recommendation.
    
    Args:
        midi_data (pretty_midi.PrettyMIDI): The MIDI data to analyze.

    Returns:
        dict or None: A dictionary containing features, or None if the MIDI is empty.
                      Features: 'note_count', 'instruments_count', 'duration',
                                'note_density', 'avg_velocity', 'pitch_range'.
    """
    all_notes = [note for instrument in midi_data.instruments for note in instrument.notes]
    note_count = len(all_notes)
    
    # Return None if the MIDI file has no notes to analyze.
    if note_count == 0:
        return None

    duration = midi_data.get_end_time()
    # Avoid division by zero for empty-duration MIDI files.
    if duration == 0:
        note_density = 0
    else:
        note_density = note_count / duration

    # --- Calculate new required features ---
    avg_velocity = sum(note.velocity for note in all_notes) / note_count
    avg_pitch = sum(note.pitch for note in all_notes) / note_count
    avg_note_length = sum(note.end - note.start for note in all_notes) / note_count

    # Calculate pitch range
    if note_count > 1:
        min_pitch = min(note.pitch for note in all_notes)
        max_pitch = max(note.pitch for note in all_notes)
        pitch_range = max_pitch - min_pitch
    else:
        pitch_range = 0

    return {
        'note_count': note_count,
        'instruments_count': len(midi_data.instruments),
        'duration': duration,
        'note_density': note_density, # Notes per second
        'avg_velocity': avg_velocity,
        'pitch_range': pitch_range, # In semitones
        'avg_pitch': avg_pitch,
        'avg_note_length': avg_note_length,
    }

def determine_waveform_type(features):
    """
    Determines the best waveform type based on analyzed MIDI features.
    - Square: Best for most general-purpose, bright melodies.
    - Sawtooth: Best for intense, heavy, or powerful leads and basses.
    - Triangle: Best for soft, gentle basses or flute-like sounds.
    
    Args:
        features (dict): The dictionary of features from analyze_midi_features.

    Returns:
        str: The recommended waveform type ('Square', 'Sawtooth', or 'Triangle').
    """
    # 1. Check for conditions that strongly suggest a Triangle wave (soft bassline)
    # MIDI Pitch 52 is ~G#3. If the average pitch is below this, it's likely a bass part.
    # If notes are long and the pitch range is narrow, it confirms a simple, melodic bassline.
    if features['avg_pitch'] <= 52 and features['avg_note_length'] >= 0.3 and features['pitch_range'] < 12:
        return "Triangle"

    # 2. Check for conditions that suggest a Sawtooth wave (intense/complex part)
    # High note density or a very wide pitch range often indicates an aggressive lead or a complex solo.
    # The sawtooth's rich harmonics are perfect for this.
    if features['note_density'] >= 6 or features['pitch_range'] >= 18:
        return "Sawtooth"

    # 3. Default to the most versatile waveform: Square
    return "Square"

def recommend_8bit_params(midi_data, default_preset):
    """
    Recommends 8-bit synthesizer parameters using a unified, factor-based model.
    This "AI" generates a sound profile based on normalized musical features.
    
    Args:
        midi_data (pretty_midi.PrettyMIDI): The MIDI data to analyze.
        default_preset (dict): A fallback preset if analysis fails.

    Returns:
        dict: A dictionary of recommended synthesizer parameters.
    """
    features = analyze_midi_features(midi_data)
    if features is None:
        # Return a default preset if MIDI is empty or cannot be analyzed
        return default_preset

    # --- Rule-based Parameter Recommendation ---
    params = {}

    # --- 1. Core Timbre Selection ---
    # Intelligent Waveform Selection
    params['waveform_type'] = determine_waveform_type(features)
    # Determine pulse width *after* knowing the waveform.
    # This only applies if the waveform is Square.
    if params['waveform_type'] == 'Square':
        # For Square waves, use pitch complexity to decide pulse width.
        # Complex melodies get a thinner sound (0.3) for clarity.
        # Simpler melodies get a fuller sound (0.5).
        params['pulse_width'] = 0.3 if features['pitch_range'] > 30 else 0.5
    else:
        # For Sawtooth or Triangle, pulse width is not applicable. Set a default.
        params['pulse_width'] = 0.5

    # --- 2. Envelope and Rhythm ---
    # Determine envelope type based on note density
    is_plucky = features['note_density'] > 10
    params['envelope_type'] = 'Plucky (AD Envelope)' if is_plucky else 'Sustained (Full Decay)'
    params['decay_time_s'] = 0.15 if is_plucky else 0.4
    
    # --- 3. Modulation (Vibrato) ---
    # Vibrato depth and rate based on velocity and density
    params['vibrato_depth'] = min(max((features['avg_velocity'] - 60) / 20, 0), 10) # More velocity = more depth
    if features['note_density'] > 12:
        params['vibrato_rate'] = 7.0 # Very fast music -> frantic vibrato
    elif features['note_density'] > 6:
        params['vibrato_rate'] = 5.0 # Moderately fast music -> standard vibrato
    else:
        params['vibrato_rate'] = 3.0 # Slow music -> gentle vibrato

    # --- 4. Progressive/Graded Parameters using Normalization ---
    
    # Smooth notes level (0.0 to 1.0): More smoothing for denser passages.
    # Effective range: 3 to 8 notes/sec.
    params['smooth_notes_level'] = min(max((features['note_density'] - 3) / 5.0, 0.0), 1.0) # Smoothen notes in denser passages

    # Continuous vibrato level (0.0 to 1.0): Less dense passages get more lyrical, continuous vibrato.
    # Effective range: 5 to 10 notes/sec. (Inverted)
    params['continuous_vibrato_level'] = 1.0 - min(max((features['note_density'] - 5) / 5.0, 0.0), 1.0) # Lyrical (less dense) music gets connected vibrato
    
    # Noise level (0.0 to 0.1): Higher velocity passages get more "air" or "grit".
    # Effective range: velocity 50 to 90.
    params['noise_level'] = min(max((features['avg_velocity'] - 50) / 40.0, 0.0), 1.0) * 0.1

    # Distortion level (0.0 to 0.1): Shorter notes get more distortion for punch.
    # Effective range: note length 0.5s down to 0.25s. (Inverted)
    if features['avg_note_length'] < 0.25: # Short, staccato notes
        params['distortion_level'] = 0.1
    elif features['avg_note_length'] < 0.5: # Medium length notes
        params['distortion_level'] = 0.05
    else: # Long, sustained notes
        params['distortion_level'] = 0.0

    # Progressive FM modulation based on a combined complexity factor.
    # Normalizes note density and pitch range to a 0-1 scale.
    density_factor = min(max((features['note_density'] - 5) / 15, 0), 1)  # Effective range 5-20 notes/sec
    range_factor = min(max((features['pitch_range'] - 15) / 30, 0), 1)    # Effective range 15-45 semitones

    # The overall complexity is the average of these two factors.
    complexity_factor = (density_factor + range_factor) / 2
    params['fm_modulation_depth'] = round(0.3 * complexity_factor, 3)
    params['fm_modulation_rate'] = round(200 * complexity_factor, 1)

    # Non-linear bass boost
    # REFINED LOGIC: Non-linear bass boost based on instrument count.
    # More instruments lead to less bass boost to avoid a muddy mix,
    # while solo or duo arrangements get a significant boost to sound fuller.
    # The boost level has a floor of 0.2 and a ceiling of 1.0.
    params['bass_boost_level'] = max(0.2, 1.0 - (features['instruments_count'] - 1) * 0.15)
    
    # Round all float values for cleaner output
    for key, value in params.items():
        if isinstance(value, float):
            params[key] = round(value, 3)

    return params


# =================================================================================================
# === Main Application Logic ===
# =================================================================================================


# --- Helper function to encapsulate the transcription pipeline for a single audio file ---
def _transcribe_stem(audio_path: str, base_name: str, temp_dir: str, params: AppParameters):
    """
    Takes a single audio file path and runs the full transcription pipeline on it.
    This includes stereo/mono handling and normalization.
    Returns:
        A tuple containing:
        - The file path of the resulting transcribed MIDI.
        - The dictionary of the final basic_pitch parameters that were actually used.
    """
    print(f"\n--- Transcribing Stem: {os.path.basename(audio_path)} ---")
    
    # Load the audio stem to process it
    audio_data, native_sample_rate = librosa.load(audio_path, sr=None, mono=False)
    
    # --- Adaptive Parameter Logic ---
    final_bp_params = {
        "onset_threshold": params.onset_threshold,
        "frame_threshold": params.frame_threshold,
        "minimum_note_length": params.minimum_note_length,
        "minimum_frequency": params.minimum_frequency,
        "maximum_frequency": params.maximum_frequency,
        "infer_onsets": params.infer_onsets,
        "melodia_trick": params.melodia_trick,
        "multiple_pitch_bends": params.multiple_pitch_bends,
    }

    # Check if the user has selected the auto-analysis option from the dropdown.
    if params.transcription_method == "General Purpose" and params.basic_pitch_preset_selector == "Auto-Analyze Audio":
        adaptive_params = analyze_audio_for_adaptive_params(audio_data, native_sample_rate)
        # Update the final_bp_params dictionary with the new adaptive values
        final_bp_params.update(adaptive_params)
        print(f"  - Overriding manual settings with auto-analyzed parameters. final_bp_params: {final_bp_params}")

    if params.enable_stereo_processing and audio_data.ndim == 2 and audio_data.shape[0] == 2:
        print("Stereo processing enabled for stem.")
        left_channel_np = audio_data[0]
        right_channel_np = audio_data[1]
        
        normalized_left = normalize_loudness(left_channel_np, native_sample_rate)
        normalized_right = normalize_loudness(right_channel_np, native_sample_rate)
        
        temp_left_path = os.path.join(temp_dir, f"{base_name}_left.flac")
        temp_right_path = os.path.join(temp_dir, f"{base_name}_right.flac")
        
        sf.write(temp_left_path, normalized_left, native_sample_rate)
        sf.write(temp_right_path, normalized_right, native_sample_rate)
        
        print(f"Saved left channel to: {temp_left_path}")
        print(f"Saved right channel to: {temp_right_path}")
        
        print("Transcribing left and right channel...")
        if params.transcription_method == "General Purpose":
            midi_path_left = TranscribeGeneralAudio(temp_left_path, **final_bp_params)
            midi_path_right = TranscribeGeneralAudio(temp_right_path, **final_bp_params)
        else: # Piano-Specific
            midi_path_left = TranscribePianoAudio(temp_left_path)
            midi_path_right = TranscribePianoAudio(temp_right_path)
        
        if midi_path_left and midi_path_right:
            merged_midi_path = os.path.join(temp_dir, f"{base_name}_merged.mid")
            return merge_midis(midi_path_left, midi_path_right, merged_midi_path), final_bp_params
        elif midi_path_left:
            print("Warning: Right channel transcription failed. Using left channel only.")
            return midi_path_left, final_bp_params
        elif midi_path_right:
            print("Warning: Left channel transcription failed. Using right channel only.")
            return midi_path_right, final_bp_params
        else:
            print(f"Warning: Stereo transcription failed for stem {base_name}.")
            return None, {}
    else:
        print("Mono processing for stem.")
        mono_signal_np = np.mean(audio_data, axis=0) if audio_data.ndim > 1 else audio_data
        normalized_mono = normalize_loudness(mono_signal_np, native_sample_rate)
        temp_mono_path = os.path.join(temp_dir, f"{base_name}_mono.flac")
        sf.write(temp_mono_path, normalized_mono, native_sample_rate)
        
        if params.transcription_method == "General Purpose":
            return TranscribeGeneralAudio(temp_mono_path, **final_bp_params), final_bp_params
        else:
            # For piano, there are no bp_params, so we return an empty dict
            return TranscribePianoAudio(temp_mono_path), {}


# --- The core processing engine for a single file ---
def run_single_file_pipeline(input_file_path: str, timestamp: str, params: AppParameters, progress: gr.Progress = None):
    """
    This is the main processing engine. It takes a file path and a dictionary of all settings,
    and performs the full pipeline: load, separate, transcribe, render, re-merge.
    It is UI-agnostic and returns file paths and data, not Gradio updates.
    It now accepts a Gradio Progress object to report granular progress.
    """
    # Helper function to safely update progress
    def update_progress(fraction, desc):
        if progress:
            progress(fraction, desc=desc)

    # --- Start timer for this specific file ---
    file_start_time = reqtime.time()

    filename = os.path.basename(input_file_path)
    base_name = os.path.splitext(filename)[0]
    
    # --- Determine file type to select the correct progress timeline ---
    is_midi_input = filename.lower().endswith(('.mid', '.midi', '.kar'))
    
    update_progress(0, f"Starting: {filename}")
    print(f"\n{'='*20} Starting Pipeline for: {filename} {'='*20}")

    # --- Use the provided timestamp for unique filenames ---
    timestamped_base_name = f"{base_name}_{timestamp}"
    
    # --- Dictionary to log parameters for each transcribed stem ---
    transcription_params_log = {}
    
    # --- Step 1: Check file type and transcribe if necessary ---
    if is_midi_input:
        # For MIDI files, we start at 0% and directly proceed to the rendering steps.
        update_progress(0, "MIDI file detected, skipping transcription...")
        print("MIDI file detected. Skipping transcription. Proceeding directly to rendering.")

        if is_stereo_midi(input_file_path):
            print("\nINFO: Stereo pan information (Left/Right) detected in the input MIDI. It will be rendered in stereo.\n")

        midi_path_for_rendering = input_file_path
    else:
        temp_dir = os.path.join("output", "temp_transcribe") # Define temp_dir early for the fallback
        os.makedirs(temp_dir, exist_ok=True)

        # --- Audio Loading ---
        update_progress(0.1, "Audio file detected, loading...")
        print("Audio file detected. Starting pre-processing...")
        # --- Robust audio loading with ffmpeg fallback ---
        try:
            # Try loading directly with torchaudio (efficient for supported formats).
            # This works for formats like WAV, MP3, FLAC, OGG, etc.
            print("Attempting to load audio with torchaudio...")
            audio_tensor, native_sample_rate = torchaudio.load(input_file_path)
            print("Torchaudio loading successful.")
        except Exception as e:
            update_progress(0.15, "Torchaudio failed, trying ffmpeg...")
            print(f"Torchaudio failed: {e}. Attempting fallback with ffmpeg...")
            try:
                # Define a path for the temporary converted file
                converted_flac_path = os.path.join(temp_dir, f"{timestamped_base_name}_converted.flac")
                # Use ffmpeg to convert the input file to a clean FLAC file on disk
                (
                    ffmpeg
                    .input(input_file_path)
                    .output(converted_flac_path, acodec='flac')
                    .overwrite_output()
                    .run(capture_stdout=True, capture_stderr=True)
                )
                # Now, load the newly created and guaranteed-to-be-compatible FLAC file
                audio_tensor, native_sample_rate = torchaudio.load(converted_flac_path)
                print(f"FFmpeg fallback successful. Loaded from: {converted_flac_path}")
            except Exception as ffmpeg_err:
                # In batch mode, we just print an error and skip this file
                stderr = ffmpeg_err.stderr.decode() if hasattr(ffmpeg_err, 'stderr') else str(ffmpeg_err)
                print(f"ERROR: Could not load {filename}. Skipping. FFmpeg error: {stderr}")
                return None # Return None to indicate failure
        
        # --- Vocal Separation Logic ---
        # This block now handles multi-stem separation, transcription, and merging logic.
        separated_stems = {} # This will store the audio tensors for merging
        sources = {} # This will hold the tensors for transcription processing

        if params.separate_vocals:
            model_name = params.separation_model
            
            # --- Demucs Separation Workflow (4-stem) ---
            if 'Demucs' in model_name and demucs_model is not None:
                update_progress(0.2, "Separating audio with Demucs...")
                # Convert to the format Demucs expects (e.g., 44.1kHz, stereo)
                audio_tensor_demucs = convert_audio(audio_tensor, native_sample_rate, demucs_model.samplerate, demucs_model.audio_channels)
                # Move tensor to GPU if available for faster processing
                if torch.cuda.is_available():
                    audio_tensor_demucs = audio_tensor_demucs.cuda()

                print("Separating audio with Demucs... This may take some time.")
                # --- Wrap the model call in a no_grad() context ---
                with torch.no_grad():
                    all_stems = apply_model(
                        demucs_model,
                        audio_tensor_demucs[None], # The input shape is [batch, channels, samples]
                        device='cuda' if torch.cuda.is_available() else 'cpu',
                        progress=True
                    )[0] # Remove the batch dimension from the output
                
                # --- Clear CUDA cache immediately after use ---
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
                    print("CUDA cache cleared.")
                
                # Populate sources for transcription and separated_stems for merging
                sources = {name: stem for name, stem in zip(demucs_model.sources, all_stems)}

                # --- Store original stems for potential re-merging ---
                for name, tensor in sources.items():
                    separated_stems[name] = (tensor.cpu(), demucs_model.samplerate)

            # --- RoFormer Separation Workflow (2-stem) ---
            elif ('BS-RoFormer' in model_name or 'Mel-RoFormer' in model_name):
                if not separator_models:
                    print("Warning: RoFormer models are not loaded. Skipping separation.")
                    params.separate_vocals = False
                else:
                    roformer_key = 'BS-RoFormer' if 'BS-RoFormer' in model_name else 'Mel-RoFormer'
                    update_progress(0.2, f"Separating audio with {roformer_key}...")

                    temp_input_path = os.path.join(temp_dir, f"{timestamped_base_name}_roformer_in.flac")
                    torchaudio.save(temp_input_path, audio_tensor.cpu(), native_sample_rate)
                    
                    try:
                        separator = separator_models[roformer_key]
                        output_paths = separator.separate(temp_input_path)

                        vocals_path, accompaniment_path = None, None
                        for path in output_paths:
                            basename = os.path.basename(path).lower()
                            path = os.path.join(temp_dir, path)
                            if '(vocals)' in basename:
                                vocals_path = path
                            elif '(instrumental)' in basename:
                                accompaniment_path = path
                        
                        if not vocals_path or not accompaniment_path:
                            raise RuntimeError(f"Could not find expected vocal/instrumental stems in output: {output_paths}")

                        print(f"Separation complete. Vocals: {os.path.basename(vocals_path)}, Accompaniment: {os.path.basename(accompaniment_path)}")

                        vocals_tensor, stem_sr = torchaudio.load(vocals_path)
                        accompaniment_tensor, stem_sr = torchaudio.load(accompaniment_path)

                        # Populate 'sources' and 'separated_stems' to match Demucs structure
                        # This ensures compatibility with downstream logic
                        sources['vocals'] = vocals_tensor
                        sources['other'] = accompaniment_tensor # The entire accompaniment
                        sources['drums'] = torch.zeros_like(accompaniment_tensor) # Dummy tensor
                        sources['bass'] = torch.zeros_like(accompaniment_tensor)  # Dummy tensor

                        for name, tensor in sources.items():
                            separated_stems[name] = (tensor.cpu(), stem_sr)

                    except Exception as e:
                        print(f"ERROR: {roformer_key} separation failed: {e}. Skipping separation.")
                        params.separate_vocals = False

        # --- Prepare Stems for Transcription ---
        if params.separate_vocals and sources: # Check if separation was successful
            stems_to_transcribe = {}
            # NOTE: When a 2-stem model is used, the UI should ensure 'enable_advanced_separation' is False.
            if params.enable_advanced_separation:
                # User is in advanced mode (Demucs only)
                if params.transcribe_vocals:
                    stems_to_transcribe['vocals'] = sources['vocals']
                if params.transcribe_drums:
                    stems_to_transcribe['drums'] = sources['drums']
                if params.transcribe_bass:
                    stems_to_transcribe['bass'] = sources['bass']
                if params.transcribe_other_or_accompaniment:
                    stems_to_transcribe['other'] = sources['other']
            else:
                # Simple mode (Demucs) or RoFormer mode
                # This logic correctly combines drums, bass, and other. For RoFormer, drums/bass are zero,
                # so this correctly results in just the accompaniment tensor.
                accompaniment_tensor = sources['drums'] + sources['bass'] + sources['other']
                if params.transcribe_vocals:
                    stems_to_transcribe['vocals'] = sources['vocals']
                if params.transcribe_other_or_accompaniment:
                    stems_to_transcribe['accompaniment'] = accompaniment_tensor
            
            # --- Transcribe Selected Stems ---
            transcribed_midi_paths = []
            if stems_to_transcribe:
                stem_count = len(stems_to_transcribe)
                # The samplerate of all stems from a single separation will be the same
                stem_samplerate = separated_stems.get('vocals', (None, native_sample_rate))[1]

                for i, (name, tensor) in enumerate(stems_to_transcribe.items()):
                    update_progress(0.3 + (0.3 * (i / stem_count)), f"Transcribing stem: {name}...")
                    stem_path = os.path.join(temp_dir, f"{timestamped_base_name}_{name}.flac")
                    torchaudio.save(stem_path, tensor.cpu(), stem_samplerate)
                    midi_path, used_bp_params = _transcribe_stem(stem_path, f"{timestamped_base_name}_{name}", temp_dir, params)
                    if midi_path:
                        transcribed_midi_paths.append((name, midi_path))
                        # --- Log the used parameters for this specific stem ---
                        if used_bp_params:
                            # Also log which preset was active for this stem
                            used_bp_params['preset_selector_mode'] = params.basic_pitch_preset_selector
                            transcription_params_log[name] = used_bp_params
                        
            # --- Merge Transcribed MIDIs ---
            if not transcribed_midi_paths:
                raise gr.Error("Separation was enabled, but no stems were selected for transcription, or transcription failed.")
            elif len(transcribed_midi_paths) == 1:
                midi_path_for_rendering = transcribed_midi_paths[0][1]
            else:
                update_progress(0.6, "Merging transcribed MIDIs...")
                merged_midi = pretty_midi.PrettyMIDI()
                for name, path in transcribed_midi_paths:
                    try:
                        midi_stem = pretty_midi.PrettyMIDI(path)
                        for inst in midi_stem.instruments:
                            inst.name = f"{name.capitalize()} - {inst.name}"
                            merged_midi.instruments.append(inst)
                    except Exception as e:
                        print(f"Warning: Could not merge MIDI for stem {name}. Error: {e}")
                final_merged_midi_path = os.path.join(temp_dir, f"{timestamped_base_name}_full_transcription.mid")
                merged_midi.write(final_merged_midi_path)
                midi_path_for_rendering = final_merged_midi_path
        
        else: # Standard workflow without separation
            # --- Standard Workflow: Transcribe the original full audio ---
            audio_to_transcribe_path = os.path.join(temp_dir, f"{timestamped_base_name}_original.flac")
            torchaudio.save(audio_to_transcribe_path, audio_tensor, native_sample_rate)

            update_progress(0.2, "Transcribing audio to MIDI...")
            midi_path_for_rendering, used_bp_params = _transcribe_stem(audio_to_transcribe_path, f"{timestamped_base_name}_original", temp_dir, params)

            # --- Populate the log in this workflow as well ---
            if used_bp_params:
                used_bp_params['preset_selector_mode'] = params.basic_pitch_preset_selector
                # Use a standard key like "full_mix" for the log
                transcription_params_log["full_mix"] = used_bp_params
                print("  - Logged transcription parameters for the full mix.")

    if not midi_path_for_rendering or not os.path.exists(midi_path_for_rendering):
        print(f"ERROR: Transcription failed for {filename}. Skipping.")
        return None

    # --- Step 2: Render the FINAL MIDI file with selected options ---
    # The progress values are now conditional based on the input file type.
    update_progress(0.1 if is_midi_input else 0.6, "Applying MIDI transformations...")
    
    # --- Auto-Recommendation Logic ---
    # If the user selected the auto-recommend option, override the parameters
    if params.s8bit_preset_selector == "Auto-Recommend (Analyze MIDI)":
        update_progress(0.15 if is_midi_input else 0.65, "Auto-recommending 8-bit parameters...")
        print("Auto-Recommendation is enabled. Analyzing MIDI features...")
        try:
            midi_to_analyze = pretty_midi.PrettyMIDI(midi_path_for_rendering)
            default_preset = S8BIT_PRESETS[FALLBACK_PRESET_NAME]
            recommended_params = recommend_8bit_params(midi_to_analyze, default_preset)

            print("Recommended parameters:", recommended_params)
            # Update the params object *before* the main pipeline runs
            for key, value in recommended_params.items():
                setattr(params, f"s8bit_{key}", value)
            print("Parameters updated with recommendations.")
        except Exception as e:
            print(f"Could not auto-recommend parameters for {filename}: {e}.")
            
    # --- Step 2: Render the FINAL MIDI file ---
    update_progress(0.2 if is_midi_input else 0.7, "Rendering MIDI to audio...")
    print(f"Proceeding to render MIDI file: {os.path.basename(midi_path_for_rendering)}")

    # Call the rendering function, Pass dictionaries directly to Render_MIDI
    results_tuple = Render_MIDI(input_midi_path=midi_path_for_rendering, params=params, progress=progress)
    
    # --- Final Audio Merging Logic ---
    stems_to_merge = []
    if params.separate_vocals and separated_stems:
        if params.merge_vocals_to_render and 'vocals' in separated_stems:
            stems_to_merge.append(separated_stems['vocals'])
        
        if params.enable_advanced_separation:
            if params.merge_drums_to_render and 'drums' in separated_stems:
                stems_to_merge.append(separated_stems['drums'])
            if params.merge_bass_to_render and 'bass' in separated_stems:
                stems_to_merge.append(separated_stems['bass'])
            if params.merge_other_or_accompaniment and 'other' in separated_stems:
                stems_to_merge.append(separated_stems['other'])
        else: # Simple mode or RoFormer
            if params.merge_other_or_accompaniment:
                # This correctly combines the accompaniment, which for RoFormer is just the 'other' stem.
                accompaniment_tensor = separated_stems['drums'][0] + separated_stems['bass'][0] + separated_stems['other'][0]
                accompaniment_sr = separated_stems['other'][1]
                stems_to_merge.append((accompaniment_tensor, accompaniment_sr))
    
    if stems_to_merge:
        update_progress(0.9, "Re-merging audio stems...")
        rendered_srate, rendered_music_int16 = results_tuple[4]
        rendered_music_float = rendered_music_int16.astype(np.float32) / 32767.0
        final_mix_tensor = torch.from_numpy(rendered_music_float).T
        final_srate = rendered_srate
        
        for stem_tensor, stem_srate in stems_to_merge:
            # Resample if necessary
            if stem_srate != final_srate:
                # Resample all stems to match the rendered audio's sample rate
                resampler = torchaudio.transforms.Resample(stem_srate, final_srate)
                stem_tensor = resampler(stem_tensor)
            
            # Ensure stem is stereo if mix is stereo
            if final_mix_tensor.shape[0] == 2 and stem_tensor.shape[0] == 1:
                stem_tensor = stem_tensor.repeat(2, 1)
                
            # Pad and add to the final mix
            len_mix = final_mix_tensor.shape[1]
            len_stem = stem_tensor.shape[1]
            if len_mix > len_stem:
                stem_tensor = torch.nn.functional.pad(stem_tensor, (0, len_mix - len_stem))
            elif len_stem > len_mix:
                final_mix_tensor = torch.nn.functional.pad(final_mix_tensor, (0, len_stem - len_mix))
            
            final_mix_tensor += stem_tensor
            
        # Normalize final mix to prevent clipping
        max_abs = torch.max(torch.abs(final_mix_tensor))
        if max_abs > 1.0: final_mix_tensor /= max_abs
        
        # Convert back to the required format (int16 numpy array)
        merged_audio_int16 = (final_mix_tensor.T.numpy() * 32767).astype(np.int16)
        
        # Update the results tuple with the newly merged audio
        temp_results_list = list(results_tuple)
        temp_results_list[4] = (final_srate, merged_audio_int16)
        results_tuple = tuple(temp_results_list) # results_tuple is now updated
        print("Re-merging complete.")
        
    # --- Save final audio and return path ---
    update_progress(0.95, "Saving final files...")
    final_srate, final_audio_data = results_tuple[4]
    final_midi_path_from_render = results_tuple[3] # Get the path of the processed MIDI
    
    # --- Use timestamped names for final outputs ---
    output_audio_dir = os.path.join("output", "final_audio")
    output_midi_dir = os.path.join("output", "final_midi")
    os.makedirs(output_audio_dir, exist_ok=True)
    os.makedirs(output_midi_dir, exist_ok=True)

    final_audio_path = os.path.join(output_audio_dir, f"{timestamped_base_name}_rendered.flac")
    # Also, copy the final processed MIDI to a consistent output directory with a timestamped name
    final_midi_path = os.path.join(output_midi_dir, f"{timestamped_base_name}_processed.mid")

    # --- Save audio with embedded parameter metadata ---
    try:
        # Generate the metadata string from the final parameters used for the render.
        metadata_string = format_params_for_metadata(params, transcription_params_log)
        
        sf.write(final_audio_path, final_audio_data, final_srate)
        audio = FLAC(final_audio_path)
        audio["comment"] = metadata_string
        audio.save()
        
        print(f"  - Successfully saved audio with embedded parameters to {os.path.basename(final_audio_path)}")

    except Exception as e:
        print(f"  - Warning: Could not save audio with metadata. Error: {e}")
        print("  - Falling back to standard save method.")
        # Fallback to the original simple write method if the advanced one fails.
        sf.write(final_audio_path, final_audio_data, final_srate)

    # Use shutil to copy the final midi file to its new home
    shutil.copy(final_midi_path_from_render, final_midi_path)
    
    
    # --- Log the processing time for this specific file at the end ---
    file_processing_time = reqtime.time() - file_start_time
    print(f"--- Pipeline finished for {filename} in {file_processing_time:.2f} seconds. ---")
    print(f"Output Audio: {final_audio_path}\nOutput MIDI: {final_midi_path}")
    
    # Return a dictionary of all results for the wrappers to use
    results = {
        "final_audio_path": final_audio_path,
        "final_midi_path": final_midi_path,
        "md5_hash": results_tuple[0],
        "title": results_tuple[1],
        "summary": results_tuple[2],
        "plot": results_tuple[5],
        "description": results_tuple[6]
    }
    update_progress(1.0, "Done!")
    # Return both the results and the final state of the parameters object
    return results, params


# =================================================================================================
# === Gradio UI Wrappers ===
# =================================================================================================

class BatchProgressTracker:
    """
    A custom progress tracker for batch processing that can update a main
    progress bar and also create its own tqdm-style sub-progress bars.
    """
    def __init__(self, main_progress: gr.Progress, total_files: int, current_file_index: int, filename: str):
        self._main_progress = main_progress
        self._total_files = total_files
        self._current_file_index = current_file_index
        self._filename = filename
        self._progress_per_file = 1 / total_files if total_files > 0 else 0

    def __call__(self, local_fraction: float, desc: str = ""):
        """Makes the object callable like a function for simple progress updates."""
        overall_fraction = (self._current_file_index / self._total_files) + (local_fraction * self._progress_per_file)
        full_desc = f"({self._current_file_index + 1}/{self._total_files}) {self._filename}: {desc}"
        # Update the main progress bar
        self._main_progress(overall_fraction, desc=full_desc)

    def tqdm(self, iterable, desc="", total=None):
        """Provides a tqdm method that delegates to the original gr.Progress object."""
        # The description for the sub-progress bar
        tqdm_desc = f"({self._current_file_index + 1}/{self._total_files}) {self._filename}: {desc}"
        # Use the original gr.Progress object to create the tqdm iterator
        return self._main_progress.tqdm(iterable, desc=tqdm_desc, total=total)

# --- Thin wrapper for batch processing ---
def batch_process_files(input_files, progress=gr.Progress(track_tqdm=True), *args):
    """
    Gradio wrapper for batch processing. It iterates through files, calls the core pipeline,
    and collects the output file paths. It now provides detailed, nested progress updates.
    """
    
    if not input_files:
        print("No files uploaded for batch processing.")
        return [], [] # Return two empty lists
    
    # --- Start timer for the entire batch ---
    batch_start_time = reqtime.time()

    # --- Generate a single timestamp for the entire batch job ---
    batch_timestamp = reqtime.strftime("%Y%m%d-%H%M%S")
    
    # Create the AppParameters object from the flat list of UI values
    params = AppParameters(**dict(zip(ALL_PARAM_KEYS, args)))

    output_audio_paths = []
    output_midi_paths = [] # List to collect MIDI file paths
    total_files = len(input_files)

    # Initialize progress at 0%
    progress(0, desc="Starting Batch Process...")
    for i, file_obj in enumerate(input_files):
        # The input from gr.File is a tempfile object, we need its path
        input_path = file_obj.name
        filename = os.path.basename(input_path)
        
        # --- Use the new BatchProgressTracker class ---
        # Instead of a simple function, create an instance of our tracker class.
        # This object can both update the main progress and has a .tqdm method.
        batch_progress_tracker = BatchProgressTracker(
            main_progress=progress,
            total_files=total_files,
            current_file_index=i,
            filename=filename
        )
        
        # --- Pass the batch_timestamp to the pipeline ---
        results, _ = run_single_file_pipeline(input_path, batch_timestamp, copy.copy(params), progress=batch_progress_tracker)
        
        if results:
            if results.get("final_audio_path"):
                output_audio_paths.append(results["final_audio_path"])
            if results.get("final_midi_path"):
                output_midi_paths.append(results["final_midi_path"]) # Collect MIDI path
    
    # Ensure the progress bar reaches 100% upon completion
    progress(1, desc="Batch Process Complete!")
    
    # --- Calculate and print the total batch time ---
    total_batch_time = reqtime.time() - batch_start_time
    print(f"\nBatch processing complete. {len(output_audio_paths)} of {total_files} files processed successfully.")
    print(f"Total batch execution time: {total_batch_time:.2f} seconds.")

    # --- Return both lists of paths ---
    return output_audio_paths, output_midi_paths


# --- The original function is now a thin wrapper for the single file UI ---
def process_and_render_file(input_file, *args, progress=gr.Progress()):
    """
    Gradio wrapper for the single file processing UI. Packs UI values into an AppParameters object.
    Calls the core pipeline and formats the output for all UI components.
    Main function to handle file processing. It determines the file type and calls the
    appropriate functions for transcription and/or rendering based on user selections.
    Now includes a progress bar.
    """
    if input_file is None:
        # Return a list of updates to clear all output fields and UI controls
        return [gr.update(value=None)] * (7 + 14) # 7 results + 14 UI controls (13 synth + 1 preset selector)
    
    # --- Start timer for the single file job ---
    job_start_time = reqtime.time()

    # --- Generate a timestamp for this single job ---
    single_file_timestamp = reqtime.strftime("%Y%m%d-%H%M%S")
    
    # Create the AppParameters object from the flat list of UI values
    # The first value in *args is s8bit_preset_selector, the rest match the keys
    params = AppParameters(input_file=input_file, **dict(zip(ALL_PARAM_KEYS, args)))

    # Run the core pipeline, passing the timestamp and progress to the pipeline
    results, final_params = run_single_file_pipeline(input_file, single_file_timestamp, params, progress=progress)

    if results is None:
        raise gr.Error("File processing failed. Check console for details.")
    
    # --- Calculate and print the total job time ---
    total_job_time = reqtime.time() - job_start_time
    print(f"Total single-file job execution time: {total_job_time:.2f} seconds.")
    
    # --- Prepare UI updates using the returned final_params ---
    # This ensures the UI always reflects the parameters that were actually used for the render.
    final_ui_updates = []

    # Logic to decide what the preset selector should show after the run
    if params.s8bit_preset_selector == "Auto-Recommend (Analyze MIDI)":
        # After auto-recommendation, the state becomes "Custom"
        final_ui_updates.append(gr.update(value="Custom"))
    else:
        # Otherwise, just keep the user's current selection
        final_ui_updates.append(gr.update(value=final_params.s8bit_preset_selector))

    # Get the keys for the 13 synthesizer controls (excluding the preset selector itself)
    s8bit_control_keys = [key for key in ALL_PARAM_KEYS if key.startswith('s8bit_') and key != 's8bit_preset_selector']

    # Always update all 13 controls to match the final parameters used in the backend
    for key in s8bit_control_keys:
        value = getattr(final_params, key)
        # Explicitly convert numpy numeric types to native Python types.
        # This prevents them from being serialized as strings in the UI,
        # which would cause a TypeError on the next run.
        if isinstance(value, np.generic):
            value = value.item()
        final_ui_updates.append(value)

    # Format the main results for the output components
    main_results = [
        results['md5_hash'], results['title'], results['summary'],
        results['final_midi_path'], results['final_audio_path'],
        results['plot'], results['description']
    ]

    # The total return list now has a consistent structure and logic
    return main_results + final_ui_updates


# =================================================================================================
# === Gradio UI Setup ===
# =================================================================================================

if __name__ == "__main__":
    # Initialize the app: download model (if needed) and apply patches
    # Set to False if you don't have 'requests' or 'tqdm' installed
    initialize_app()
    
    # --- Prepare soundfonts and make the map globally accessible ---
    global soundfonts_dict, demucs_model, separator_models
    # On application start, download SoundFonts from Hugging Face Hub if they don't exist.
    soundfonts_dict = prepare_soundfonts()
    print(f"Found {len(soundfonts_dict)} local SoundFonts.")

    if not soundfonts_dict:
        print("\nWARNING: No SoundFonts were found or could be downloaded.")
        print("Rendering with SoundFonts will fail. Only the 8-bit synthesizer will be available.")

    # --- Pre-load the Demucs model on startup for efficiency ---
    print("Loading Demucs model (htdemucs_ft), this may take a moment on first run...")
    try:
        demucs_model = get_model(name='htdemucs_ft')
        if torch.cuda.is_available():
            demucs_model = demucs_model.cuda()
        print("Demucs model loaded successfully.")
    except Exception as e:
        print(f"Warning: Could not load Demucs model. Vocal separation will not be available. Error: {e}")
        demucs_model = None

    # --- Pre-load BS-RoFormer and Mel-RoFormer models ---
    separator_models: dict[str, Separator] = {}
    try:
        temp_dir = os.path.join("output", "temp_transcribe")
        print("Loading BS-RoFormer model...")
        bs_roformer = Separator(output_dir=temp_dir, output_format='flac', model_file_dir=os.path.join("src", "models"))
        bs_roformer.load_model("model_bs_roformer_ep_317_sdr_12.9755.ckpt")
        separator_models['BS-RoFormer'] = bs_roformer
        print("BS-RoFormer model loaded successfully.")

        print("Loading Mel-RoFormer model...")
        mel_roformer = Separator(output_dir=temp_dir, output_format='flac', model_file_dir=os.path.join("src", "models"))
        mel_roformer.load_model("model_mel_band_roformer_ep_3005_sdr_11.4360.ckpt")
        separator_models['Mel-RoFormer'] = mel_roformer
        print("Mel-RoFormer model loaded successfully.")

    except Exception as e:
        print(f"Warning: Could not load RoFormer models. They will not be available for separation. Error: {e}")
        
    # --- Dictionary containing descriptions for each render type ---
    RENDER_TYPE_DESCRIPTIONS = {
        "Render as-is": "**Mode: Pass-through.** Renders the MIDI file directly without any modifications. Advanced MIDI options will be ignored.",
        "Custom render": "**Mode: Activate Advanced Options.** Applies all settings from the 'Advanced MIDI Rendering Options' accordion without making other structural changes to the MIDI.",
        "Extract melody": "**Action: Simplify.** Analyzes all tracks and attempts to isolate and render only the main melody line.",
        "Flip": "**Action: Experimental.** Inverts the pitch of each note around the song's average pitch.",
        "Reverse": "**Action: Experimental.** Reverses the playback order of all notes in the MIDI file.",
        "Repair Durations": "**Action: Fix.** Recalculates note durations to ensure they connect smoothly (legato), filling any small gaps.",
        "Repair Chords": "**Action: Fix.** Analyzes and aligns notes that occur at similar times to form cleaner, more structured chords.",
        "Remove Duplicate Pitches": "**Action: Simplify.** If multiple instruments play the exact same pitch at the same time, it keeps only one.",
        "Longest Repeating Phrase": "**Action: Analyze.** Finds the longest, most-repeated musical phrase (often the chorus) and renders only that section.",
        "Multi-Instrumental Summary": "**Action: AI Summary.** Creates a short, compressed summary of a complex, multi-instrument song.",
        "Solo Piano Summary": "**Action: AI Summary.** First converts the song to a solo piano arrangement, then creates a short, compressed summary.",
        "Add Drum Track": "**Action: Enhance.** Analyzes the rhythm of the MIDI and automatically generates a basic drum track to accompany it."
    }

    # --- Define a constant for the fallback preset name ---
    # This prevents errors if the preset name is changed in the dictionary.
    FALLBACK_PRESET_NAME = "Generic Chiptune Loop"

    # --- Data structure for 8-bit synthesizer presets ---
    # Comprehensive preset dictionary with new FX parameters for all presets
    # Comprehensive preset dictionary including new JRPG and Handheld classics
    # Note: Vibrato depth is mapped to a representative value on the 0-50 Hz slider.
    S8BIT_PRESETS = {
        # --- Classic Chiptune ---
        "Mario (Super Mario Bros / スーパーマリオブラザーズ)": {
            # Description: A bright square wave with a per-note vibrato, producing the classic bouncy platformer sound.
            'waveform_type': 'Square', 'pulse_width': 0.3, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.25,
            'vibrato_rate': 5.0, 'vibrato_depth': 5,
            'smooth_notes_level': 0.8,
            'continuous_vibrato_level': 0.25,
            'bass_boost_level': 0.2, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Mega Man (Rockman / ロックマン)": {
            # Description: A thin, sharp square wave lead with fast vibrato, iconic for its driving, heroic melodies.
            'waveform_type': 'Square', 'pulse_width': 0.2, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.15,
            'vibrato_rate': 6.0, 'vibrato_depth': 8,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.85,
            'bass_boost_level': 0.3, 'noise_level': 0.0, 'distortion_level': 0.05,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Zelda (The Legend of Zelda / ゼルダの伝説)": {
            # Description: The classic pure triangle wave lead, perfect for heroic and adventurous overworld themes.
            'waveform_type': 'Triangle', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.3,
            'vibrato_rate': 4.5, 'vibrato_depth': 4,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.9,
            'bass_boost_level': 0.15, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Kirby's Bubbly Melody (Hoshi no Kirby / 星のカービィ)": {
            # Description: A soft, round square wave with a bouncy vibrato, creating a cheerful and adorable sound.
            'waveform_type': 'Square', 'pulse_width': 0.4, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.2,
            'vibrato_rate': 6.0, 'vibrato_depth': 4,
            'smooth_notes_level': 0.85,
            'continuous_vibrato_level': 0.3,   # Formerly False (0.0); adds a hint of continuity for more liveliness.
            'bass_boost_level': 0.1, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Pokémon (Game Boy Classics / ポケットモンスター)": {
            # Description: A full, friendly square wave sound, capturing the cheerful and adventurous spirit of early handheld RPGs.
            'waveform_type': 'Square', 'pulse_width': 0.5, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.22,
            'vibrato_rate': 5.0, 'vibrato_depth': 5,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.9,
            'bass_boost_level': 0.25, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Castlevania (Akumajō Dracula / 悪魔城ドラキュラ)": {
            # Description: A sharp square wave with dramatic vibrato, ideal for fast, gothic, and baroque-inspired melodies.
            'waveform_type': 'Square', 'pulse_width': 0.25, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.18,
            'vibrato_rate': 6.5, 'vibrato_depth': 6,
            'smooth_notes_level': 0.85,
            'continuous_vibrato_level': 0.85,
            'bass_boost_level': 0.35, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Final Fantasy (Arpeggio / ファイナルファンタジー)": {
            # Description: A perfect, clean square wave with zero vibrato, creating the iconic, crystal-clear arpeggio sound.
            'waveform_type': 'Square', 'pulse_width': 0.5, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.22,
            'vibrato_rate': 5.0, 'vibrato_depth': 0,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.2,
            'bass_boost_level': 0.2, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "ONI V (Wafu Mystic / ONI V 隠忍を継ぐ者)": {
            # Description: A solemn triangle wave with a slow, expressive vibrato, evoking the mysterious atmosphere of Japanese folklore.
            'waveform_type': 'Triangle', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.4,
            'vibrato_rate': 3.5, 'vibrato_depth': 3,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.85,
            'bass_boost_level': 0.4, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        # --- Advanced System Impressions ---
        "Commodore 64 (SID Feel)": {
            # Description: (Impression) Uses high-speed, shallow vibrato to mimic the characteristic "buzzy" texture of the SID chip's PWM.
            'waveform_type': 'Square', 'pulse_width': 0.25, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.25,
            'vibrato_rate': 8.0, 'vibrato_depth': 4,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.3,
            'bass_boost_level': 0.2, 'noise_level': 0.05, 'distortion_level': 0.1,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Megadrive/Genesis (FM Grit)": {
            # Description: (Impression) Uses FM, distortion, and noise to capture the gritty, metallic, and aggressive tone of the YM2612 chip.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.18,
            'vibrato_rate': 0.0, 'vibrato_depth': 0,
            'smooth_notes_level': 0.0,
            'continuous_vibrato_level': 0.9,
            'bass_boost_level': 0.4, 'noise_level': 0.1, 'distortion_level': 0.2,
            'fm_modulation_depth': 0.2, 'fm_modulation_rate': 150
        },
        "PC-98 (Touhou Feel / 東方Project)": {
            # Description: (Impression) A very sharp square wave with fast FM, emulating the bright, high-energy leads of Japanese PC games.
            'waveform_type': 'Square', 'pulse_width': 0.15, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.12,
            'vibrato_rate': 7.5, 'vibrato_depth': 7,
            'smooth_notes_level': 0.95,
            'continuous_vibrato_level': 0.85,
            'bass_boost_level': 0.3, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.1, 'fm_modulation_rate': 200
        },
        "Roland SC-88 (GM Vibe)": {
            # Description: (Impression) A clean, stable triangle wave with no effects, mimicking the polished, sample-based sounds of General MIDI.
            'waveform_type': 'Triangle', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.35,
            'vibrato_rate': 0, 'vibrato_depth': 0,
            'smooth_notes_level': 1.0,
            'continuous_vibrato_level': 0.0,
            'bass_boost_level': 0.1, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        # --- Action & Rock Leads ---
        "Falcom Ys (Rock Lead / イース)": {
            # Description: A powerful sawtooth with slight distortion, emulating the driving rock organ and guitar leads of action JRPGs.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.15,
            'vibrato_rate': 5.5, 'vibrato_depth': 6,
            'smooth_notes_level': 0.85,
            'continuous_vibrato_level': 0.8,
            'bass_boost_level': 0.4, 'noise_level': 0.05, 'distortion_level': 0.15,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Arcade Brawler Lead (Street Fighter / ストリートファイター)": {
            # Description: A gritty sawtooth lead with a hard attack, capturing the high-energy feel of classic fighting games.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.15,
            'vibrato_rate': 5.0, 'vibrato_depth': 6,
            'smooth_notes_level': 0.8,
            'continuous_vibrato_level': 0.7,
            'bass_boost_level': 0.4, 'noise_level': 0.05, 'distortion_level': 0.1,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Rhythm Pop Lead (Rhythm Tengoku / リズム天国)": {
            # Description: A clean, round square wave perfect for the snappy, catchy feel of rhythm games.
            'waveform_type': 'Square', 'pulse_width': 0.5, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.18,
            'vibrato_rate': 4.5, 'vibrato_depth': 4,
            'smooth_notes_level': 0.9,          # Formerly True -> 1.0; slightly reduced for a bit more attack.
            'continuous_vibrato_level': 0.8,    # Formerly True -> 1.0; slightly weakened for more defined note transitions.
            'bass_boost_level': 0.3, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        # --- Epic & Orchestral Pads ---
        "Dragon Quest (Orchestral Feel / ドラゴンクエスト)": {
            # Description: A pure triangle wave with a long decay, mimicking the grand, orchestral feel of a classical flute or string section.
            'waveform_type': 'Triangle', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.6,
            'vibrato_rate': 3.0, 'vibrato_depth': 4,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.9,
            'bass_boost_level': 0.3, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Mystic Mana Pad (Secret of Mana / 聖剣伝説2)": {
             # Description: A warm, ethereal square wave pad with slow vibrato, capturing a feeling of fantasy and wonder.
            'waveform_type': 'Square', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.5,
            'vibrato_rate': 2.5, 'vibrato_depth': 4,
            'smooth_notes_level': 1.0,
            'continuous_vibrato_level': 0.95,
            'bass_boost_level': 0.3, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Modern JRPG Pad (Persona / ペルソナ)": {
            # Description: A warm, stylish square wave pad, capturing the modern, pop/jazz-infused feel of the Persona series.
            'waveform_type': 'Square', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.5,
            'vibrato_rate': 2.5, 'vibrato_depth': 4,
            'smooth_notes_level': 1.0,
            'continuous_vibrato_level': 0.95,
            'bass_boost_level': 0.3, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Tactical Brass (Fire Emblem / ファイアーエムブレム)": {
            # Description: A powerful, sustained sawtooth emulating the bold, heroic synth-brass of Fire Emblem's tactical themes.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.4,
            'vibrato_rate': 3.5, 'vibrato_depth': 5,
            'smooth_notes_level': 0.95,
            'continuous_vibrato_level': 0.9,
            'bass_boost_level': 0.5, 'noise_level': 0.1, 'distortion_level': 0.15,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Mecha & Tactics Brass (Super Robot Wars / スーパーロボット大戦)": {
            # Description: A powerful, sustained sawtooth emulating the bold, heroic synth-brass of strategy and mecha anime themes.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.4,
            'vibrato_rate': 3.5, 'vibrato_depth': 5,
            'smooth_notes_level': 0.95,
            'continuous_vibrato_level': 0.9,
            'bass_boost_level': 0.5, 'noise_level': 0.1, 'distortion_level': 0.15,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Dark/Boss Atmosphere (Shin Megami Tensei / 真・女神転生)": {
            # Description: An aggressive sawtooth, inspired by the dark, rock-infused themes of SMT.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.35,
            'vibrato_rate': 7.0, 'vibrato_depth': 12,
            'smooth_notes_level': 0.1,
            'continuous_vibrato_level': 0.0,
            'bass_boost_level': 0.4, 'noise_level': 0.15, 'distortion_level': 0.25,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        # --- Vocal Synthesis ---
        "8-Bit Vocal Lead": {
            # Description: A soft, sustained triangle wave with gentle vibrato to mimic a singing voice.
            'waveform_type': 'Triangle',
            'pulse_width': 0.5,
            'envelope_type': 'Sustained (Full Decay)',
            'decay_time_s': 0.8,
            'vibrato_rate': 5.5,
            'vibrato_depth': 4, # Mapped from the suggested 0.15 range
            'bass_boost_level': 0.1,
            'smooth_notes_level': 0.85,
            'continuous_vibrato_level': 0.9,
            'noise_level': 0.02,
            'distortion_level': 0.0,
            'fm_modulation_depth': 0.05,
            'fm_modulation_rate': 20
        },
        "8-Bit Male Vocal": {
            # Description: A deeper, fuller triangle wave with more bass and slower vibrato for a masculine feel.
            'waveform_type': 'Triangle',           
            'pulse_width': 0.5,
            'envelope_type': 'Sustained (Full Decay)',
            'decay_time_s': 1.0,
            'vibrato_rate': 5.0,
            'vibrato_depth': 3, # Mapped from the suggested 0.12 range
            'bass_boost_level': 0.3,
            'smooth_notes_level': 0.9,             
            'continuous_vibrato_level': 0.85,      
            'noise_level': 0.015,                  
            'distortion_level': 0.0,               
            'fm_modulation_depth': 0.08,
            'fm_modulation_rate': 25               
        },
        "8-Bit Female Vocal": {
            # Description: A brighter, lighter triangle wave with faster vibrato and less bass for a feminine feel.
            'waveform_type': 'Triangle',
            'pulse_width': 0.5,
            'envelope_type': 'Sustained (Full Decay)',
            'decay_time_s': 0.7,
            'vibrato_rate': 6.0,
            'vibrato_depth': 5, # Mapped from the suggested 0.18 range
            'bass_boost_level': 0.05,
            'smooth_notes_level': 0.85,
            'continuous_vibrato_level': 0.92,
            'noise_level': 0.025,
            'distortion_level': 0.0,
            'fm_modulation_depth': 0.04,
            'fm_modulation_rate': 30
        },
        "Lo-Fi Vocal": {
            # Description: A gritty, noisy square wave with a short decay to simulate a low-resolution vocal sample.
            'waveform_type': 'Square',
            'pulse_width': 0.48,
            'envelope_type': 'Plucky (AD Envelope)', # "Short" implies a plucky, not sustained, envelope
            'decay_time_s': 0.4,
            'vibrato_rate': 4.8,
            'vibrato_depth': 2, # Mapped from the suggested 0.10 range
            'bass_boost_level': 0.1,
            'smooth_notes_level': 0.65,
            'continuous_vibrato_level': 0.6,
            'noise_level': 0.05,
            'distortion_level': 0.05,
            'fm_modulation_depth': 0.02,
            'fm_modulation_rate': 20
        },
        # --- Sound FX & Experimental ---
        "Sci-Fi Energy Field": {
            # Description: (SFX) High-speed vibrato and noise create a constant, shimmering hum suitable for energy shields or force fields.
            'waveform_type': 'Triangle', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.4,
            'vibrato_rate': 10.0, 'vibrato_depth': 3,
            'smooth_notes_level': 0.85,
            'continuous_vibrato_level': 0.9,
            'bass_boost_level': 0.1, 'noise_level': 0.1, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.05, 'fm_modulation_rate': 50
        },
        "Industrial Alarm": {
            # Description: (SFX) Extreme vibrato rate on a sawtooth wave produces a harsh, metallic, dissonant alarm sound.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.2,
            'vibrato_rate': 15.0, 'vibrato_depth': 8,
            'smooth_notes_level': 0.0,
            'continuous_vibrato_level': 0.0,
            'bass_boost_level': 0.3, 'noise_level': 0.2, 'distortion_level': 0.3,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Laser Charge-Up": {
            # Description: (SFX) Extreme vibrato depth creates a dramatic, rising pitch effect, perfect for sci-fi weapon sounds.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.3,
            'vibrato_rate': 4.0, 'vibrato_depth': 25,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.95,
            'bass_boost_level': 0.2, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        "Unstable Machine Core": {
            # Description: (SFX) Maximum depth and distortion create a chaotic, atonal noise, simulating a machine on the verge of exploding.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Sustained (Full Decay)', 'decay_time_s': 0.5,
            'vibrato_rate': 1.0, 'vibrato_depth': 50,
            'smooth_notes_level': 0.0,
            'continuous_vibrato_level': 0.9,
            'bass_boost_level': 0.5, 'noise_level': 0.3, 'distortion_level': 0.4,
            'fm_modulation_depth': 0.5, 'fm_modulation_rate': 10
        },
        "Hardcore Gabber Kick": {
            # Description: (Experimental) Maximum bass boost and distortion create an overwhelmingly powerful, clipped kick drum sound.
            'waveform_type': 'Sawtooth', 'pulse_width': 0.5, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.1,
            'vibrato_rate': 0, 'vibrato_depth': 0,
            'smooth_notes_level': 0.0,
            'continuous_vibrato_level': 0.0,
            'bass_boost_level': 0.8, 'noise_level': 0.2, 'distortion_level': 0.5,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
        # --- Utility & Starting Points ---
        "Generic Chiptune Loop": {
            # Description: A well-balanced, pleasant square wave lead that serves as a great starting point for custom sounds.
            'waveform_type': 'Square', 'pulse_width': 0.25, 'envelope_type': 'Plucky (AD Envelope)', 'decay_time_s': 0.2,
            'vibrato_rate': 5.5, 'vibrato_depth': 4,
            'smooth_notes_level': 0.9,
            'continuous_vibrato_level': 0.85,
            'bass_boost_level': 0.25, 'noise_level': 0.0, 'distortion_level': 0.0,
            'fm_modulation_depth': 0.0, 'fm_modulation_rate': 0.0
        },
    }

    # --- Data structure for basic_pitch transcription presets ---
    BASIC_PITCH_PRESETS = {
        # --- General & All-Purpose ---
        "Default (Balanced)": {
            'description': "A good all-around starting point for most music types.",
            'onset_threshold': 0.5, 'frame_threshold': 0.3, 'minimum_note_length': 128,
            'minimum_frequency': 60, 'maximum_frequency': 4000,
            'infer_onsets': True, 'melodia_trick': True, 'multiple_bends': False
        },
        "Anime / J-Pop": {
            'description': "For tracks with clear melodies and pop/rock arrangements.",
            'onset_threshold': 0.5, 'frame_threshold': 0.3, 'minimum_note_length': 150,
            'minimum_frequency': 40, 'maximum_frequency': 2500,
            'infer_onsets': True, 'melodia_trick': True, 'multiple_bends': True
        },
        
        # --- Specific Instruments ---
        "Solo Vocals": {
            'description': "Optimized for a single singing voice. Sensitive to nuances.",
            'onset_threshold': 0.4, 'frame_threshold': 0.3, 'minimum_note_length': 100,
            'minimum_frequency': 80, 'maximum_frequency': 1200,
            'infer_onsets': True, 'melodia_trick': True, 'multiple_bends': True
        },
        "Solo Piano": {
            'description': "For solo piano with a wide dynamic and frequency range.",
            'onset_threshold': 0.4, 'frame_threshold': 0.3, 'minimum_note_length': 120,
            'minimum_frequency': 27, 'maximum_frequency': 4200,
            'infer_onsets': True, 'melodia_trick': True, 'multiple_bends': True
        },
        "Acoustic Guitar": {
            'description': "Balanced for picked or strummed acoustic guitar.",
            'onset_threshold': 0.5, 'frame_threshold': 0.3, 'minimum_note_length': 90,
            'minimum_frequency': 80, 'maximum_frequency': 2500,
            'infer_onsets': True, 'melodia_trick': True, 'multiple_bends': False
        },
        "Bass Guitar": {
            'description': "Isolates and transcribes only the low frequencies of a bassline.",
            'onset_threshold': 0.4, 'frame_threshold': 0.3, 'minimum_note_length': 100,
            'minimum_frequency': 30, 'maximum_frequency': 400,
            'infer_onsets': True, 'melodia_trick': True, 'multiple_bends': False
        },
        "Percussion / Drums": {
            'description': "For drums and rhythmic elements. Catches fast, sharp hits.",
            'onset_threshold': 0.7, 'frame_threshold': 0.6, 'minimum_note_length': 30,
            'minimum_frequency': 40, 'maximum_frequency': 10000,
            'infer_onsets': True, 'melodia_trick': False, 'multiple_bends': False
        },

        # --- Complex Genres ---
        "Rock / Metal": {
            'description': "Higher thresholds for distorted guitars, bass, and drums in a dense mix.",
            'onset_threshold': 0.6, 'frame_threshold': 0.4, 'minimum_note_length': 100,
            'minimum_frequency': 50, 'maximum_frequency': 3000,
            'infer_onsets': True, 'melodia_trick': True, 'multiple_bends': True
        },
        "Jazz (Multi-instrument)": {
            'description': "High thresholds to separate notes in complex, improvisational passages.",
            'onset_threshold': 0.7, 'frame_threshold': 0.5, 'minimum_note_length': 150,
            'minimum_frequency': 55, 'maximum_frequency': 2000,
            'infer_onsets': True, 'melodia_trick': False, 'multiple_bends': True
        },
        "Classical (Orchestral)": {
            'description': "Longer note length to focus on sustained notes and filter out performance noise.",
            'onset_threshold': 0.5, 'frame_threshold': 0.4, 'minimum_note_length': 200,
            'minimum_frequency': 32, 'maximum_frequency': 4200,
            'infer_onsets': True, 'melodia_trick': True, 'multiple_bends': True
        },
        "Electronic / Synth": {
            'description': "Low thresholds and short note length for sharp, synthetic sounds.",
            'onset_threshold': 0.3, 'frame_threshold': 0.2, 'minimum_note_length': 50,
            'minimum_frequency': 20, 'maximum_frequency': 8000,
            'infer_onsets': True, 'melodia_trick': False, 'multiple_bends': False
        }
    }


    # --- UI visibility logic now controls three components ---
    def update_vocal_ui_visibility(separate_vocals):
        """Shows or hides the separation-related UI controls based on selections."""
        is_visible = gr.update(visible=separate_vocals)
        return is_visible, is_visible, is_visible

    def update_ui_visibility(transcription_method, soundfont_choice):
        """
        Dynamically updates the visibility of UI components based on user selections.
        """
        is_general = (transcription_method == "General Purpose")
        is_8bit = (soundfont_choice == SYNTH_8_BIT_LABEL)

        return {
            general_transcription_settings: gr.update(visible=is_general),
            synth_8bit_settings: gr.update(visible=is_8bit),
        }

    # --- Function to control visibility of advanced MIDI rendering options ---
    def update_advanced_midi_options_visibility(render_type_choice):
        """
        Shows or hides the advanced MIDI rendering options based on the render type.
        The options are only visible if the type is NOT 'Render as-is'.
        """
        is_visible = (render_type_choice != "Render as-is")
        return gr.update(visible=is_visible)

    # --- UI controller function to update the description text ---
    def update_render_type_description(render_type_choice):
        """
        Returns the description for the selected render type.
        """
        return RENDER_TYPE_DESCRIPTIONS.get(render_type_choice, "Select a render type to see its description.")

    # --- Controller function to apply basic_pitch presets to the UI ---
    def apply_basic_pitch_preset(preset_name):
        if preset_name not in BASIC_PITCH_PRESETS:
            # If "Custom" is selected or name is invalid, don't change anything
            return {comp: gr.update() for comp in basic_pitch_ui_components}
        
        settings = BASIC_PITCH_PRESETS[preset_name]
        
        # Return a dictionary that maps each UI component to its new value
        return {
            onset_threshold: gr.update(value=settings['onset_threshold']),
            frame_threshold: gr.update(value=settings['frame_threshold']),
            minimum_note_length: gr.update(value=settings['minimum_note_length']),
            minimum_frequency: gr.update(value=settings['minimum_frequency']),
            maximum_frequency: gr.update(value=settings['maximum_frequency']),
            infer_onsets: gr.update(value=settings['infer_onsets']),
            melodia_trick: gr.update(value=settings['melodia_trick']),
            multiple_pitch_bends: gr.update(value=settings['multiple_bends'])
        }

    # --- Function to apply 8-bit synthesizer presets ---
    # --- This function must be defined before the UI components that use it ---
    def apply_8bit_preset(preset_name):
        """
        Takes the name of a preset and returns a dictionary of gr.update objects
        to set the values of the 13 8-bit synthesizer control components.
        This version is more robust as it directly maps keys to UI components.
        """
        # If a special value is selected or the preset is not found, return empty updates for all controls.
        if preset_name in ["Custom", "Auto-Recommend (Analyze MIDI)"] or preset_name not in S8BIT_PRESETS:
            # We create a dictionary mapping each control component to an empty update.
            s8bit_control_keys = [key for key in ALL_PARAM_KEYS if key.startswith('s8bit_') and key != 's8bit_preset_selector']
            return {ui_component_map[key]: gr.update() for key in s8bit_control_keys}
        
        # Get the settings dictionary for the chosen preset.
        settings = S8BIT_PRESETS[preset_name]
        updates = {}
        
        # Iterate through the KEY-VALUE pairs in the chosen preset's settings.
        for simple_key, value in settings.items():
            # Reconstruct the full component key (e.g., 'waveform_type' -> 's8bit_waveform_type')
            full_key = f"s8bit_{simple_key}"
            
            # Check if this key corresponds to a valid UI component
            if full_key in ui_component_map:
                component = ui_component_map[full_key]
                updates[component] = gr.update(value=value)
                
        return updates

    # --- UI Controller Function for Dynamic Visibility ---
    def update_separation_mode_ui(is_advanced):
        """
        Updates the visibility and labels of UI components based on whether
        the advanced separation mode is enabled.
        """
        if is_advanced:
            # Advanced Mode: Show individual controls, label becomes "Other"
            return {
                advanced_separation_controls: gr.update(visible=True),
                transcribe_drums: gr.update(visible=True),
                transcribe_bass: gr.update(visible=True),
                transcribe_other_or_accompaniment: gr.update(label="Transcribe Other"),
                merge_drums_to_render: gr.update(visible=True),
                merge_bass_to_render: gr.update(visible=True),
                merge_other_or_accompaniment: gr.update(label="Merge Other")
            }
        else:
            # Simple Mode: Hide individual controls, label becomes "Accompaniment"
            return {
                advanced_separation_controls: gr.update(visible=False),
                transcribe_drums: gr.update(visible=False),
                transcribe_bass: gr.update(visible=False),
                transcribe_other_or_accompaniment: gr.update(label="Transcribe Accompaniment"),
                merge_drums_to_render: gr.update(visible=False),
                merge_bass_to_render: gr.update(visible=False),
                merge_other_or_accompaniment: gr.update(label="Merge Accompaniment")
            }
    
    # --- UI controller for handling model selection ---
    def on_separation_model_change(model_choice):
        """
        Update the UI when the separation model changes.
        If a 2-stem model (RoFormer) is selected, hide advanced (4-stem) controls.
        """
        is_demucs = 'Demucs' in model_choice
        # For 2-stem models, we force simple mode (is_advanced=False)
        updates = update_separation_mode_ui(is_advanced=False)
        # Also hide the checkbox that allows switching to advanced mode
        updates[enable_advanced_separation] = gr.update(visible=is_demucs, value=False)
        return updates

    # --- Use the dataclass to define the master list of parameter keys ---
    # This is now the single source of truth for parameter order.
    ALL_PARAM_KEYS = [field.name for field in fields(AppParameters) if field.name not in ["input_file", "batch_input_files"]]

    app = gr.Blocks(theme=gr.themes.Base())

    with app:
        gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Audio-to-MIDI & Advanced Renderer</h1>")
        gr.Markdown(
            "**Upload a Audio for transcription-then-rendering, or a MIDI for rendering-only.**\n\n"
            "This application combines piano audio transcription with a powerful MIDI transformation and rendering toolkit. "
            "Based on the work of [asigalov61](https://github.com/asigalov61)."
        )

        # --- Use Tabs for different workflows ---
        with gr.Tabs():
            waveform_options = gr.WaveformOptions(show_recording_waveform=False)
            # --- TAB 1: SINGLE FILE PROCESSING ---
            with gr.TabItem("Single File Processing"):
                # --- All of your existing UI components go inside this Tab ---
                with gr.Row():
                    with gr.Column(scale=1):
                        # --- INPUT COLUMN ---
                        gr.Markdown("## 1. Upload File")
                
                        # Changed from gr.File to gr.Audio to allow for audio preview.
                        # type="filepath" ensures the component returns a string path to the uploaded file.
                        # The component will show a player for supported audio types (e.g., WAV, MP3).
                        input_file = gr.Audio(
                            label="Input Audio or MIDI File",
                            type="filepath",
                            sources=["upload"], waveform_options=waveform_options
                        )
                        # --- The single file processing button ---
                        submit_btn = gr.Button("Process and Render Single File", variant="primary")
                    
                    with gr.Column(scale=2):
                        # --- OUTPUT COLUMN ---
                        gr.Markdown("### 2. Results")
                        output_midi_title = gr.Textbox(label="MIDI Title")
                        output_song_description = gr.Textbox(label="MIDI Description", lines=3)
                        output_audio = gr.Audio(label="Rendered Audio Output", format="wav", waveform_options=waveform_options)
                        output_plot = gr.Plot(label="MIDI Score Plot")
                        with gr.Row():
                            output_midi = gr.File(label="Download Processed MIDI File", file_types=[".mid"])
                            output_midi_md5 = gr.Textbox(label="Output MIDI MD5 Hash")
                        output_midi_summary = gr.Textbox(label="MIDI metadata summary", lines=4)
                

            # --- TAB 2: BATCH PROCESSING ---
            with gr.TabItem("Batch Processing"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### 1. Upload Files")
                        gr.Markdown("Uses the **global settings** configured above.")
                        batch_input_files = gr.File(
                            label="Upload Audio or MIDI Files",
                            file_count="multiple"
                        )
                        
                        batch_process_btn = gr.Button("Process Batch", variant="primary")

                    with gr.Column():
                        gr.Markdown("### 2. Download Results")
                        batch_output_audio_files = gr.File(
                            label="Download Rendered FLAC Files",
                            file_count="multiple",
                            interactive=False
                        )
                        batch_output_midi_files = gr.File(
                            label="Download Processed MIDI Files",
                            file_count="multiple",
                            interactive=False
                        )
        # --- Global Settings Accordion, Define all settings in a global, shared accordion ---
        with gr.Accordion("▶️ Configure Global Settings (for both Single File and Batch)", open=True):
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### Transcription Settings\n"
                        "> _**Note:** This entire section is for audio-to-MIDI conversion. All settings here are ignored if a MIDI file is uploaded._"
                    )
                    # --- Transcription Method Selector ---
                    transcription_method = gr.Radio(["General Purpose", "Piano-Specific"], label="Audio Transcription Method", value="General Purpose",
                            info="Choose 'General Purpose' for most music (vocals, etc.). Choose 'Piano-Specific' only for solo piano recordings.")
                    # --- Stereo Processing Checkbox ---
                    enable_stereo_processing = gr.Checkbox(label="Enable Stereo Transcription", value=False,
                            info="For stereo audio files only. When enabled, transcribes left and right channels independently, then merges them. Note: This will double the transcription time.")
                    
                    # --- Vocal Separation Group ---
                    with gr.Group(): 
                        separate_vocals = gr.Checkbox(label="Enable Source Separation", value=False,
                                info="If checked, separates the audio into its component stems (vocals, drums, etc.) before processing.")

                        # --- Container for all separation options, visible only when enabled ---
                        with gr.Group(visible=False) as separation_options_box:
                            separation_model = gr.Radio(
                                ["Demucs (4-stem)", "BS-RoFormer (Vocals/Instrumental)", "Mel-RoFormer (Vocals/Instrumental)"],
                                label="Separation Model",
                                value="Demucs (4-stem)",
                                info="Select the separation model. Demucs provides 4 stems (vocals, drums, bass, other). RoFormer models are specialized for 2-stem (vocals/instrumental) separation.",
                            )

                            gr.Markdown("#### 1. Stem Separation Options")
                            enable_advanced_separation = gr.Checkbox(label="Enable Advanced Stem Control (Demucs Only)", value=False,
                                info="If checked, you can individually control drums, bass, and other. If unchecked, they are treated as a single 'Accompaniment' track. This option is only available for the Demucs model.")
                            
                            with gr.Row(visible=False) as advanced_separation_controls:
                                separate_drums = gr.Checkbox(label="Drums", value=True)
                                separate_bass = gr.Checkbox(label="Bass", value=True)
                                separate_other = gr.Checkbox(label="Other", value=True)
                            
                            gr.Markdown("#### 2. Transcription Targets")
                            gr.Markdown("_Select which separated stem(s) to convert to MIDI._")
                            with gr.Row():
                                transcribe_vocals = gr.Checkbox(label="Transcribe Vocals", value=False)
                                # These two will be hidden/shown dynamically
                                transcribe_drums = gr.Checkbox(label="Transcribe Drums", value=False, visible=False)
                                transcribe_bass = gr.Checkbox(label="Transcribe Bass", value=False, visible=False)
                                # This checkbox will have its label changed dynamically
                                transcribe_other_or_accompaniment = gr.Checkbox(label="Transcribe Accompaniment", value=True)

                            gr.Markdown("#### 3. Audio Merging Targets")
                            gr.Markdown(
                                """
                                _Select which **original, unprocessed** audio stems to merge back into the final output. 
                                This does **not** use the transcribed MIDI; it uses the raw audio from the initial separation. 
                                You can leave all boxes unchecked. This step only affects the final audio file, not the MIDI output._
                                """
                            )
                            with gr.Row():
                                merge_vocals_to_render = gr.Checkbox(label="Merge Vocals", value=False)
                                # These two will be hidden/shown dynamically
                                merge_drums_to_render = gr.Checkbox(label="Merge Drums", value=False, visible=False)
                                merge_bass_to_render = gr.Checkbox(label="Merge Bass", value=False, visible=False)
                                # This checkbox will have its label changed dynamically
                                merge_other_or_accompaniment = gr.Checkbox(label="Merge Accompaniment", value=False)

                    with gr.Accordion("General Purpose Transcription Settings", open=True) as general_transcription_settings:
                        # --- Preset dropdown for basic_pitch ---
                        basic_pitch_preset_selector = gr.Dropdown(
                            choices=["Auto-Analyze Audio", "Custom"] + list(BASIC_PITCH_PRESETS.keys()),
                            value="Default (Balanced)",
                            label="Transcription Profile Preset",
                            info="Select a profile to auto-fill settings for different instrument types."
                                 "For reference only; it is recommended to test and adjust for optimal results.")
                        # --- The existing basic_pitch components ---
                        onset_threshold = gr.Slider(
                            0.0, 1.0, value=0.5, step=0.05, 
                            label="On-set Threshold", 
                            info="Sensitivity for detecting the start of a new note. Lower values will detect more notes (even faint ones), but may create false positives. Higher values are stricter and cleaner, but might miss subtle notes."
                        )
                        frame_threshold = gr.Slider(
                            0.0, 1.0, value=0.3, step=0.05, 
                            label="Frame Threshold", 
                            info="Sensitivity for determining if a note is 'on' or 'off'. Lower values will sustain notes longer, but can merge distinct notes. Higher values create shorter, more separated notes, but might cut off tails."
                        )
                        minimum_note_length = gr.Slider(
                            10, 500, value=128, step=1, 
                            label="Minimum Note Length (ms)", 
                            info="Filters out notes shorter than this duration. Increase this to remove fast, noisy artifacts or clicks. Decrease it if the transcription is missing very short, staccato notes."
                        )
                        minimum_frequency = gr.Slider(
                            0, 500, value=60, step=5, 
                            label="Minimum Frequency (Hz)", 
                            info="Ignores any detected pitches below this frequency. Increase this to filter out low-frequency noise like rumble or hum. Set it just below your target instrument's lowest note (e.g., ~80Hz for guitar)."
                        )
                        maximum_frequency = gr.Slider(
                            501, 10000, value=4000, step=10, 
                            label="Maximum Frequency (Hz)", 
                            info="Ignores any detected pitches above this frequency. Decrease this to filter out high-frequency noise like hiss or cymbals. Set it just above your target instrument's highest note (e.g., ~1200Hz for vocals)."
                        )
                        infer_onsets = gr.Checkbox(
                            value=True, 
                            label="Infer Onsets (Boost Onsets)",
                            info="When enabled, the model actively looks for and emphasizes the start of each note (the 'attack'). Recommended for percussive or clear, rhythmic music. Disable for very smooth, legato music like vocal pads."
                        )
                        melodia_trick = gr.Checkbox(
                            value=True, 
                            label="Melodia Trick (Contour Optimization)",
                            info="When enabled, uses a secondary melody-detection algorithm to refine the main pitch contour. Highly recommended for most melodic content. Disable if you are transcribing non-melodic noise or complex polyphony."
                        )
                        multiple_pitch_bends = gr.Checkbox(
                            value=False, 
                            label="Allow Multiple Pitch Bends",
                            info="When enabled, allows a single note to have multiple, continuous pitch bends within it. Essential for transcribing vocals, slides, or vibrato-heavy instruments. Disable for clean, discrete notes like a standard piano."
                        )

                with gr.Column(scale=1):
                    # --- Rendering Settings ---
                    gr.Markdown("### MIDI Transformation & Rendering Settings")
                    render_type = gr.Radio(
                        list(RENDER_TYPE_DESCRIPTIONS.keys()), # Use keys from dict for choices
                        ["Render as-is", "Custom render", "Extract melody", "Flip", "Reverse", "Repair Durations", "Repair Chords", "Remove Duplicate Pitches", "Longest Repeating Phrase", "Multi-Instrumental Summary", "Solo Piano Summary", "Add Drum Track"],
                        label="MIDI Transformation Render Type",
                        value="Render as-is",
                        info="Apply transformations to the MIDI before rendering. Select 'Render as-is' for basic rendering or other options for transformations.")
                    # --- A Markdown box for the dynamic descriptions ---
                    render_type_info = gr.Markdown(
                        value=RENDER_TYPE_DESCRIPTIONS["Render as-is"], # Set initial value
                        elem_classes="description-box" # Optional: for CSS styling
                    )
                    # --- SoundFont Bank with Preview Button ---
                    with gr.Row(elem_id="soundfont_selector_row"):
                        soundfont_bank = gr.Dropdown(
                            [SYNTH_8_BIT_LABEL] + list(soundfonts_dict.keys()),
                            label="SoundFont / Synthesizer",
                            value=list(soundfonts_dict.keys())[0] if soundfonts_dict else SYNTH_8_BIT_LABEL,
                            scale=4 # Give the dropdown more space
                        )
                        # The preview button, with a speaker icon for clarity.
                        preview_sf_button = gr.Button("🔊 Preview", scale=1)

                    # This audio player is dedicated to playing the preview clips.
                    # It's not interactive, as it's for output only.
                    preview_sf_player = gr.Audio(label="SoundFont Preview", interactive=False, show_label=False)
                    render_sample_rate = gr.Radio(
                        ["16000", "32000", "44100"],
                        label="Audio Sample Rate",
                        value="44100")
                    
                    with gr.Accordion("Advanced MIDI Rendering Options", open=False) as advanced_rendering_options:
                        render_with_sustains = gr.Checkbox(label="Apply sustain pedal effects (if present)", value=True,
                            info="Applies sustain pedal effects (CC64) to lengthen notes, creating a more realistic and connected performance, especially for piano.")
                        render_output_as_solo_piano = gr.Checkbox(label="Convert to Solo Piano (Grand Piano patch)", value=False,
                            info="Converts all non-drum instruments to a Grand Piano patch, creating a solo piano arrangement of the entire score.")
                        render_remove_drums = gr.Checkbox(label="Remove drum track", value=False,
                            info="Removes the entire drum track (typically MIDI Channel 9) from the score. Ideal for creating instrumental or karaoke versions.")
                        render_transpose_to_C4 = gr.Checkbox(label="Transpose entire score to center around C4", value=False,
                            info="Transposes the entire score so that its average pitch is centered around C4 (MIDI note 60). Useful for standardizing key.")
                        render_transpose_value = gr.Slider(-12, 12, value=0, step=1, label="Transpose (semitones)",
                            info="Shifts the pitch of all non-drum notes up (positive values) or down (negative values) by the specified number of semitones.")
                        custom_render_patch = gr.Slider(-1, 127, value=-1, step=1, label="Force MIDI Patch (-1 to disable)",
                            info="Forces all non-drum instruments to use a single specified MIDI patch number. Set to -1 to use the original instruments.")
                        merge_misaligned_notes = gr.Slider(-1, 127, value=-1, label="Time to merge notes in ms (-1 to disable)",
                            info="Aligns the start times of notes that are played almost simultaneously (within the specified ms threshold). Cleans up sloppy timing. -1 to disable.")
                        render_align = gr.Radio(
                            ["Do not align", "Start Times", "Start Times and Durations", "Start Times and Split Durations"],
                            label="Align notes to musical bars",
                            value="Do not align",
                            info="Quantizes the score to a fixed bar length. 'Start Times' aligns onsets. "
                            "'Durations' trims notes at the bar line. 'Split Durations' splits notes that cross the bar line."
                        )

                with gr.Column(scale=1):
                    # --- 8-bit Synthesizer Settings ---
                    #
                    # =================================================================================
                    # === 8-Bit Synthesizer Parameter Guide ===
                    # =================================================================================
                    #
                    # --- Basic Tone Shaping ---
                    #
                    # Waveform Type: The fundamental timbre of the sound.
                    #   - Square: The classic, bright, somewhat hollow sound of the NES. Its tone is heavily modified by Pulse Width.
                    #   - Sawtooth: Aggressive, buzzy, and rich. Great for intense leads or gritty basslines.
                    #   - Triangle: Soft, pure, and flute-like. Often used for basslines or gentler melodies.
                    #
                    # Pulse Width (Square Wave Only): Modifies the character of the Square wave.
                    #   - Low (near 0.1) or High (near 0.9): Creates a thin, sharp, or nasal sound. A common choice for classic leads.
                    #   - Mid (near 0.5): A "perfect" square wave. The sound is full, round, and most robust.
                    #
                    # Envelope Type: Shapes the volume of each note over its duration.
                    #   - Plucky (AD): Creates a percussive, short sound that attacks instantly and then fades. Ideal for fast melodies and arpeggios.
                    #   - Sustained (Full Decay): Creates a held-out sound that lasts for the note's full duration. Ideal for pads and atmospheric sounds.
                    #
                    # Decay Time (s): Controls how long a note's sound lasts (in the Plucky envelope).
                    #   - Low: Very short, staccato notes.
                    #   - High: Longer, more resonant notes that can bleed into each other.
                    #
                    # Bass Boost Level: Mixes in a sub-octave (a square wave one octave lower).
                    #   - Low (or 0): The pure, original waveform.
                    #   - High: Adds significant weight, thickness, and power to the sound.
                    #
                    # --- Modulation & Performance ---
                    #
                    # Vibrato Rate (Hz): The SPEED of the pitch wobble.
                    #   - Low: A slow, gentle wavering effect.
                    #   - High (8Hz+): A fast, frantic buzzing or trembling effect. Can create "ring-mod" style sounds at extreme values.
                    #
                    # Vibrato Depth (Hz): The INTENSITY of the pitch wobble.
                    #   - Low (or 0): A very subtle effect, or no vibrato at all.
                    #   - High: An extreme, dramatic pitch bend. Can sound chaotic or like a siren at extreme values.
                    #
                    # Smooth Notes (Checkbox):
                    #   - Enabled: Applies a tiny fade-in/out to reduce clicking artifacts. Makes the sound slightly softer but cleaner.
                    #   - Disabled: More abrupt, harsh note onsets. Can be desirable for an aggressive sound.
                    #
                    # Continuous Vibrato (Checkbox):
                    #   - Enabled: The vibrato is smooth and connected across a musical phrase, creating a "singing" or legato effect.
                    #   - Disabled: The vibrato resets on each new note, creating a bouncy, per-note, staccato effect (key for the "Mario" style).
                    #
                    # --- FX & Advanced Synthesis ---
                    #
                    # Noise Level: Mixes in white noise with the main waveform.
                    #   - Low (or 0): No noise.
                    #   - High: Adds "air," "grit," or a "hissing" quality. Essential for simulating percussion or creating wind-like sound effects.
                    #
                    # Distortion Level: Applies a wave-shaping algorithm to make the sound harsher.
                    #   - Low (or 0): The clean, original sound.
                    #   - High: Progressively crushes and saturates the waveform, creating a very aggressive, "fuzzy" or "broken" tone.
                    #
                    # FM Depth (Frequency Modulation): Controls the intensity of the frequency modulation.
                    #   - Low (or 0): No FM effect.
                    #   - High: The main frequency is more heavily altered by the FM Rate, creating complex, bell-like, metallic, or dissonant tones.
                    #
                    # FM Rate (Frequency Modulation): Controls the speed of the modulating oscillator.
                    #   - Low: Creates a slow, vibrato-like or "wobbling" FM effect.
                    #   - High: Creates fast modulation, resulting in bright, complex, often metallic harmonics and sidebands.
                    # =================================================================================
                    #
                    # --- New option for auto-recommendation ---
                    # Define the 8-bit UI components in one place for easy reference
                    gr.Markdown("### 8-bit Synthesizer Settings")
                    with gr.Accordion("8-bit Synthesizer Settings", open=True, visible=False) as synth_8bit_settings:
                        s8bit_preset_selector = gr.Dropdown(
                            choices=["Custom", "Auto-Recommend (Analyze MIDI)"] + list(S8BIT_PRESETS.keys()), 
                            value="Custom", 
                            label="Style Preset",
                            info="Select a preset to auto-fill the settings below. Choose 'Custom' for manual control or 'Auto-Recommend' to analyze the MIDI.\nFor reference and entertainment only. These presets are not guaranteed to be perfectly accurate."
                        )
                        s8bit_waveform_type = gr.Dropdown(
                            ['Square', 'Sawtooth', 'Triangle'], 
                            value='Square', 
                            label="Waveform Type",
                            info="The fundamental timbre of the sound. Square is bright and hollow (classic NES), Sawtooth is aggressive and buzzy, Triangle is soft and flute-like."
                        )
                        s8bit_pulse_width = gr.Slider(
                            0.01, 0.99, value=0.5, step=0.01, 
                            label="Pulse Width (Square Wave Only)",
                            info="Changes the character of the Square wave. Low values (\~0.1) are thin and nasal, while mid values (\~0.5) are full and round."
                        )
                        s8bit_envelope_type = gr.Dropdown(
                            ['Plucky (AD Envelope)', 'Sustained (Full Decay)'], 
                            value='Plucky (AD Envelope)', 
                            label="Envelope Type",
                            info="Shapes the volume of each note. 'Plucky' is a short, percussive sound. 'Sustained' holds the note for its full duration."
                        )
                        s8bit_decay_time_s = gr.Slider(
                            0.01, 1.0, value=0.1, step=0.01, 
                            label="Decay Time (s)",
                            info="For the 'Plucky' envelope, this is the time it takes for a note to fade to silence. Low values are short and staccato; high values are longer and more resonant."
                        )
                        s8bit_adaptive_decay = gr.Checkbox(
                            value=True, # Default to True, as the effect is generally better.
                            label="Enable Adaptive Decay (Fix for Staccato)",
                            info="Recommended! Fixes low volume on fast/short notes by ensuring a consistent decay rate, regardless of note length. Makes staccato passages sound fuller and more powerful."
                        )
                        s8bit_vibrato_rate = gr.Slider(
                            0, 20, value=5, 
                            label="Vibrato Rate (Hz)",
                            info="The SPEED of the pitch wobble. Low values create a slow, gentle waver. High values create a fast, frantic buzz."
                        )
                        s8bit_vibrato_depth = gr.Slider(
                            0, 50, value=0, 
                            label="Vibrato Depth (Hz)",
                            info="The INTENSITY of the pitch wobble. Low values are subtle or off. High values create a dramatic, siren-like pitch bend."
                        )
                        s8bit_bass_boost_level = gr.Slider(
                            0.0, 1.0, value=0.0, step=0.05, 
                            label="Bass Boost Level", 
                            info="Mixes in a sub-octave (a square wave one octave lower). Low values have no effect; high values add significant weight and power."
                        )
                        # UI control for Intelligent Bass Boost
                        s8bit_bass_boost_cutoff_hz = gr.Slider(
                            50.0, 500.0, value=200.0, step=10.0,
                            label="Bass Boost Cutoff (Hz)",
                            info="Intelligent Bass Boost: The boost effect will gradually fade out for notes BELOW this frequency, preventing muddiness in the low-end."
                        )
                        s8bit_smooth_notes_level = gr.Slider(
                            0.0, 1.0, value=0.0, step=0.05, 
                            label="Smooth Notes Level", 
                            info="Applies a tiny fade-in/out to reduce clicking. Low values (or 0) give a hard, abrupt attack. High values give a softer, cleaner onset."
                        )
                        s8bit_continuous_vibrato_level = gr.Slider(
                            0.0, 1.0, value=0.0, step=0.05, 
                            label="Continuous Vibrato Level", 
                            info="Controls vibrato continuity across notes. Low values (0) reset vibrato on each note (bouncy). High values (1) create a smooth, connected 'singing' vibrato."
                        )
                        # --- New accordion for advanced effects ---
                        with gr.Accordion("Advanced Synthesis & FX", open=True):
                            s8bit_noise_level = gr.Slider(
                                0.0, 1.0, value=0.0, step=0.05, 
                                label="Noise Level", 
                                info="Mixes in white noise with the main waveform. Low values are clean; high values add 'grit', 'air', or a hissing quality, useful for percussion."
                            )
                            s8bit_distortion_level = gr.Slider(
                                0.0, 0.9, value=0.0, step=0.05, 
                                label="Distortion Level", 
                                info="Applies wave-shaping to make the sound harsher. Low values are clean; high values create a crushed, 'fuzzy', and aggressive tone."
                            )
                            s8bit_fm_modulation_depth = gr.Slider(
                                0.0, 1.0, value=0.0, step=0.05, 
                                label="FM Depth", 
                                info="Frequency Modulation intensity. At low values, there is no effect. At high values, it creates complex, metallic, or bell-like tones."
                            )
                            s8bit_fm_modulation_rate = gr.Slider(
                                0.0, 500.0, value=0.0, step=1.0, 
                                label="FM Rate", 
                                info="Frequency Modulation speed. Low values create a slow 'wobble'. High values create fast modulation, resulting in bright, dissonant harmonics."
                            )
                            # --- Echo Sustain Feature Block (Visually Grouped) ---
                            # This outer group ensures the checkbox and its settings are visually linked.
                            with gr.Group():
                                s8bit_echo_sustain = gr.Checkbox(
                                    value=False, # Default to off as it's a special effect.
                                    label="Enable Echo Sustain for Long Notes",
                                    info="For 'Plucky' envelope only. Fills the silent tail of long, sustained notes with quiet, repeating pulses. Fixes 'choppy' sound on long piano notes."
                                )
                                # This inner group contains the sliders and is controlled by the checkbox above.
                                with gr.Group(visible=False) as echo_sustain_settings:
                                    s8bit_echo_rate_hz = gr.Slider(
                                        1.0, 20.0, value=5.0, step=0.5,
                                        label="Echo Rate (Hz)",
                                        info="How many echoes (pulses) per second. Higher values create a faster, 'tremolo'-like effect."
                                    )
                                    s8bit_echo_decay_factor = gr.Slider(
                                        0.1, 0.95, value=0.45, step=0.05,
                                        label="Echo Decay Factor",
                                        info="How quickly the echoes fade. A value of 0.6 means each echo is 60% of the previous one's volume. Lower is faster."
                                    )
                                    s8bit_echo_trigger_threshold = gr.Slider(
                                        1.1, 30.0, value=20, step=0.1,
                                        label="Echo Trigger Threshold (x Decay Time)",
                                        info="Controls how long a note must be to trigger echoes. This value is a multiplier of the 'Decay Time'. Example: If 'Decay Time' is 0.1s and this threshold is set to 10.0, only notes longer than 1.0s (0.1 * 10.0) will produce echoes."
                                    )
                        # --- Re-architected into two separate, parallel accordions ---
#                       --- Section 1: Arpeggiator (Creative Tool) ---
                        with gr.Accordion("Arpeggiator (Creative Tool to Reduce Stiffness)", open=False):
                            s8bit_enable_arpeggiator = gr.Checkbox(
                                value=False,
                                label="Enable Arpeggiator (to reduce stiffness)",
                                info="Transforms chords into rapid sequences of notes, creating a classic, lively chiptune feel. This is a key technique to make 8-bit music sound more fluid."
                            )
                            with gr.Group(visible=False) as arpeggiator_settings_box:
                                s8bit_arpeggio_target = gr.Dropdown(
                                    ["Accompaniment Only", "Melody Only", "Full Mix"],
                                    value="Accompaniment Only",
                                    label="Arpeggiation Target",
                                    info="""
- **Accompaniment Only (Classic):** Applies arpeggios only to the harmony/chord parts, leaving the lead melody untouched. The classic chiptune style.
- **Melody Only (Modern):** Applies arpeggios as a decorative effect to the lead melody notes, leaving the accompaniment as is. Creates a modern, expressive synth lead sound.
- **Full Mix:** Applies arpeggios to all non-drum tracks. Can create a very dense, complex texture.
                                    """
                                )
                                s8bit_arpeggio_velocity_scale = gr.Slider(
                                    0.1, 1.5, value=0.3, step=0.05,
                                    label="Arpeggio Velocity Scale",
                                    info="A master volume control for the arpeggiator. 0.7 means arpeggiated notes will have 70% of the original chord's velocity."
                                )
                                s8bit_arpeggio_density = gr.Slider(
                                    0.1, 1.0, value=0.4, step=0.05,
                                    label="Arpeggio Density Scale",
                                    info="Controls the density/sparseness of arpeggios. Lower values create more silence between notes, making long chords feel more relaxed."
                                )
                                s8bit_arpeggio_rhythm = gr.Dropdown(
                                    [
                                        "Continuous 16ths", 
                                        "Classic Upbeat (8th)",
                                        "Pulsing 8ths",
                                        "Triplet 8ths",
                                        "Pulsing 4ths",
                                        "Galloping",
                                        "Simple Quarter Notes"
                                    ],
                                    value="Pulsing 8ths",
                                    label="Arpeggio Rhythm Pattern",
                                    info="""
- **Continuous 16ths:** A constant, driving wall of sound with no breaks. Creates a very dense, high-energy texture. (Sounds like: ta-ta-ta-ta ta-ta-ta-ta)
- **Classic Upbeat (8th):** The quintessential chiptune rhythm. Creates a bouncy, syncopated feel by playing on the off-beats. (Sounds like: _ _ ta-ta _ _ ta-ta)
- **Pulsing 8ths:** A steady, on-beat rhythm playing two notes per beat. Good for a solid, rhythmic foundation. (Sounds like: ta-ta ta-ta)
- **Triplet 8ths:** A rolling, "three-feel" rhythm that creates a swing or shuffle groove. Very common in Blues, Jazz, and Hip-Hop. (Sounds like: ta-ta-ta ta-ta-ta)
- **Pulsing 4ths:** A strong, deliberate pulse on each downbeat, with a clear separation between notes. (Sounds like: ta_ ta_ ta_)
- **Galloping:** A driving, forward-moving rhythm with a distinctive long-short pattern. Excellent for action themes. (Sounds like: ta--ta ta--ta)
- **Simple Quarter Notes:** The most sparse pattern, playing one sustained note per beat. Creates a calm and open feel. (Sounds like: ta _ ta _ ta _ ta _)
                                    """
                                )
                                s8bit_arpeggio_pattern = gr.Dropdown(
                                    ["Up", "Down", "UpDown"],
                                    value="Up",
                                    label="Arpeggio Pattern",
                                    info="""
- **Up:** The classic choice. Ascends from the lowest to the highest note of the chord, then jumps back to the bottom. Creates a feeling of energy, optimism, and forward momentum.
- **Down:** Descends from the highest to the lowest note. Often creates a more melancholic, reflective, or suspenseful mood.
- **UpDown:** Ascends to the highest note, then descends back down without jumping. This is the smoothest and most fluid pattern, creating a gentle, wave-like motion.
                                    """
                                )
                                s8bit_arpeggio_octave_range = gr.Slider(
                                    1, 4, value=1, step=1,
                                    label="Arpeggio Octave Range",
                                    info="How many octaves the arpeggio pattern will span before repeating."
                                )
                                s8bit_arpeggio_panning = gr.Dropdown(
                                    ["Stereo", "Center", "Left", "Right"],
                                    value="Stereo",
                                    label="Arpeggio Layer Panning",
                                    info="""
- **Stereo (Recommended):** Creates a wide, immersive sound by alternating arpeggio tracks between the left and right speakers. This provides maximum clarity and separation from the main melody.
- **Center:** Places the arpeggio directly in the middle (mono). Creates a focused, powerful, and retro sound, but may conflict with a centered lead melody.
- **Left / Right:** Places the entire arpeggio layer on only one side. Useful for creative "call and response" effects or special mixing choices.
                                    """
                                )
                            # --- Delay/Echo Sub-Section ---
                            with gr.Group():
                                s8bit_enable_delay = gr.Checkbox(
                                    value=False,
                                    label="Enable Delay / Echo Effect",
                                    info="Adds repeating, decaying echoes to notes, creating a sense of space and rhythmic complexity."
                                )
                                with gr.Group(visible=False) as delay_settings_box:
                                    s8bit_delay_on_melody_only = gr.Checkbox(
                                        value=True,
                                        label="Apply Delay to Melody Only",
                                        info="Recommended. Applies the echo effect only to the lead melody notes, keeping the harmony clean."
                                    )
                                    s8bit_delay_division = gr.Dropdown(
                                        ["Quarter Note", "Dotted 8th Note", "8th Note", "Triplet 8th Note", "16th Note"],
                                        value="Dotted 8th Note",
                                        label="Delay Time (Tempo Synced)",
                                        info="""
"The time between echoes, synced to the MIDI's tempo. 'Dotted 8th Note' is a classic rhythmic choice."
- **Quarter Note:** A simple, stable echo on the next beat. (1, 2, 3, 4)
- **Dotted 8th Note (Classic):** Creates a very popular, rolling syncopated rhythm. Highly recommended for adding energy and complexity.
- **8th Note:** A steady, "call and response" echo on the off-beat. Creates a running or swing feel.
- **Triplet 8th Note:** Creates a unique "shuffling" or "bouncing" 3-feel groove over the standard 4/4 beat.
- **16th Note:** A very fast, dense echo. Can act more like a textural effect than a distinct rhythmic delay.
                                        """
                                    )
                                    s8bit_delay_feedback = gr.Slider(
                                        0.1, 0.9, value=0.5, step=0.05,
                                        label="Delay Feedback (Volume Decay)",
                                        info="Controls how much quieter each echo is. 0.5 means each echo is 50% the volume of the one before it."
                                    )
                                    s8bit_delay_repeats = gr.Slider(
                                        1, 10, value=3, step=1,
                                        label="Number of Repeats",
                                        info="The total number of echoes to generate for each note."
                                    )
                                    # --- UI controls for low-end management ---
                                    s8bit_delay_highpass_cutoff_hz = gr.Slider(
                                        0, 500, value=100, step=10,
                                        label="Echo High-Pass Filter (Hz)",
                                        info="Filters out low frequencies from the echoes to prevent muddiness. Set to 0 to disable. 80-120Hz is a good range to clean up bass."
                                    )
                                    s8bit_delay_bass_pitch_shift = gr.Slider(
                                        -12, 24, value=12, step=1,
                                        label="Echo Pitch Shift for Low Notes (Semitones)",
                                        info="Shifts the pitch of echoes for very low notes (below C3). +12 is one octave up, +7 is a perfect fifth. 0 to disable."
                                    )
                                    # --- UI controls for high-end management ---
                                    s8bit_delay_lowpass_cutoff_hz = gr.Slider(
                                        1000, 20000, value=5000, step=500,
                                        label="Echo Low-Pass Filter (Hz)",
                                        info="Filters out high frequencies from the echoes to reduce harshness. Set to 20000 to disable. 4k-8kHz is a good range to make echoes sound 'darker'."
                                    )
                                    s8bit_delay_treble_pitch_shift = gr.Slider(
                                        -24, 12, value=-12, step=1,
                                        label="Echo Pitch Shift for High Notes (Semitones)",
                                        info="Shifts the pitch of echoes for very high notes (above C6). -12 is one octave down. 0 to disable."
                                    )
                        
                        # --- Section 2: MIDI Pre-processing (Corrective Tool) ---
                        with gr.Accordion("MIDI Pre-processing (Corrective Tool)", open=False):
                            s8bit_enable_midi_preprocessing = gr.Checkbox(
                                value=True,
                                label="Enable MIDI Pre-processing (Anti-Harshness)",
                                info="Intelligently reduces the velocity of notes that are likely to cause harshness (e.g., very high notes or loud, dense chords) before synthesis begins."
                            )
                            with gr.Group(visible=True) as midi_preprocessing_settings_box:
                                s8bit_high_pitch_threshold = gr.Slider(
                                    60, 108, value=84, step=1,
                                    label="High Pitch Threshold (MIDI Note)",
                                    info="Notes above this pitch will have their velocity reduced. 84 = C6."
                                )
                                s8bit_high_pitch_velocity_scale = gr.Slider(
                                    0.1, 1.0, value=0.8, step=0.05,
                                    label="High Pitch Velocity Scale",
                                    info="Multiplier for high notes' velocity (e.g., 0.8 = 80% of original velocity)."
                                )
                                # --- UI controls for low-pitch management ---
                                s8bit_low_pitch_threshold = gr.Slider(
                                    21, 60, value=36, step=1,
                                    label="Low Pitch Threshold (MIDI Note)",
                                    info="Notes below this pitch will have their velocity reduced to prevent muddiness. 36 = C2."
                                )
                                s8bit_low_pitch_velocity_scale = gr.Slider(
                                    0.1, 1.0, value=0.9, step=0.05,
                                    label="Low Pitch Velocity Scale",
                                    info="Multiplier for low notes' velocity. Use this to gently tame excessive sub-bass."
                                )
                                s8bit_chord_density_threshold = gr.Slider(
                                    2, 10, value=4, step=1,
                                    label="Chord Density Threshold",
                                    info="Minimum number of notes to be considered a 'dense' chord."
                                )
                                s8bit_chord_velocity_threshold = gr.Slider(
                                    50, 127, value=100, step=1,
                                    label="Chord Velocity Threshold",
                                    info="If a dense chord's average velocity is above this, it will be tamed."
                                )
                                s8bit_chord_velocity_scale = gr.Slider(
                                    0.1, 1.0, value=0.75, step=0.05,
                                    label="Chord Velocity Scale",
                                    info="Velocity multiplier for loud, dense chords."
                                )
                        
                        # --- Section 3: Audio Post-processing, accordion for Anti-Aliasing and Quality Settings ---
                        with gr.Accordion("Audio Quality & Anti-Aliasing (Post-processing)", open=False):
                            s8bit_enable_anti_aliasing = gr.Checkbox(
                                value=False,
                                label="Enable All Audio Quality Enhancements",
                                info="Master toggle for all settings below. Disabling may slightly speed up rendering but can result in harsher, more aliased sound."
                            )
                            with gr.Group(visible=False) as anti_aliasing_settings_box:
                                s8bit_use_additive_synthesis = gr.Checkbox(
                                    value=False,
                                    label="Use Additive Synthesis (High Quality, High CPU)",
                                    info="Generates band-limited waveforms to drastically reduce aliasing (harshness). Slower to render but produces a much cleaner sound. Note: The other anti-aliasing settings below will still apply even if this is disabled."
                                )
                                s8bit_edge_smoothing_ms = gr.Slider(
                                    0.0, 2.0, value=0.5, step=0.1,
                                    label="Waveform Edge Smoothing (ms)",
                                    info="Applies a tiny blur to the sharp edges of standard Square/Sawtooth waves to reduce aliasing. A cheap and effective alternative to Additive Synthesis."
                                )
                                s8bit_noise_lowpass_hz = gr.Slider(
                                    1000, 20000, value=9000, step=500,
                                    label="Noise Lowpass Filter (Hz)",
                                    info="Applies a lowpass filter to the white noise, making it sound softer and less harsh. Lower values produce a 'darker' noise."
                                )
                                s8bit_harmonic_lowpass_factor = gr.Slider(
                                    4.0, 32.0, value=12.0, step=0.5,
                                    label="Harmonic Lowpass Factor",
                                    info="Controls a dynamic lowpass filter. The cutoff frequency is (Note Frequency * this factor). Lower values create a darker, more muted sound."
                                )
                                s8bit_final_gain = gr.Slider(
                                    0.1, 1.5, value=0.8, step=0.05,
                                    label="Final Gain / Limiter Level",
                                    info="A final volume adjustment before adding the sound to the mix. Values > 1.0 can introduce soft clipping (distortion)."
                                )

        # Create a dictionary mapping key names to the actual Gradio components
        ui_component_map = locals()
        
        # Build the list of all setting components in the correct order using ALL_PARAM_KEYS
        all_settings_components = [ui_component_map[key] for key in ALL_PARAM_KEYS]
        
        # --- FIX START: Isolate the preset selector from the controls it updates ---
        # Original list of all 14 synth components
        s8bit_ui_keys = [key for key in ALL_PARAM_KEYS if key.startswith('s8bit_')]
        s8bit_ui_components = [ui_component_map[key] for key in s8bit_ui_keys]

        # NEW: Create a separate list containing only the 13 controls to be updated
        s8bit_control_components = [comp for comp in s8bit_ui_components if comp != s8bit_preset_selector]
        
        # The list of basic_pitch UI components that can be updated by its preset selector.
        basic_pitch_keys = ['onset_threshold', 'frame_threshold', 'minimum_note_length', 'minimum_frequency', 'maximum_frequency', 
                              'infer_onsets', 'melodia_trick', 'multiple_pitch_bends']
        basic_pitch_ui_components = [ui_component_map[key] for key in basic_pitch_keys]
        
        # Define inputs and outputs for Gradio events
        single_file_inputs = [input_file] + all_settings_components
        result_outputs = [output_midi_md5, output_midi_title, output_midi_summary, output_midi, output_audio, output_plot, output_song_description]
        # The output list for the single file process now correctly includes all 14 synth components
        single_file_outputs = result_outputs + s8bit_ui_components
        
        batch_inputs = [batch_input_files] + all_settings_components
        batch_outputs = [batch_output_audio_files, batch_output_midi_files]

        # Event Handling for Single File Tab
        submit_btn.click(
            fn=process_and_render_file, 
            inputs=single_file_inputs,
            outputs=single_file_outputs
        )
        # --- Event Handling for Batch Tab ---
        batch_process_btn.click(
            fn=batch_process_files,
            inputs=batch_inputs,
            outputs=batch_outputs
        )
        
        # Event listeners for UI visibility and presets
        # When the main separation checkbox is toggled
        separate_vocals.change(
            fn=lambda x: gr.update(visible=x),
            inputs=separate_vocals,
            outputs=[separation_options_box]
        )

        # When the model selection changes, trigger UI update
        separation_model.change(
            fn=on_separation_model_change,
            inputs=separation_model,
            outputs=[
                enable_advanced_separation,
                advanced_separation_controls,
                transcribe_drums,
                transcribe_bass,
                transcribe_other_or_accompaniment,
                merge_drums_to_render,
                merge_bass_to_render,
                merge_other_or_accompaniment
            ]
        )

        # When the advanced stem control checkbox is toggled, update all related UI parts
        enable_advanced_separation.change(
            fn=update_separation_mode_ui,
            inputs=enable_advanced_separation,
            outputs=[
                advanced_separation_controls,
                transcribe_drums,
                transcribe_bass,
                transcribe_other_or_accompaniment,
                merge_drums_to_render,
                merge_bass_to_render,
                merge_other_or_accompaniment
            ]
        )
        
        # --- Listeners for dynamic UI updates ---
        transcription_method.change(
            fn=lambda x: gr.update(visible=(x == "General Purpose")),
            inputs=transcription_method,
            outputs=general_transcription_settings
        )
        soundfont_bank.change(
            fn=lambda x: gr.update(visible=(x == SYNTH_8_BIT_LABEL)),
            inputs=soundfont_bank,
            outputs=synth_8bit_settings
        )
        
        # --- Event listener for the new basic_pitch preset dropdown ---
        basic_pitch_preset_selector.change(
            fn=apply_basic_pitch_preset,
            inputs=basic_pitch_preset_selector,
            outputs=basic_pitch_ui_components
        )
        
        # --- Event listener for the 8-bit preset selector ---
        s8bit_preset_selector.change(
            fn=apply_8bit_preset,
            inputs=s8bit_preset_selector,
            outputs=s8bit_control_components
        )
        
        # --- New event listener for the render_type radio button ---
        # This listener now has TWO outputs
        render_type.change(
            fn=update_advanced_midi_options_visibility,
            inputs=render_type,
            outputs=advanced_rendering_options
        ).then( # Chain another event to the same trigger
            fn=update_render_type_description,
            inputs=render_type,
            outputs=render_type_info
        )
        # --- New event listener for the Echo Sustain UI ---
        s8bit_echo_sustain.change(
            fn=lambda x: gr.update(visible=x), # A simple lambda function to update visibility.
            inputs=s8bit_echo_sustain,
            outputs=echo_sustain_settings
        )
        # --- Event listener for the unified sound source preview button ---
        preview_sf_button.click(
            fn=preview_sound_source,
            inputs=[soundfont_bank] + all_settings_components,
            outputs=[preview_sf_player]
        )
        # Event listener for the new Anti-Aliasing settings box
        s8bit_enable_anti_aliasing.change(
            fn=lambda x: gr.update(visible=x),
            inputs=s8bit_enable_anti_aliasing,
            outputs=anti_aliasing_settings_box
        )
        # Event listener for the new MIDI Pre-processing settings box
        s8bit_enable_midi_preprocessing.change(
            fn=lambda x: gr.update(visible=x),
            inputs=s8bit_enable_midi_preprocessing,
            outputs=midi_preprocessing_settings_box
        )
        # Event listener for the new Arpeggiator settings box
        s8bit_enable_arpeggiator.change(
            fn=lambda x: gr.update(visible=x),
            inputs=s8bit_enable_arpeggiator,
            outputs=arpeggiator_settings_box
        )
        # Event listener for the new Delay/Echo settings box
        s8bit_enable_delay.change(
            fn=lambda x: gr.update(visible=x),
            inputs=s8bit_enable_delay,
            outputs=delay_settings_box
        )

    # Launch the Gradio app
    app.queue().launch(inbrowser=True, debug=True)