File size: 165,256 Bytes
069adbe
 
 
d9db89f
069adbe
40fb788
2e3cd9d
069adbe
 
 
 
 
7852820
069adbe
 
 
 
 
4f8d205
8e0da46
43df572
936a186
119b2bf
cc0edce
1c0e798
68208b0
2e3cd9d
158eaa8
60f791f
872a007
069adbe
 
10ea178
69a388c
d1401a0
291f3d7
 
 
 
 
 
 
 
 
 
 
 
 
 
d1401a0
 
291f3d7
 
 
 
 
 
 
 
 
 
 
 
 
 
d1401a0
69a388c
dd94c84
 
069adbe
82d70c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad242a2
f8485d4
 
 
449ebce
4162581
f8485d4
 
ad242a2
 
cf0e214
ad242a2
 
 
 
 
 
 
 
044bb1e
ad242a2
044bb1e
ad242a2
044bb1e
ad242a2
044bb1e
ad242a2
 
 
 
bfa4569
 
 
 
ad242a2
 
 
 
f8485d4
 
 
 
 
6a84d90
f8485d4
52391b5
6a84d90
 
d884d9a
f8485d4
 
 
 
 
bbf380a
 
50ce3f6
bbf380a
 
 
 
cefd40a
bbf380a
 
56fb76a
cefd40a
 
 
87bb04e
b9049ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87bb04e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbf380a
2022d2c
 
e354cc6
 
 
 
 
d503c02
e354cc6
2022d2c
 
 
 
 
 
 
 
 
 
e354cc6
82d70c9
069adbe
 
 
 
 
43df572
069adbe
 
 
 
 
 
 
52391b5
 
 
 
069adbe
 
 
 
 
 
 
 
 
 
 
 
 
 
0c21721
 
ad242a2
 
 
 
 
 
 
 
 
 
 
 
 
bf8ac3e
069adbe
 
 
 
 
43df572
7852820
 
 
 
 
 
 
 
069adbe
 
 
 
 
 
 
28cb5be
 
7852820
ad242a2
28cb5be
7852820
d6a9410
7852820
 
 
ad242a2
7852820
28cb5be
d6a9410
28cb5be
 
 
ad242a2
28cb5be
 
d6a9410
28cb5be
 
 
 
 
 
 
 
 
 
 
2e3cd9d
28cb5be
 
 
069adbe
 
 
43df572
069adbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad242a2
069adbe
 
901bbc5
4af194e
901bbc5
 
 
5492e06
 
 
 
 
6ba45c0
604e91a
61dd8c5
 
 
 
 
f396a8d
069adbe
b9049ff
 
 
 
 
 
069adbe
2e3cd9d
680a8ac
 
2e3cd9d
680a8ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
680a8ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a21253
680a8ac
 
265891c
 
d01aca2
265891c
291f3d7
265891c
 
 
 
d01aca2
265891c
291f3d7
265891c
 
2e3cd9d
 
40fb788
680a8ac
 
 
 
2e3cd9d
 
 
05f2b9c
2e3cd9d
 
 
 
 
 
 
 
 
 
 
05f2b9c
2e3cd9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad14b7e
2e3cd9d
 
 
680a8ac
2e3cd9d
 
 
 
069adbe
255a179
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
 
069adbe
255a179
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
 
069adbe
255a179
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
069adbe
255a179
 
 
 
069adbe
255a179
 
069adbe
255a179
 
069adbe
255a179
 
069adbe
255a179
 
069adbe
255a179
 
 
069adbe
255a179
 
 
 
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
069adbe
255a179
069adbe
255a179
 
069adbe
255a179
 
 
 
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
069adbe
255a179
069adbe
255a179
 
069adbe
255a179
 
 
 
 
 
069adbe
255a179
 
 
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
255a179
 
 
069adbe
255a179
 
 
 
069adbe
255a179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
82d70c9
2e3cd9d
cefd40a
851f97e
8ae5fd1
cefd40a
379368b
517ef17
8ae5fd1
a589040
 
 
8ae5fd1
4088be2
 
 
 
 
 
 
 
 
 
37c59a0
efb1867
642b27d
28cb5be
37c59a0
ba4c85f
2e3cd9d
642b27d
2e3cd9d
37c59a0
05f2b9c
37c59a0
 
fdf735a
 
37c59a0
 
 
 
 
fdf735a
 
37c59a0
 
 
 
 
fdf735a
 
37c59a0
 
 
05f2b9c
fdf735a
 
 
2e3cd9d
 
 
37c59a0
87e0fcb
37c59a0
fdf735a
 
87e0fcb
 
 
 
37c59a0
fdf735a
 
87e0fcb
 
 
 
37c59a0
fdf735a
 
87e0fcb
 
43f4453
2e3cd9d
 
 
520ddc7
517ef17
ab5ff8c
 
520ddc7
20a3bf0
7a8cb18
 
 
 
 
 
0b4291c
efb1867
7a8cb18
e16cb76
57a5f25
0da9464
5404e76
0da9464
 
 
 
0b4291c
efb1867
0da9464
74f9c17
9251b5c
74f9c17
b88e69e
 
4166ef5
 
 
 
 
 
b88e69e
4166ef5
 
 
 
 
 
b88e69e
3b75b70
13857b8
2e3cd9d
13857b8
 
2e3cd9d
74f9c17
4f967b3
fba063e
4f967b3
fba063e
4f967b3
fba063e
379368b
4f967b3
 
 
b88e69e
4f967b3
 
b88e69e
 
 
 
 
 
 
4f967b3
 
b88e69e
 
 
4f967b3
 
 
 
 
 
 
 
 
 
 
 
379368b
c618f4d
b88e69e
20a3bf0
 
b88e69e
 
 
 
 
 
 
20a3bf0
 
b88e69e
 
13857b8
 
20a3bf0
37c59a0
20a3bf0
13857b8
20a3bf0
13857b8
 
4f967b3
 
37c59a0
74f9c17
 
 
37c59a0
74f9c17
37c59a0
3daeb17
 
5481883
 
 
 
3b75b70
5481883
69d924b
 
74f9c17
fba063e
 
 
 
 
 
 
379368b
20a3bf0
37c59a0
3daeb17
 
6a37505
fa47128
3daeb17
 
6a37505
3daeb17
 
 
 
 
 
 
 
 
 
 
20a3bf0
37c59a0
 
3daeb17
 
6a37505
fa47128
3daeb17
 
6a37505
3daeb17
 
 
 
 
 
 
 
 
 
20a3bf0
646dbbe
 
3daeb17
 
fa47128
 
 
 
3daeb17
 
 
fa47128
 
 
 
3daeb17
 
 
fa47128
 
 
 
3daeb17
 
 
 
 
 
 
 
 
 
 
 
646dbbe
 
 
3daeb17
 
fa47128
 
 
 
3daeb17
 
 
fa47128
 
 
 
3daeb17
 
 
fa47128
 
 
 
3daeb17
 
 
 
 
 
 
 
 
 
 
 
646dbbe
911d70e
 
 
4f967b3
 
fba063e
 
 
 
7ac9771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fba063e
 
 
7ac9771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fba063e
 
 
7ac9771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fba063e
 
 
7ac9771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fba063e
 
 
 
 
55d145d
37c59a0
74f9c17
 
 
 
 
ff85862
74f9c17
efb1867
74f9c17
 
 
 
 
 
 
 
2e3cd9d
74f9c17
 
 
 
 
 
2e3cd9d
74f9c17
fba063e
 
 
 
 
 
 
379368b
74f9c17
b3c964e
4f967b3
 
 
fba063e
 
 
 
 
 
43df572
f591d4e
43df572
eb50f14
82d3e88
fba063e
 
 
 
 
 
 
379368b
4f967b3
 
 
 
 
 
 
 
 
 
 
 
 
fba063e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e3cd9d
 
 
 
42c2829
fba063e
 
 
 
 
 
 
2e3cd9d
99b9aa9
4f967b3
 
fba063e
 
99b9aa9
fba063e
 
a281a4f
 
 
 
 
 
 
 
 
 
e7a0def
a281a4f
 
e7a0def
a281a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b90f9a
 
 
 
439e0ac
9b90f9a
 
 
 
a281a4f
 
da65172
 
 
a281a4f
 
 
 
 
9b90f9a
 
 
 
439e0ac
9b90f9a
 
 
 
a281a4f
 
 
 
 
9b90f9a
 
 
 
439e0ac
9b90f9a
 
 
 
a281a4f
 
 
 
 
9b90f9a
 
 
 
439e0ac
9b90f9a
 
 
 
a281a4f
 
 
 
da65172
a281a4f
 
 
da65172
a281a4f
 
 
 
 
 
 
9b90f9a
 
 
 
439e0ac
9b90f9a
 
 
 
a281a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
dce062f
a281a4f
dce062f
a281a4f
 
dce062f
 
 
 
 
 
 
 
 
a281a4f
 
da65172
 
 
dce062f
a281a4f
dce062f
a281a4f
 
dce062f
 
 
 
 
 
 
 
 
a281a4f
 
dce062f
a281a4f
 
dce062f
 
 
 
 
 
 
 
 
a281a4f
 
dce062f
a281a4f
 
dce062f
 
 
 
 
 
 
 
 
a281a4f
 
 
dce062f
da65172
a281a4f
dce062f
a281a4f
da65172
dce062f
a281a4f
 
 
dce062f
a281a4f
 
dce062f
 
 
 
 
 
 
 
 
a281a4f
 
 
 
 
dce062f
a281a4f
 
 
 
 
158eaa8
 
d918500
d148196
01c1482
b2bcefd
dd1aa56
 
1b89d01
3a20f4f
388f2db
84f3f0b
fba063e
 
 
 
 
 
 
cc4f407
58b86c3
8913211
cc4f407
4f967b3
 
1e4e9b8
b42fc89
1e4e9b8
 
 
 
 
 
b42fc89
1e4e9b8
 
 
 
 
 
b42fc89
1e4e9b8
 
 
 
4f967b3
 
b42fc89
 
 
4f967b3
b42fc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f967b3
 
b42fc89
4f967b3
 
 
 
1e4e9b8
4f967b3
b42fc89
4f967b3
 
 
 
1e4e9b8
4f967b3
b42fc89
4f967b3
 
 
 
f548d53
4f967b3
 
 
 
b01e348
0543ffc
4f967b3
fba063e
 
58b86c3
8913211
f548d53
fba063e
 
b42fc89
fba063e
 
 
 
 
b42fc89
fba063e
 
 
 
 
 
b42fc89
fba063e
 
 
 
 
 
b42fc89
 
 
fba063e
b42fc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fba063e
e8c9dac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f548d53
fba063e
 
 
 
b01e348
0543ffc
fba063e
1e4e9b8
6b15752
e39607b
 
 
 
 
57d6a24
 
e39607b
 
 
 
 
57d6a24
 
e39607b
 
 
f8485d4
ad242a2
f8485d4
e39607b
5647915
a589040
5647915
 
8ae5fd1
5647915
90fa87c
 
 
 
a589040
e39607b
 
 
a4a0f62
57d6a24
a4a0f62
57d6a24
a589040
 
11d73be
a589040
11d73be
a589040
 
409a345
a589040
 
 
 
 
 
 
e39607b
57d6a24
fbd7505
ab4dc7d
069adbe
ab4dc7d
 
 
069adbe
ab4dc7d
 
 
 
 
 
 
 
 
 
 
 
 
069adbe
ab4dc7d
 
 
069adbe
ab4dc7d
57d6a24
ab4dc7d
23ffbed
85260c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac28920
1fe7139
ab4dc7d
68208b0
6c81ee5
2e3cd9d
 
 
 
 
e43f97d
2e3cd9d
9682eff
 
00b2e24
9682eff
 
 
 
 
 
65b348b
9682eff
57d6a24
 
 
 
 
 
d23b397
9682eff
 
 
 
00b2e24
9682eff
 
 
 
65b348b
9682eff
57d6a24
 
 
 
 
 
d23b397
9682eff
 
 
00b2e24
9682eff
 
 
 
 
 
65b348b
9682eff
57d6a24
 
 
 
 
 
d23b397
9682eff
2e3cd9d
05f2b9c
2e3cd9d
 
 
00b2e24
2e3cd9d
 
 
 
65b348b
2e3cd9d
57d6a24
 
 
 
 
 
d23b397
2e3cd9d
 
 
00b2e24
2e3cd9d
 
 
 
 
 
65b348b
2e3cd9d
57d6a24
 
 
 
 
 
d23b397
2e3cd9d
05f2b9c
2e3cd9d
 
00b2e24
2e3cd9d
 
 
 
 
 
65b348b
2e3cd9d
57d6a24
 
 
 
 
 
d23b397
2e3cd9d
 
 
 
 
 
 
e43f97d
2e3cd9d
6c81ee5
2e3cd9d
6c81ee5
 
 
 
 
 
0abd3e1
d23b397
 
6c81ee5
 
 
 
2e3cd9d
 
57d6a24
2e3cd9d
 
57d6a24
2e3cd9d
 
 
 
 
57d6a24
2e3cd9d
 
 
 
57d6a24
 
 
 
 
 
d23b397
2e3cd9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d23b397
 
2e3cd9d
 
 
 
6c81ee5
68208b0
 
 
 
 
 
9c68c67
 
 
 
 
c4992bf
 
 
 
9c68c67
 
 
 
 
 
68208b0
 
 
 
 
 
 
 
 
 
 
 
 
 
d23b397
b7746b2
68208b0
 
 
 
 
 
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
import streamlit as st
st.set_page_config(layout="wide")
import pandas as pd
from rapidfuzz import process
import random
from collections import Counter
import io

## import global functions
from global_func.clean_player_name import clean_player_name
from global_func.load_file import load_file
from global_func.load_ss_file import load_ss_file
from global_func.load_dk_fd_file import load_dk_fd_file
from global_func.find_name_mismatches import find_name_mismatches
from global_func.predict_dupes import predict_dupes
from global_func.highlight_rows import highlight_changes, highlight_changes_winners, highlight_changes_losers
from global_func.load_csv import load_csv
from global_func.find_csv_mismatches import find_csv_mismatches
from global_func.trim_portfolio import trim_portfolio
from global_func.get_portfolio_names import get_portfolio_names
from global_func.small_field_preset import small_field_preset
from global_func.large_field_preset import large_field_preset
from global_func.hedging_preset import hedging_preset
from global_func.volatility_preset import volatility_preset
from global_func.reduce_volatility_preset import reduce_volatility_preset
from global_func.analyze_player_combos import analyze_player_combos
from global_func.stratification_function import stratification_function
from global_func.exposure_spread import exposure_spread
from global_func.reassess_edge import reassess_edge
from global_func.recalc_diversity import recalc_diversity

freq_format = {'Finish_percentile': '{:.2%}', 'Lineup Edge': '{:.2%}', 'Win%': '{:.2%}'}
stacking_sports = ['MLB', 'NHL', 'NFL', 'LOL', 'NCAAF']
stack_column_dict = {
    'Draftkings': {
        'Classic': {
            'MLB': ['C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3'],
            'NHL': ['C', 'W', 'D'],
            'NFL': ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX'],
            'LOL': ['TOP', 'JNG', 'MID', 'ADC', 'SUP', 'TEAM'],
            'NCAAF': ['QB', 'WR1', 'WR2', 'WR3', 'FLEX', 'SFLEX'],
        },
        'Showdown': {
            'MLB': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
            'NHL': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
            'NFL': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
            'LOL': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
            'NCAAF': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
        },
    },
    'Fanduel': {
        'Classic': {
            'MLB': ['C/1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL'],
            'NHL': ['C', 'W', 'D'],
            'NFL': ['QB', 'RB1', 'RB2', 'WR1', 'WR2', 'WR3', 'TE', 'FLEX'],
            'LOL': ['TOP', 'JNG', 'MID', 'ADC', 'SUP', 'TEAM'],
            'NCAAF': ['QB', 'WR1', 'WR2', 'WR3', 'FLEX', 'SFLEX'],
        },
        'Showdown': {
            'MLB': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
            'NHL': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
            'NFL': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
            'LOL': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
            'NCAAF': ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5'],
        },
    },
}
player_wrong_names_mlb = ['Enrique Hernandez', 'Joseph Cantillo', 'Mike Soroka', 'Jakob Bauers', 'Temi Fágbénlé']
player_right_names_mlb = ['Kike Hernandez', 'Joey Cantillo', 'Michael Soroka', 'Jake Bauers', 'Temi Fagbenle']

st.markdown("""
<style>
    /* Tab styling */
    .stElementContainer [data-baseweb="button-group"] {
        gap: 2.000rem;
        padding: 4px;
    }
    .stElementContainer [kind="segmented_control"] {
        height: 2.000rem;
        white-space: pre-wrap;
        background-color: #DAA520;
        color: white;
        border-radius: 20px;
        gap: 1px;
        padding: 10px 20px;
        font-weight: bold;
        transition: all 0.3s ease;
    }
    .stElementContainer [kind="segmented_controlActive"] {
        height: 3.000rem;
        background-color: #DAA520;
        border: 3px solid #FFD700;
        border-radius: 10px;
        color: black;
    }
    .stElementContainer [kind="segmented_control"]:hover {
        background-color: #FFD700;
        cursor: pointer;
    }

    div[data-baseweb="select"] > div {
        background-color: #DAA520;
        color: white;
    }

</style>""", unsafe_allow_html=True)

def create_position_export_dict(column_name, csv_file, site_var, type_var, sport_var):
    try:
        # Remove any numbers from the column name to get the position
        import re
        position_filter = re.sub(r'\d+$', '', column_name)

        # Filter CSV file by position
        if 'Position' in csv_file.columns:
            if type_var == 'Showdown':
                filtered_df = csv_file.copy()
            else:
                if position_filter == 'SP':
                    filtered_df = csv_file[
                        csv_file['Roster Position'] == 'P'
                    ]
                elif position_filter == 'CPT':
                    filtered_df = csv_file.copy()
                elif position_filter == 'FLEX' or position_filter == 'UTIL':
                    if sport_var == 'NFL':
                        filtered_df = csv_file[csv_file['Position'].isin(['RB', 'WR', 'TE'])]
                    elif sport_var == 'SOC':
                        filtered_df = csv_file[csv_file['Position'].str.contains('D|M|F', na=False, regex=True)]
                    elif sport_var == 'NCAAF':
                        filtered_df = csv_file[csv_file['Position'].str.contains('RB|WR', na=False, regex=True)]
                    elif sport_var == 'NHL':
                        filtered_df = csv_file[csv_file['Position'].str.contains('C|W|D', na=False, regex=True)]
                    else:
                        filtered_df = csv_file.copy()
                elif position_filter == 'SFLEX':
                    filtered_df = csv_file.copy()
                elif position_filter == 'C/1B':
                    filtered_df = csv_file[
                        csv_file['Position'].str.contains(['C', '1B'], na=False, regex=False)
                    ]
                else:
                    filtered_df = csv_file[
                        csv_file['Position'].str.contains(position_filter, na=False, regex=False)
                    ]
        else:
            # Fallback to all players if no position column found
            filtered_df = csv_file
        
        # Create the export dictionary for this position
        if site_var == 'Draftkings':
            filtered_df = filtered_df.sort_values(by='Salary', ascending=False).drop_duplicates(subset=['Name'])
            return dict(zip(filtered_df['Name'], filtered_df['Name + ID']))
        else:
            filtered_df = filtered_df.sort_values(by='Salary', ascending=False).drop_duplicates(subset=['Nickname'])
            return dict(zip(filtered_df['Nickname'], filtered_df['Id']))
                
    except Exception as e:
        st.error(f"Error creating position export dict for {column_name}: {str(e)}")
        return {}

with st.container():
    
    col1, col2, col3, col4 = st.columns([1, 4, 4, 4])
    with col1:
        if st.button('Clear data', key='reset3'):
            st.session_state.clear()
    with col2:
        site_var = st.selectbox("Select Site", ['Draftkings', 'Fanduel'])

    with col3:
        sport_var = st.selectbox("Select Sport", ['NFL', 'MLB', 'NBA', 'NHL', 'NCAAF', 'MMA', 'CS2', 'LOL', 'TENNIS', 'NASCAR', 'GOLF', 'WNBA', 'F1'])
        
    with col4:
        type_var = st.selectbox("Select Game Type", ['Classic', 'Showdown'])
    
    if sport_var == 'GOLF':
        position_var = 'G'
        team_var = 'GOLF'
    elif sport_var == 'TENNIS':
        position_var = 'T'
        team_var = 'TENNIS'
    elif sport_var == 'MMA':
        position_var = 'F'
        team_var = 'MMA'
    elif sport_var == 'NASCAR':
        position_var = 'D'
        team_var = 'NASCAR'
    elif sport_var == 'F1':
        position_var = 'D'
        team_var = 'F1'
    else:
        position_var = None
        team_var = None

    if site_var == 'Draftkings':
        salary_max = 50000
    elif site_var == 'Fanduel':
        if type_var == 'Classic':
            if sport_var == 'MLB':
                salary_max = 40000
            elif sport_var == 'WNBA':
                salary_max = 40000
            elif sport_var == 'GOLF':
                salary_max = 60000
            elif sport_var == 'MMA':
                salary_max = 100
            elif sport_var == 'NFL':
                salary_max = 60000
            elif sport_var == 'NASCAR':
                salary_max = 50000
            else:
                salary_max = 60000
        elif type_var == 'Showdown':
            salary_max = 60000

try:
    selected_tab = st.segmented_control(
    "Select Tab",
    options=["Data Load", "Manage Portfolio"],
    selection_mode='single',
    default='Data Load',
    label_visibility='collapsed',
    width='stretch',
    key='tab_selector'
    )
except:
    selected_tab = st.segmented_control(
    "Select Tab",
    options=["Data Load", "Manage Portfolio"],
    selection_mode='single',
    default='Data Load',
    label_visibility='collapsed',
    key='tab_selector'
    )

if selected_tab == 'Data Load':
    # Add file uploaders to your app
    col1, col2, col3 = st.columns(3)

    with col1:
        st.subheader("Draftkings/Fanduel CSV")
        st.info("Upload the player pricing CSV from the site you are playing on")

        upload_csv_col, csv_template_col = st.columns([3, 1])
        with upload_csv_col:
            csv_file = st.file_uploader("Upload CSV File", type=['csv'])
            if 'csv_file' in st.session_state:
                del st.session_state['csv_file']
        with csv_template_col:
            if site_var == 'Draftkings':
                csv_template_df = pd.DataFrame(columns=['Name', 'ID', 'Roster Position', 'Salary'])
            else:
                csv_template_df = pd.DataFrame(columns=['Nickname', 'Id', 'Roster Position', 'Salary'])

            st.download_button(
                label="CSV Template",
                data=csv_template_df.to_csv(index=False),
                file_name="csv_template.csv",
                mime="text/csv"
            )
        st.session_state['csv_file'] = load_csv(csv_file)
        try:
            st.session_state['csv_file']['Salary'] = st.session_state['csv_file']['Salary'].astype(str).str.replace(',', '').astype(int)
        except:
            pass
            
        if csv_file:
            if type_var == 'Showdown':
                st.session_state['csv_file']['Position'] = 'FLEX'
            else:
                if sport_var == 'GOLF':
                    st.session_state['csv_file']['Position'] = 'FLEX'
                    st.session_state['csv_file']['Team'] = 'GOLF'
                elif sport_var == 'TENNIS':
                    st.session_state['csv_file']['Position'] = 'FLEX'
                    st.session_state['csv_file']['Team'] = 'TENNIS'
                elif sport_var == 'MMA':
                    st.session_state['csv_file']['Position'] = 'FLEX'
                    st.session_state['csv_file']['Team'] = 'MMA'
                elif sport_var == 'NASCAR':
                    st.session_state['csv_file']['Position'] = 'FLEX'
                    st.session_state['csv_file']['Team'] = 'NASCAR'
            # st.session_state['csv_file'] = st.session_state['csv_file'].drop_duplicates(subset=['Name'])
            st.success('Projections file loaded successfully!')
            st.dataframe(st.session_state['csv_file'].head(10))
    
    with col2:
        st.subheader("Portfolio File")
        st.info("Go ahead and upload a portfolio file here. Only include player columns.")

        upload_toggle = st.selectbox("What source are you uploading from?", options=['SaberSim (Just IDs)', 'Draftkings/Fanduel (Names + IDs)', 'Other (Just Names)'])
        if upload_toggle == 'SaberSim (Just IDs)' or upload_toggle == 'Draftkings/Fanduel (Names + IDs)':
            portfolio_file = st.file_uploader("Upload Portfolio File (CSV or Excel)", type=['csv', 'xlsx', 'xls'])
            if 'portfolio' in st.session_state:
                del st.session_state['portfolio']
            if 'export_portfolio' in st.session_state:
                del st.session_state['export_portfolio']

        else:
            portfolio_file = st.file_uploader("Upload Portfolio File (CSV or Excel)", type=['csv', 'xlsx', 'xls'])
            if 'portfolio' in st.session_state:
                del st.session_state['portfolio']
            if 'export_portfolio' in st.session_state:
                del st.session_state['export_portfolio']
        if 'portfolio' not in st.session_state:
            if portfolio_file:
                if upload_toggle == 'SaberSim (Just IDs)':
                    st.session_state['export_portfolio'], st.session_state['portfolio'] = load_ss_file(portfolio_file, st.session_state['csv_file'], site_var, type_var, sport_var)
                    st.session_state['export_portfolio'] = st.session_state['export_portfolio'].dropna(how='all')
                    st.session_state['export_portfolio'] = st.session_state['export_portfolio'].reset_index(drop=True)

                    st.session_state['portfolio'] = st.session_state['portfolio'].dropna(how='all')
                    st.session_state['portfolio'] = st.session_state['portfolio'].reset_index(drop=True)
                elif upload_toggle == 'Draftkings/Fanduel (Names + IDs)':
                    st.session_state['export_portfolio'], st.session_state['portfolio'] = load_dk_fd_file(portfolio_file, st.session_state['csv_file'], site_var, type_var, sport_var)
                    st.session_state['export_portfolio'] = st.session_state['export_portfolio'].dropna(how='all')
                    st.session_state['export_portfolio'] = st.session_state['export_portfolio'].reset_index(drop=True)

                    st.session_state['portfolio'] = st.session_state['portfolio'].dropna(how='all')
                    st.session_state['portfolio'] = st.session_state['portfolio'].reset_index(drop=True)
                else:
                    st.session_state['export_portfolio'], st.session_state['portfolio'] = load_file(portfolio_file, site_var, type_var, sport_var, 'portfolio')
                    st.session_state['export_portfolio'] = st.session_state['export_portfolio'].dropna(how='all')
                    st.session_state['export_portfolio'] = st.session_state['export_portfolio'].reset_index(drop=True)

                    st.session_state['portfolio'] = st.session_state['portfolio'].dropna(how='all')
                    st.session_state['portfolio'] = st.session_state['portfolio'].reset_index(drop=True)
                # Check if Stack column exists in the portfolio
                if 'Stack' in st.session_state['portfolio'].columns:
                    # Create dictionary mapping index to Stack values
                    stack_dict = dict(zip(st.session_state['portfolio'].index, st.session_state['portfolio']['Stack']))
                    st.write(f"Found {len(stack_dict)} stack assignments")
                    st.session_state['portfolio'] = st.session_state['portfolio'].drop(columns=['Stack'])
                else:
                    stack_dict = None
                if st.session_state['portfolio'] is not None:
                    
                    st.success('Portfolio file loaded successfully!')
                    st.session_state['portfolio'] = st.session_state['portfolio'].apply(lambda x: x.replace(player_wrong_names_mlb, player_right_names_mlb))
                    st.dataframe(st.session_state['portfolio'].head(10))

    with col3:
        st.subheader("Projections File")
        st.info("upload a projections file that has 'player_names', 'salary', 'median', 'ownership', and 'captain ownership' columns. Note that the salary for showdown needs to be the FLEX salary, not the captain salary.")
        
        # Create two columns for the uploader and template button
        upload_col, template_col = st.columns([3, 1])
        
        with upload_col:
            projections_file = st.file_uploader("Upload Projections File (CSV or Excel)", type=['csv', 'xlsx', 'xls'])
            if 'projections_df' in st.session_state:
                del st.session_state['projections_df']
        
        with template_col:
            # Create empty DataFrame with required columns
            template_df = pd.DataFrame(columns=['player_names', 'position', 'team', 'salary', 'median', 'ownership', 'captain ownership'])
            # Add download button for template
            st.download_button(
                label="Template",
                data=template_df.to_csv(index=False),
                file_name="projections_template.csv",
                mime="text/csv"
            )
            
        if projections_file:
            export_projections, projections = load_file(projections_file, site_var, type_var, sport_var, 'projections')
            if projections is not None:
                st.success('Projections file loaded successfully!')
                try:
                    projections['salary'] = projections['salary'].str.replace(',', '').str.replace('$', '').str.replace(' ', '')
                    st.write('replaced salary symbols')
                except:
                    pass
                try:
                    projections['ownership'] = projections['ownership'].str.replace('%', '').str.replace(' ', '')
                    st.write('replaced ownership symbols')
                except:
                    pass
                projections['salary'] = projections['salary'].dropna().astype(int)
                projections['ownership'] = projections['ownership'].astype(float)
                if projections['captain ownership'].isna().all():
                    projections['CPT_Own_raw'] = (projections['ownership'] / 2) * ((100 - (100-projections['ownership']))/100)
                    cpt_own_var = 100 / projections['CPT_Own_raw'].sum()
                    projections['captain ownership'] = projections['CPT_Own_raw'] * cpt_own_var
                    projections = projections.drop(columns='CPT_Own_raw', axis=1)
                            
                projections = projections.apply(lambda x: x.replace(player_wrong_names_mlb, player_right_names_mlb))
                ### if the position column is empty, set to sport_var appropriate position
                if position_var is not None:
                    projections['position'] = position_var
                if team_var is not None:
                    projections['team'] = team_var

                st.dataframe(projections.head(10))

    if portfolio_file and projections_file:
        if st.session_state['portfolio'] is not None and projections is not None:
        
            st.subheader("Name Matching Analysis")
            # Initialize projections_df in session state if it doesn't exist
            # Get unique names from portfolio
            portfolio_names = get_portfolio_names(st.session_state['portfolio'])
            try:
                csv_names = st.session_state['csv_file']['Name'].tolist()
            except:
                csv_names = st.session_state['csv_file']['Nickname'].tolist()
            projection_names = projections['player_names'].tolist()
            
            # Create match dictionary for portfolio names to projection names
            portfolio_match_dict = {}
            unmatched_names = []
            for portfolio_name in portfolio_names:
                match = process.extractOne(
                    portfolio_name,
                    csv_names,
                    score_cutoff=87
                )
                if match:
                    portfolio_match_dict[portfolio_name] = match[0]
                    if match[1] < 100:
                        st.write(f"{portfolio_name} matched from portfolio to site csv {match[0]} with a score of {match[1]}%")
                else:
                    portfolio_match_dict[portfolio_name] = portfolio_name
                    unmatched_names.append(portfolio_name)
            
            # Update portfolio with matched names
            portfolio = st.session_state['portfolio'].copy()
            player_columns = [col for col in portfolio.columns 
                            if col not in ['salary', 'median', 'Own']]
            
            # For each player column, update names using the match dictionary
            for col in player_columns:
                portfolio[col] = portfolio[col].map(lambda x: portfolio_match_dict.get(x, x))
            st.session_state['portfolio'] = portfolio
            
            # Create match dictionary for portfolio names to projection names
            projections_match_dict = {}
            unmatched_proj_names = []
            for projections_name in projection_names:
                match = process.extractOne(
                    projections_name,
                    csv_names,
                    score_cutoff=87
                )
                if match:
                    projections_match_dict[projections_name] = match[0]
                    if match[1] < 100:
                        st.write(f"{projections_name} matched from projections to site csv {match[0]} with a score of {match[1]}%")
                else:
                    projections_match_dict[projections_name] = projections_name
                    unmatched_proj_names.append(projections_name)
            
            # Update projections with matched names
            projections['player_names'] = projections['player_names'].map(lambda x: projections_match_dict.get(x, x))
            st.session_state['projections_df'] = projections

            projections_names = st.session_state['projections_df']['player_names'].tolist()
            portfolio_names = get_portfolio_names(st.session_state['portfolio'])
            
            # Create match dictionary for portfolio names to projection names
            projections_match_dict = {}
            unmatched_proj_names = []
            for projections_name in projection_names:
                match = process.extractOne(
                    projections_name,
                    portfolio_names,
                    score_cutoff=87
                )
                if match:
                    projections_match_dict[projections_name] = match[0]
                    if match[1] < 100:
                        st.write(f"{projections_name} matched from portfolio to projections {match[0]} with a score of {match[1]}%")
                else:
                    projections_match_dict[projections_name] = projections_name
                    unmatched_proj_names.append(projections_name)
            
            # Update projections with matched names
            projections['player_names'] = projections['player_names'].map(lambda x: projections_match_dict.get(x, x))
            st.session_state['projections_df'] = projections

            if sport_var in stacking_sports:
                team_dict = dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['team']))
                st.session_state['portfolio']['Stack'] = st.session_state['portfolio'].apply(
                    lambda row: Counter(
                        team_dict.get(player, '') for player in row[stack_column_dict[site_var][type_var][sport_var]]
                        if team_dict.get(player, '') != ''
                    ).most_common(1)[0][0] if any(team_dict.get(player, '') for player in row[stack_column_dict[site_var][type_var][sport_var]]) else '',
                    axis=1
                )
                st.session_state['portfolio']['Size'] = st.session_state['portfolio'].apply(
                    lambda row: Counter(
                        team_dict.get(player, '') for player in row[stack_column_dict[site_var][type_var][sport_var]]
                        if team_dict.get(player, '') != ''
                    ).most_common(1)[0][1] if any(team_dict.get(player, '') for player in row[stack_column_dict[site_var][type_var][sport_var]]) else 0,
                    axis=1
                )
                st.session_state['stack_dict'] = dict(zip(st.session_state['portfolio'].index, st.session_state['portfolio']['Stack']))
                st.session_state['size_dict'] = dict(zip(st.session_state['portfolio'].index, st.session_state['portfolio']['Size']))

            try:
                st.session_state['export_dict'] = dict(zip(st.session_state['csv_file']['Name'], st.session_state['csv_file']['Name + ID']))
            except:
                st.session_state['export_dict'] = dict(zip(st.session_state['csv_file']['Nickname'], st.session_state['csv_file']['Id']))
            if 'map_dict' not in st.session_state:
                if site_var == 'Draftkings':
                    if type_var == 'Classic':
                        if sport_var == 'CS2' or sport_var == 'LOL':
                            st.session_state['map_dict'] = {
                                'pos_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['position'])),
                                'team_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['team'])),
                                'salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'])),
                                'proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'])),
                                'own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'])),
                                'own_percent_rank':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'].rank(pct=True))),
                                'cpt_salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'] * 1.5)),
                                'cpt_proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'] * 1.5)),
                                'cpt_own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['captain ownership']))
                            }
                        elif sport_var != 'CS2' and sport_var != 'LOL':
                            st.session_state['map_dict'] = {
                                'pos_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['position'])),
                                'team_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['team'])),
                                'salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'])),
                                'proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'])),
                                'own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'])),
                                'own_percent_rank':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'].rank(pct=True))),
                                'cpt_salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'])),
                                'cpt_proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'] * 1.5)),
                                'cpt_own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['captain ownership']))
                            }
                    elif type_var == 'Showdown':
                        if sport_var == 'GOLF':
                            st.session_state['map_dict'] = {
                                'pos_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['position'])),
                                'team_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['team'])),
                                'salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'])),
                                'proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'])),
                                'own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'])),
                                'own_percent_rank':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'].rank(pct=True))),
                                'cpt_salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'])),
                                'cpt_proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'])),
                                'cpt_own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership']))
                            }
                        if sport_var != 'GOLF':
                            st.session_state['map_dict'] = {
                                'pos_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['position'])),
                                'team_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['team'])),
                                'salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'])),
                                'proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'])),
                                'own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'])),
                                'own_percent_rank':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'].rank(pct=True))),
                                'cpt_salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'] * 1.5)),
                                'cpt_proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'] * 1.5)),
                                'cpt_own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['captain ownership']))
                            }
                elif site_var == 'Fanduel':
                    st.session_state['map_dict'] = {
                        'pos_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['position'])),
                        'team_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['team'])),
                        'salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'])),
                        'proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'])),
                        'own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'])),
                        'own_percent_rank':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['ownership'].rank(pct=True))),
                        'cpt_salary_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['salary'] * 1.5)),
                        'cpt_proj_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['median'] * 1.5)),
                        'cpt_own_map':dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['captain ownership']))
                    }
            st.session_state['origin_portfolio'] = st.session_state['portfolio'].copy()
            buffer = io.BytesIO()
            st.session_state['portfolio'].to_parquet(buffer, compression='snappy')
            st.session_state['origin_portfolio'] = buffer.getvalue()
            del st.session_state['portfolio']

# with tab2:
#     if st.button('Clear data', key='reset2'):
#         st.session_state.clear()
    
#     if 'portfolio' in st.session_state and 'projections_df' in st.session_state:

#         optimized_df = None

#         map_dict = {
#                     'pos_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                     st.session_state['projections_df']['position'])),
#                     'salary_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                         st.session_state['projections_df']['salary'])),
#                     'proj_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                     st.session_state['projections_df']['median'])),
#                     'own_map': dict(zip(st.session_state['projections_df']['player_names'],
#                                     st.session_state['projections_df']['ownership'])),
#                     'team_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                         st.session_state['projections_df']['team']))
#                 }
#         # Calculate new stats for optimized lineups
#         st.session_state['portfolio']['salary'] = st.session_state['portfolio'].apply(
#             lambda row: sum(map_dict['salary_map'].get(player, 0) for player in row if player in map_dict['salary_map']), axis=1
#         )
#         st.session_state['portfolio']['median'] = st.session_state['portfolio'].apply(
#             lambda row: sum(map_dict['proj_map'].get(player, 0) for player in row if player in map_dict['proj_map']), axis=1
#         )

#         st.session_state['portfolio']['Own'] = st.session_state['portfolio'].apply(
#             lambda row: sum(map_dict['own_map'].get(player, 0) for player in row if player in map_dict['own_map']), axis=1
#         )

#         options_container = st.container()
#         with options_container:
#             col1, col2, col3, col4, col5, col6 = st.columns(6)
#             with col1:
#                 curr_site_var = st.selectbox("Select your current site", options=['DraftKings', 'FanDuel'])
#             with col2:
#                 curr_sport_var = st.selectbox("Select your current sport", options=['NBA', 'MLB', 'NFL', 'NHL', 'MMA'])
#             with col3:
#                 swap_var = st.multiselect("Select late swap strategy", options=['Optimize', 'Increase volatility', 'Decrease volatility'])
#             with col4:
#                 remove_teams_var = st.multiselect("What teams have already played?", options=st.session_state['projections_df']['team'].unique())
#             with col5:
#                 winners_var = st.multiselect("Are there any players doing exceptionally well?", options=st.session_state['projections_df']['player_names'].unique(), max_selections=3)
#             with col6:
#                 losers_var = st.multiselect("Are there any players doing exceptionally poorly?", options=st.session_state['projections_df']['player_names'].unique(), max_selections=3)
#         if st.button('Clear Late Swap'):
#             if 'optimized_df' in st.session_state:
#                 del st.session_state['optimized_df']

#             map_dict = {
#                         'pos_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                         st.session_state['projections_df']['position'])),
#                         'salary_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                             st.session_state['projections_df']['salary'])),
#                         'proj_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                         st.session_state['projections_df']['median'])),
#                         'own_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                         st.session_state['projections_df']['ownership'])),
#                         'team_map': dict(zip(st.session_state['projections_df']['player_names'], 
#                                         st.session_state['projections_df']['team']))
#                     }
#             # Calculate new stats for optimized lineups
#             st.session_state['portfolio']['salary'] = st.session_state['portfolio'].apply(
#                 lambda row: sum(map_dict['salary_map'].get(player, 0) for player in row if player in map_dict['salary_map']), axis=1
#             )
#             st.session_state['portfolio']['median'] = st.session_state['portfolio'].apply(
#                 lambda row: sum(map_dict['proj_map'].get(player, 0) for player in row if player in map_dict['proj_map']), axis=1
#             )
#             st.session_state['portfolio']['Own'] = st.session_state['portfolio'].apply(
#                 lambda row: sum(map_dict['own_map'].get(player, 0) for player in row if player in map_dict['own_map']), axis=1
#             )

#         if st.button('Run Late Swap'):
#             st.session_state['portfolio'] = st.session_state['portfolio'].drop(columns=['salary', 'median', 'Own'])
#             if curr_sport_var == 'NBA':
#                 if curr_site_var == 'DraftKings':
#                     st.session_state['portfolio'] = st.session_state['portfolio'].set_axis(['PG', 'SG', 'SF', 'PF', 'C', 'G', 'F', 'UTIL'], axis=1)
#                 else:
#                     st.session_state['portfolio'] = st.session_state['portfolio'].set_axis(['PG', 'PG', 'SG', 'SG', 'SF', 'SF', 'PF', 'PF', 'C'], axis=1)
            
#             # Define roster position rules
#             if curr_site_var == 'DraftKings':
#                 position_rules = {
#                     'PG': ['PG'],
#                     'SG': ['SG'],
#                     'SF': ['SF'],
#                     'PF': ['PF'],
#                     'C': ['C'],
#                     'G': ['PG', 'SG'],
#                     'F': ['SF', 'PF'],
#                     'UTIL': ['PG', 'SG', 'SF', 'PF', 'C']
#                     }
#             else:
#                 position_rules = {
#                     'PG': ['PG'],
#                     'SG': ['SG'],
#                     'SF': ['SF'],
#                     'PF': ['PF'],
#                     'C': ['C'],
#                 }
#             # Create position groups from projections data
#             position_groups = {}
#             for _, player in st.session_state['projections_df'].iterrows():
#                 positions = player['position'].split('/')
#                 for pos in positions:
#                     if pos not in position_groups:
#                         position_groups[pos] = []
#                     position_groups[pos].append({
#                         'player_names': player['player_names'],
#                         'salary': player['salary'],
#                         'median': player['median'],
#                         'ownership': player['ownership'],
#                         'positions': positions  # Store all eligible positions
#                     })

#             def optimize_lineup(row):
#                 current_lineup = []
#                 total_salary = 0
#                 if curr_site_var == 'DraftKings':
#                     salary_cap = 50000
#                 else:
#                     salary_cap = 60000
#                 used_players = set()

#                 # Convert row to dictionary with roster positions
#                 roster = {}
#                 for col, player in zip(row.index, row):
#                     if col not in ['salary', 'median', 'Own', 'Finish_percentile', 'Dupes', 'Lineup Edge']:
#                         roster[col] = {
#                             'name': player,
#                             'position': map_dict['pos_map'].get(player, '').split('/'),
#                             'team': map_dict['team_map'].get(player, ''),
#                             'salary': map_dict['salary_map'].get(player, 0),
#                             'median': map_dict['proj_map'].get(player, 0),
#                             'ownership': map_dict['own_map'].get(player, 0)
#                         }
#                         total_salary += roster[col]['salary']
#                         used_players.add(player)

#                 # Optimize each roster position in random order
#                 roster_positions = list(roster.items())
#                 random.shuffle(roster_positions)
                
#                 for roster_pos, current in roster_positions:
#                     # Skip optimization for players from removed teams
#                     if current['team'] in remove_teams_var:
#                         continue
                    
#                     valid_positions = position_rules[roster_pos]
#                     better_options = []

#                     # Find valid replacements for this roster position
#                     for pos in valid_positions:
#                         if pos in position_groups:
#                             pos_options = [
#                                 p for p in position_groups[pos]
#                                 if p['median'] > current['median']
#                                 and (total_salary - current['salary'] + p['salary']) <= salary_cap
#                                 and p['player_names'] not in used_players
#                                 and any(valid_pos in p['positions'] for valid_pos in valid_positions)
#                                 and map_dict['team_map'].get(p['player_names']) not in remove_teams_var  # Check team restriction
#                             ]
#                             better_options.extend(pos_options)

#                     if better_options:
#                         # Remove duplicates
#                         better_options = {opt['player_names']: opt for opt in better_options}.values()
                        
#                         # Sort by median projection and take the best one
#                         best_replacement = max(better_options, key=lambda x: x['median'])
                        
#                         # Update the lineup and tracking variables
#                         used_players.remove(current['name'])
#                         used_players.add(best_replacement['player_names'])
#                         total_salary = total_salary - current['salary'] + best_replacement['salary']
#                         roster[roster_pos] = {
#                             'name': best_replacement['player_names'],
#                             'position': map_dict['pos_map'][best_replacement['player_names']].split('/'),
#                             'team': map_dict['team_map'][best_replacement['player_names']],
#                             'salary': best_replacement['salary'],
#                             'median': best_replacement['median'],
#                             'ownership': best_replacement['ownership']
#                         }

#                 # Return optimized lineup maintaining original column order
#                 return [roster[pos]['name'] for pos in row.index if pos in roster]

#             def optimize_lineup_winners(row):
#                 current_lineup = []
#                 total_salary = 0
#                 if curr_site_var == 'DraftKings':
#                     salary_cap = 50000
#                 else:
#                     salary_cap = 60000
#                 used_players = set()

#                 # Check if any winners are in the lineup and count them
#                 winners_in_lineup = sum(1 for player in row if player in winners_var)
#                 changes_needed = min(winners_in_lineup, 3) if winners_in_lineup > 0 else 0
#                 changes_made = 0

#                 # Convert row to dictionary with roster positions
#                 roster = {}
#                 for col, player in zip(row.index, row):
#                     if col not in ['salary', 'median', 'Own', 'Finish_percentile', 'Dupes', 'Lineup Edge']:
#                         roster[col] = {
#                             'name': player,
#                             'position': map_dict['pos_map'].get(player, '').split('/'),
#                             'team': map_dict['team_map'].get(player, ''),
#                             'salary': map_dict['salary_map'].get(player, 0),
#                             'median': map_dict['proj_map'].get(player, 0),
#                             'ownership': map_dict['own_map'].get(player, 0)
#                         }
#                         total_salary += roster[col]['salary']
#                         used_players.add(player)

#                 # Only proceed with ownership-based optimization if we have winners in the lineup
#                 if changes_needed > 0:
#                     # Randomize the order of positions to optimize
#                     roster_positions = list(roster.items())
#                     random.shuffle(roster_positions)
                    
#                     for roster_pos, current in roster_positions:
#                         # Stop if we've made enough changes
#                         if changes_made >= changes_needed:
#                             break
                            
#                         # Skip optimization for players from removed teams or if the current player is a winner
#                         if current['team'] in remove_teams_var or current['name'] in winners_var:
#                             continue
                        
#                         valid_positions = list(position_rules[roster_pos])
#                         random.shuffle(valid_positions)
#                         better_options = []

#                         # Find valid replacements with higher ownership
#                         for pos in valid_positions:
#                             if pos in position_groups:
#                                 pos_options = [
#                                     p for p in position_groups[pos]
#                                     if p['ownership'] > current['ownership']
#                                     and p['median'] >= current['median'] - 3
#                                     and (total_salary - current['salary'] + p['salary']) <= salary_cap
#                                     and (total_salary - current['salary'] + p['salary']) >= salary_cap - 1000
#                                     and p['player_names'] not in used_players
#                                     and any(valid_pos in p['positions'] for valid_pos in valid_positions)
#                                     and map_dict['team_map'].get(p['player_names']) not in remove_teams_var
#                                 ]
#                                 better_options.extend(pos_options)

#                         if better_options:
#                             # Remove duplicates
#                             better_options = {opt['player_names']: opt for opt in better_options}.values()
                            
#                             # Sort by ownership and take the highest owned option
#                             best_replacement = max(better_options, key=lambda x: x['ownership'])
                            
#                             # Update the lineup and tracking variables
#                             used_players.remove(current['name'])
#                             used_players.add(best_replacement['player_names'])
#                             total_salary = total_salary - current['salary'] + best_replacement['salary']
#                             roster[roster_pos] = {
#                                 'name': best_replacement['player_names'],
#                                 'position': map_dict['pos_map'][best_replacement['player_names']].split('/'),
#                                 'team': map_dict['team_map'][best_replacement['player_names']],
#                                 'salary': best_replacement['salary'],
#                                 'median': best_replacement['median'],
#                                 'ownership': best_replacement['ownership']
#                             }
#                             changes_made += 1

#                 # Return optimized lineup maintaining original column order
#                 return [roster[pos]['name'] for pos in row.index if pos in roster]
            
#             def optimize_lineup_losers(row):
#                 current_lineup = []
#                 total_salary = 0
#                 if curr_site_var == 'DraftKings':
#                     salary_cap = 50000
#                 else:
#                     salary_cap = 60000
#                 used_players = set()

#                 # Check if any winners are in the lineup and count them
#                 losers_in_lineup = sum(1 for player in row if player in losers_var)
#                 changes_needed = min(losers_in_lineup, 3) if losers_in_lineup > 0 else 0
#                 changes_made = 0

#                 # Convert row to dictionary with roster positions
#                 roster = {}
#                 for col, player in zip(row.index, row):
#                     if col not in ['salary', 'median', 'Own', 'Finish_percentile', 'Dupes', 'Lineup Edge']:
#                         roster[col] = {
#                             'name': player,
#                             'position': map_dict['pos_map'].get(player, '').split('/'),
#                             'team': map_dict['team_map'].get(player, ''),
#                             'salary': map_dict['salary_map'].get(player, 0),
#                             'median': map_dict['proj_map'].get(player, 0),
#                             'ownership': map_dict['own_map'].get(player, 0)
#                         }
#                         total_salary += roster[col]['salary']
#                         used_players.add(player)

#                 # Only proceed with ownership-based optimization if we have winners in the lineup
#                 if changes_needed > 0:
#                     # Randomize the order of positions to optimize
#                     roster_positions = list(roster.items())
#                     random.shuffle(roster_positions)
                    
#                     for roster_pos, current in roster_positions:
#                         # Stop if we've made enough changes
#                         if changes_made >= changes_needed:
#                             break
                            
#                         # Skip optimization for players from removed teams or if the current player is a winner
#                         if current['team'] in remove_teams_var or current['name'] in losers_var:
#                             continue
                        
#                         valid_positions = list(position_rules[roster_pos])
#                         random.shuffle(valid_positions)
#                         better_options = []

#                         # Find valid replacements with higher ownership
#                         for pos in valid_positions:
#                             if pos in position_groups:
#                                 pos_options = [
#                                     p for p in position_groups[pos]
#                                     if p['ownership'] < current['ownership']
#                                     and p['median'] >= current['median'] - 3
#                                     and (total_salary - current['salary'] + p['salary']) <= salary_cap
#                                     and (total_salary - current['salary'] + p['salary']) >= salary_cap - 1000
#                                     and p['player_names'] not in used_players
#                                     and any(valid_pos in p['positions'] for valid_pos in valid_positions)
#                                     and map_dict['team_map'].get(p['player_names']) not in remove_teams_var
#                                 ]
#                                 better_options.extend(pos_options)

#                         if better_options:
#                             # Remove duplicates
#                             better_options = {opt['player_names']: opt for opt in better_options}.values()
                            
#                             # Sort by ownership and take the highest owned option
#                             best_replacement = max(better_options, key=lambda x: x['ownership'])
                            
#                             # Update the lineup and tracking variables
#                             used_players.remove(current['name'])
#                             used_players.add(best_replacement['player_names'])
#                             total_salary = total_salary - current['salary'] + best_replacement['salary']
#                             roster[roster_pos] = {
#                                 'name': best_replacement['player_names'],
#                                 'position': map_dict['pos_map'][best_replacement['player_names']].split('/'),
#                                 'team': map_dict['team_map'][best_replacement['player_names']],
#                                 'salary': best_replacement['salary'],
#                                 'median': best_replacement['median'],
#                                 'ownership': best_replacement['ownership']
#                             }
#                             changes_made += 1

#                 # Return optimized lineup maintaining original column order
#                 return [roster[pos]['name'] for pos in row.index if pos in roster]

#             # Create a progress bar
#             progress_bar = st.progress(0)
#             status_text = st.empty()
            
#             # Process each lineup
#             optimized_lineups = []
#             total_lineups = len(st.session_state['portfolio'])
            
#             for idx, row in st.session_state['portfolio'].iterrows():
#                 # First optimization pass
#                 first_pass = optimize_lineup(row)
#                 first_pass_series = pd.Series(first_pass, index=row.index)

#                 second_pass = optimize_lineup(first_pass_series)
#                 second_pass_series = pd.Series(second_pass, index=row.index)

#                 third_pass = optimize_lineup(second_pass_series)
#                 third_pass_series = pd.Series(third_pass, index=row.index)

#                 fourth_pass = optimize_lineup(third_pass_series)
#                 fourth_pass_series = pd.Series(fourth_pass, index=row.index)

#                 fifth_pass = optimize_lineup(fourth_pass_series)
#                 fifth_pass_series = pd.Series(fifth_pass, index=row.index)
                
#                 # Second optimization pass
#                 final_lineup = optimize_lineup(fifth_pass_series)
#                 optimized_lineups.append(final_lineup)
                
#                 if 'Optimize' in swap_var:
#                     progress = (idx + 1) / total_lineups
#                     progress_bar.progress(progress)
#                     status_text.text(f'Optimizing Lineups {idx + 1} of {total_lineups}')
#                 else:
#                     pass
            
#             # Create new dataframe with optimized lineups
#             if 'Optimize' in swap_var:
#                 st.session_state['optimized_df_medians'] = pd.DataFrame(optimized_lineups, columns=st.session_state['portfolio'].columns)
#             else:
#                 st.session_state['optimized_df_medians'] = st.session_state['portfolio']

#             # Create a progress bar
#             progress_bar_winners = st.progress(0)
#             status_text_winners = st.empty()
            
#             # Process each lineup
#             optimized_lineups_winners = []
#             total_lineups = len(st.session_state['optimized_df_medians'])
            
#             for idx, row in st.session_state['optimized_df_medians'].iterrows():

#                 final_lineup = optimize_lineup_winners(row)
#                 optimized_lineups_winners.append(final_lineup)
                
#                 if 'Decrease volatility' in swap_var:
#                     progress_winners = (idx + 1) / total_lineups
#                     progress_bar_winners.progress(progress_winners)
#                     status_text_winners.text(f'Lowering Volatility around Winners {idx + 1} of {total_lineups}')
#                 else:
#                     pass
            
#             # Create new dataframe with optimized lineups
#             if 'Decrease volatility' in swap_var:
#                 st.session_state['optimized_df_winners'] = pd.DataFrame(optimized_lineups_winners, columns=st.session_state['optimized_df_medians'].columns)
#             else:
#                 st.session_state['optimized_df_winners'] = st.session_state['optimized_df_medians']

#             # Create a progress bar
#             progress_bar_losers = st.progress(0)
#             status_text_losers = st.empty()
            
#             # Process each lineup
#             optimized_lineups_losers = []
#             total_lineups = len(st.session_state['optimized_df_winners'])
            
#             for idx, row in st.session_state['optimized_df_winners'].iterrows():

#                 final_lineup = optimize_lineup_losers(row)
#                 optimized_lineups_losers.append(final_lineup)
                
#                 if 'Increase volatility' in swap_var:
#                     progress_losers = (idx + 1) / total_lineups
#                     progress_bar_losers.progress(progress_losers)
#                     status_text_losers.text(f'Increasing Volatility around Losers {idx + 1} of {total_lineups}')
#                 else:
#                     pass
            
#             # Create new dataframe with optimized lineups
#             if 'Increase volatility' in swap_var:
#                 st.session_state['optimized_df'] = pd.DataFrame(optimized_lineups_losers, columns=st.session_state['optimized_df_winners'].columns)
#             else:
#                 st.session_state['optimized_df'] = st.session_state['optimized_df_winners']
            
#             # Calculate new stats for optimized lineups
#             st.session_state['optimized_df']['salary'] = st.session_state['optimized_df'].apply(
#                 lambda row: sum(map_dict['salary_map'].get(player, 0) for player in row if player in map_dict['salary_map']), axis=1
#             )
#             st.session_state['optimized_df']['median'] = st.session_state['optimized_df'].apply(
#                 lambda row: sum(map_dict['proj_map'].get(player, 0) for player in row if player in map_dict['proj_map']), axis=1
#             )
#             st.session_state['optimized_df']['Own'] = st.session_state['optimized_df'].apply(
#                 lambda row: sum(map_dict['own_map'].get(player, 0) for player in row if player in map_dict['own_map']), axis=1
#             )

#             # Display results
#             st.success('Optimization complete!')

#         if 'optimized_df' in st.session_state:
#             st.write("Increase in median highlighted in yellow, descrease in volatility highlighted in blue, increase in volatility highlighted in red:")
#             st.dataframe(
#                 st.session_state['optimized_df'].style
#                 .apply(highlight_changes, axis=1)
#                 .apply(highlight_changes_winners, axis=1)
#                 .apply(highlight_changes_losers, axis=1)
#                 .background_gradient(axis=0)
#                 .background_gradient(cmap='RdYlGn')
#                 .format(precision=2),
#                 height=1000,
#                 use_container_width=True
#             )
            
#             # Option to download optimized lineups
#             if st.button('Prepare Late Swap Export'):
#                 export_df = st.session_state['optimized_df'].copy()
                
#                 # Map player names to their export IDs for all player columns
#                 for col in export_df.columns:
#                     if col not in ['salary', 'median', 'Own']:
#                         export_df[col] = export_df[col].map(st.session_state['export_dict'])
                
#                 csv = export_df.to_csv(index=False)
#                 st.download_button(
#                     label="Download CSV",
#                     data=csv,
#                     file_name="optimized_lineups.csv",
#                     mime="text/csv"
#                 )
#         else:
#             st.write("Current Portfolio")
#             st.dataframe(
#                 st.session_state['portfolio'].style
#                 .background_gradient(axis=0)
#                 .background_gradient(cmap='RdYlGn')
#                 .format(precision=2),
#                 height=1000,
#                 use_container_width=True
#             )

if selected_tab == 'Manage Portfolio':
    if 'origin_portfolio' in st.session_state and 'projections_df' in st.session_state:
        with st.container():
            reset_port_col, recalc_div_col, blank_reset_col, contest_size_col = st.columns([1, 1, 6, 4])
            with reset_port_col:
                if st.button('Reset Portfolio', key='reset_port'):
                    st.session_state['settings_base'] = True
                    st.session_state['working_frame'] = st.session_state['base_frame'].copy()
            with recalc_div_col:
                if st.button("Recalculate Diversity"):
                        st.session_state['display_frame']['Diversity'] = recalc_diversity(st.session_state['display_frame'], st.session_state['player_columns'])

            with contest_size_col:
                with st.form(key='contest_size_form'):
                    size_col, strength_col, submit_col = st.columns(3)
                    with size_col:
                        Contest_Size = st.number_input("Enter Contest Size", value=25000, min_value=1, step=1)
                    with strength_col:
                        strength_var = st.selectbox("Select field strength", ['Average', 'Sharp', 'Weak'])
                    with submit_col:
                        submitted = st.form_submit_button("Submit Size/Strength")
                    if submitted:
                        del st.session_state['working_frame']
        
        excluded_cols = ['salary', 'median', 'Own', 'Finish_percentile', 'Dupes', 'Stack', 'Size', 'Win%', 'Lineup Edge', 'Weighted Own', 'Geomean', 'Diversity']
        

        if 'working_frame' not in st.session_state:
            st.session_state['settings_base'] = True
            st.session_state['working_frame'] = pd.read_parquet(io.BytesIO(st.session_state['origin_portfolio']))
            st.session_state['player_columns'] = [col for col in st.session_state['working_frame'].columns if col not in excluded_cols]
            
            if type_var == 'Classic':
                if sport_var == 'CS2' or sport_var == 'LOL':
                    # Calculate salary (CPT uses cpt_salary_map, others use salary_map)
                    st.session_state['working_frame']['salary'] = st.session_state['working_frame'].apply(
                        lambda row: st.session_state['map_dict']['cpt_salary_map'].get(row.iloc[0], 0) + 
                                sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row.iloc[1:]),
                        axis=1
                    )
                    
                    # Calculate median (CPT uses cpt_proj_map, others use proj_map)
                    st.session_state['working_frame']['median'] = st.session_state['working_frame'].apply(
                        lambda row: st.session_state['map_dict']['cpt_proj_map'].get(row.iloc[0], 0) + 
                                sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row.iloc[1:]),
                        axis=1
                    )
                    
                    # Calculate ownership (CPT uses cpt_own_map, others use own_map)
                    st.session_state['working_frame']['Own'] = st.session_state['working_frame'].apply(
                        lambda row: st.session_state['map_dict']['cpt_own_map'].get(row.iloc[0], 0) + 
                                sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row.iloc[1:]),
                        axis=1
                    )

                elif sport_var != 'CS2' and sport_var != 'LOL':
                    st.session_state['working_frame']['salary'] = st.session_state['working_frame'].apply(lambda row: sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row), axis=1)
                    st.session_state['working_frame']['median'] = st.session_state['working_frame'].apply(lambda row: sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row), axis=1)
                    st.session_state['working_frame']['Own'] = st.session_state['working_frame'].apply(lambda row: sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row), axis=1)
                    if 'stack_dict' in st.session_state:
                        st.session_state['working_frame']['Stack'] = st.session_state['working_frame'].index.map(st.session_state['stack_dict'])
                        st.session_state['working_frame']['Size'] = st.session_state['working_frame'].index.map(st.session_state['size_dict'])
            elif type_var == 'Showdown':
                # Calculate salary (CPT uses cpt_salary_map, others use salary_map)
                st.session_state['working_frame']['salary'] = st.session_state['working_frame'].apply(
                    lambda row: st.session_state['map_dict']['cpt_salary_map'].get(row.iloc[0], 0) + 
                            sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row.iloc[1:]),
                    axis=1
                )
                
                # Calculate median (CPT uses cpt_proj_map, others use proj_map)
                st.session_state['working_frame']['median'] = st.session_state['working_frame'].apply(
                    lambda row: st.session_state['map_dict']['cpt_proj_map'].get(row.iloc[0], 0) + 
                            sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row.iloc[1:]),
                    axis=1
                )
                
                # Calculate ownership (CPT uses cpt_own_map, others use own_map)
                st.session_state['working_frame']['Own'] = st.session_state['working_frame'].apply(
                    lambda row: st.session_state['map_dict']['cpt_own_map'].get(row.iloc[0], 0) + 
                            sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row.iloc[1:]),
                    axis=1
                )
            # st.session_state['working_frame']['Own'] = st.session_state['working_frame']['Own'].astype('float32')
            st.session_state['working_frame']['median'] = st.session_state['working_frame']['median'].astype('float32')
            st.session_state['working_frame']['salary'] = st.session_state['working_frame']['salary'].astype('uint16')
            
            st.session_state['base_frame'], check_frame = predict_dupes(st.session_state['working_frame'], st.session_state['map_dict'], site_var, type_var, Contest_Size, strength_var, sport_var, salary_max)
            st.session_state['working_frame'] = st.session_state['base_frame'].copy()
            # st.session_state['highest_owned_teams'] = st.session_state['projections_df'][~st.session_state['projections_df']['position'].isin(['P', 'SP'])].groupby('team')['ownership'].sum().sort_values(ascending=False).head(3).index.tolist()
            # st.session_state['highest_owned_pitchers'] = st.session_state['projections_df'][st.session_state['projections_df']['position'].isin(['P', 'SP'])]['player_names'].sort_values(by='ownership', ascending=False).head(3).tolist()
            st.table(check_frame)

            if 'trimming_dict_maxes' not in st.session_state:
                st.session_state['trimming_dict_maxes'] = {
                    'Own': st.session_state['working_frame']['Own'].max(),
                    'Geomean': st.session_state['working_frame']['Geomean'].max(),
                    'Weighted Own': st.session_state['working_frame']['Weighted Own'].max(),
                    'median': st.session_state['working_frame']['median'].max(),
                    'Finish_percentile': st.session_state['working_frame']['Finish_percentile'].max(),
                    'Diversity': st.session_state['working_frame']['Diversity'].max()
                }

        with st.sidebar:
            if 'trimming_dict_maxes' not in st.session_state:
                st.session_state['trimming_dict_maxes'] = {
                    'Own': 500.0,
                    'Geomean': 500.0,
                    'Weighted Own': 500.0,
                    'median': 500.0,
                    'Finish_percentile': 1.0,
                    'Diversity': 1.0
                }
            with st.expander('Macro Filter Options'):
                # recent changes for showdown included
                with st.form(key='macro_filter_form'):
                    macro_min_col, macro_max_col = st.columns(2)
                    with macro_min_col:
                        min_salary = st.number_input("Min acceptable salary?", value=0, min_value=0, max_value=salary_max, step=100)
                        min_proj = st.number_input("Min acceptable projection?", value=0.0, min_value=0.0, max_value=500.0, step=1.0)
                        min_own = st.number_input("Min acceptable ownership?", value=0.0, min_value=0.0, max_value=500.0, step=1.0)
                        min_dupes = st.number_input("Min acceptable dupes?", value=0, min_value=0, max_value=1000, step=1)
                        min_finish_percentile = st.number_input("Min acceptable finish percentile?", value=0.00, min_value=0.00, max_value=1.00, step=.001)
                        min_lineup_edge = st.number_input("Min acceptable Lineup Edge?", value=-1.00, min_value=-1.00, max_value=1.00, step=.001)
                    with macro_max_col:
                        max_salary = st.number_input("Max acceptable salary?", value=salary_max, min_value=0, max_value=salary_max, step=100)
                        max_proj = st.number_input("Max acceptable projection?", value=500.0, min_value=0.0, max_value=500.0, step=1.0)
                        max_own = st.number_input("Max acceptable ownership?", value=500.0, min_value=0.0, max_value=500.0, step=1.0)
                        max_dupes = st.number_input("Max acceptable dupes?", value=1000, min_value=1, max_value=1000, step=1)
                        max_finish_percentile = st.number_input("Max acceptable finish percentile?", value=1.00, min_value=0.00, max_value=1.00, step=.001)
                        max_lineup_edge = st.number_input("Max acceptable Lineup Edge?", value=1.00, min_value=-1.00, max_value=1.00, step=.001)

                    if sport_var in stacking_sports:
                        stack_include_toggle = st.selectbox("Include specific stacks?", options=['All Stacks', 'Specific Stacks'], index=0)
                        stack_selections = st.multiselect("If Specific Stacks, Which to include?", options=sorted(list(set(st.session_state['stack_dict'].values()))), default=[])

                        stack_remove_toggle = st.selectbox("Remove specific stacks?", options=['No', 'Yes'], index=0)
                        stack_remove = st.multiselect("If Specific Stacks, Which to remove?", options=sorted(list(set(st.session_state['stack_dict'].values()))), default=[])
                    
                    submitted_col, export_col = st.columns(2)
                    st.info("Portfolio Button applies to your overall Portfolio, Export button applies to your Custom Export")
                    with submitted_col:
                        reg_submitted = st.form_submit_button("Portfolio")
                    with export_col:
                        exp_submitted = st.form_submit_button("Export")
                    
                    if reg_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = st.session_state['working_frame'].copy()
                        
                        parsed_frame = parsed_frame[parsed_frame['salary'] >= min_salary]
                        parsed_frame = parsed_frame[parsed_frame['salary'] <= max_salary]
                        parsed_frame = parsed_frame[parsed_frame['median'] >= min_proj]
                        parsed_frame = parsed_frame[parsed_frame['median'] <= max_proj]
                        parsed_frame = parsed_frame[parsed_frame['Own'] >= min_own]
                        parsed_frame = parsed_frame[parsed_frame['Own'] <= max_own]
                        parsed_frame = parsed_frame[parsed_frame['Dupes'] >= min_dupes]
                        parsed_frame = parsed_frame[parsed_frame['Dupes'] <= max_dupes]
                        parsed_frame = parsed_frame[parsed_frame['Finish_percentile'] >= min_finish_percentile]
                        parsed_frame = parsed_frame[parsed_frame['Finish_percentile'] <= max_finish_percentile]
                        parsed_frame = parsed_frame[parsed_frame['Lineup Edge'] >= min_lineup_edge]
                        parsed_frame = parsed_frame[parsed_frame['Lineup Edge'] <= max_lineup_edge]
                        
                        
                        if 'Stack' in parsed_frame.columns:
                            if stack_include_toggle == 'All Stacks':
                                parsed_frame = parsed_frame
                            else:
                                parsed_frame = parsed_frame[parsed_frame['Stack'].isin(stack_selections)]
                            if stack_remove_toggle == 'Yes':
                                parsed_frame = parsed_frame[~parsed_frame['Stack'].isin(stack_remove)]
                            else:
                                parsed_frame = parsed_frame
                        st.session_state['working_frame'] = parsed_frame.sort_values(by='median', ascending=False).reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['working_frame'].copy()
                    if exp_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = st.session_state['export_base'].copy()

                        parsed_frame = parsed_frame[parsed_frame['salary'] >= min_salary]
                        parsed_frame = parsed_frame[parsed_frame['salary'] <= max_salary]
                        parsed_frame = parsed_frame[parsed_frame['median'] >= min_proj]
                        parsed_frame = parsed_frame[parsed_frame['median'] <= max_proj]
                        parsed_frame = parsed_frame[parsed_frame['Own'] >= min_own]
                        parsed_frame = parsed_frame[parsed_frame['Own'] <= max_own]
                        parsed_frame = parsed_frame[parsed_frame['Dupes'] >= min_dupes]
                        parsed_frame = parsed_frame[parsed_frame['Dupes'] <= max_dupes]
                        parsed_frame = parsed_frame[parsed_frame['Finish_percentile'] >= min_finish_percentile]
                        parsed_frame = parsed_frame[parsed_frame['Finish_percentile'] <= max_finish_percentile]
                        parsed_frame = parsed_frame[parsed_frame['Lineup Edge'] >= min_lineup_edge]
                        parsed_frame = parsed_frame[parsed_frame['Lineup Edge'] <= max_lineup_edge]

                        if 'Stack' in parsed_frame.columns:
                            if stack_include_toggle == 'All Stacks':
                                parsed_frame = parsed_frame
                            else:
                                parsed_frame = parsed_frame[parsed_frame['Stack'].isin(stack_selections)]
                            if stack_remove_toggle == 'Yes':
                                parsed_frame = parsed_frame[~parsed_frame['Stack'].isin(stack_remove)]
                            else:
                                parsed_frame = parsed_frame
                        st.session_state['export_base'] = parsed_frame.sort_values(by='median', ascending=False).reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['export_base'].copy()

            with st.expander('Micro Filter Options'):
                with st.form(key='micro_filter_form'):
                    player_names = set()
                    for col in st.session_state['working_frame'].columns:
                        if col not in excluded_cols:
                            player_names.update(st.session_state['working_frame'][col].unique())
                    if type_var == 'Showdown':
                        cpt_flex_focus = st.selectbox("Focus on Overall, CPT, or FLEX?", options=['Overall', 'CPT', 'FLEX'], index=0)
                    player_lock = st.multiselect("Lock players?", options=sorted(list(player_names)), default=[])
                    player_remove = st.multiselect("Remove players?", options=sorted(list(player_names)), default=[])
                    team_include = st.multiselect("Include teams?", options=sorted(list(set(st.session_state['projections_df']['team'].unique()))), default=[])
                    team_remove = st.multiselect("Remove teams?", options=sorted(list(set(st.session_state['projections_df']['team'].unique()))), default=[])
                    if sport_var in stacking_sports:
                        size_include = st.multiselect("Include sizes?", options=sorted(list(set(st.session_state['working_frame']['Size'].unique()))), default=[])
                    else:
                        size_include = []
                    
                    submitted_col, export_col = st.columns(2)
                    st.info("Portfolio Button applies to your overall Portfolio, Export button applies to your Custom Export")
                    with submitted_col:
                        reg_submitted = st.form_submit_button("Portfolio")
                    with export_col:
                        exp_submitted = st.form_submit_button("Export")
                    if reg_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = st.session_state['working_frame'].copy()
                        if player_remove:
                            if type_var == 'Showdown':
                                if cpt_flex_focus == 'CPT':
                                    remove_mask = parsed_frame.iloc[:, 0].apply(
                                        lambda player: not any(remove_player in str(player) for remove_player in player_remove)
                                    )
                                elif cpt_flex_focus == 'FLEX':
                                    remove_mask = parsed_frame.iloc[:, 1:].apply(
                                        lambda row: not any(player in list(row) for player in player_remove), axis=1
                                    )
                                elif cpt_flex_focus == 'Overall':
                                    remove_mask = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda row: not any(player in list(row) for player in player_remove), axis=1
                                    )
                            else:
                                # Create mask for lineups that contain any of the removed players
                                remove_mask = parsed_frame[st.session_state['player_columns']].apply(
                                    lambda row: not any(player in list(row) for player in player_remove), axis=1
                                )
                            parsed_frame = parsed_frame[remove_mask]
                        
                        if player_lock:
                            if type_var == 'Showdown':
                                if cpt_flex_focus == 'CPT':
                                    lock_mask = parsed_frame.iloc[:, 0].apply(
                                        lambda player: any(lock_player in str(player) for lock_player in player_lock)
                                    )
                                elif cpt_flex_focus == 'FLEX':
                                    lock_mask = parsed_frame.iloc[:, 1:].apply(
                                        lambda row: all(player in list(row) for player in player_lock), axis=1
                                    )
                                elif cpt_flex_focus == 'Overall':
                                    lock_mask = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda row: all(player in list(row) for player in player_lock), axis=1
                                    )
                            else:
                                lock_mask = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda row: all(player in list(row) for player in player_lock), axis=1
                                    )
                            parsed_frame = parsed_frame[lock_mask]
                        
                        if team_include:
                            if type_var == 'Showdown':
                                if cpt_flex_focus == 'CPT':
                                    team_frame = parsed_frame.iloc[:, 0].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    include_mask = team_frame.apply(
                                        lambda row: any(team in list(row) for team in team_include), axis=1
                                    )
                                elif cpt_flex_focus == 'FLEX':
                                    team_frame = parsed_frame.iloc[:, 1:].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    include_mask = team_frame.apply(
                                        lambda row: any(team in list(row) for team in team_include), axis=1
                                    )
                                elif cpt_flex_focus == 'Overall':
                                    team_frame = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    include_mask = team_frame.apply(
                                        lambda row: any(team in list(row) for team in team_include), axis=1
                                    )
                            else:
                                # Create a copy of the frame with player names replaced by teams, excluding SP1 and SP2
                                filtered_player_columns = [col for col in st.session_state['player_columns'] if col not in ['SP1', 'SP2']]
                                team_frame = parsed_frame[filtered_player_columns].apply(
                                    lambda x: x.map(st.session_state['map_dict']['team_map'])
                                )
                                # Create mask for lineups that contain any of the included teams
                                include_mask = team_frame.apply(
                                    lambda row: any(team in list(row) for team in team_include), axis=1
                                )
                            parsed_frame = parsed_frame[include_mask]
                        
                        if team_remove:
                            if type_var == 'Showdown':
                                if cpt_flex_focus == 'CPT':
                                    team_frame = parsed_frame.iloc[:, 0].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    remove_mask = team_frame.apply(
                                        lambda row: not any(team in list(row) for team in team_remove), axis=1
                                    )
                                elif cpt_flex_focus == 'FLEX':
                                    team_frame = parsed_frame.iloc[:, 1:].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    remove_mask = team_frame.apply(
                                        lambda row: not any(team in list(row) for team in team_remove), axis=1
                                    )
                                elif cpt_flex_focus == 'Overall':
                                    team_frame = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    remove_mask = team_frame.apply(
                                        lambda row: not any(team in list(row) for team in team_remove), axis=1
                                    )
                            else:
                                # Create a copy of the frame with player names replaced by teams, excluding SP1 and SP2
                                filtered_player_columns = [col for col in st.session_state['player_columns'] if col not in ['SP1', 'SP2']]
                                team_frame = parsed_frame[filtered_player_columns].apply(
                                    lambda x: x.map(st.session_state['map_dict']['team_map'])
                                )
                                # Create mask for lineups that don't contain any of the removed teams
                                remove_mask = team_frame.apply(
                                    lambda row: not any(team in list(row) for team in team_remove), axis=1
                                )
                            parsed_frame = parsed_frame[remove_mask]
                        
                        if size_include:
                            parsed_frame = parsed_frame[parsed_frame['Size'].isin(size_include)]
                        st.session_state['working_frame'] = parsed_frame.sort_values(by='median', ascending=False).reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['working_frame'].copy()
                    elif exp_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = st.session_state['export_base'].copy()
                        if player_remove:
                            if type_var == 'Showdown':
                                if cpt_flex_focus == 'CPT':
                                    remove_mask = parsed_frame.iloc[:, 0].apply(
                                        lambda player: not any(remove_player in str(player) for remove_player in player_remove)
                                    )
                                elif cpt_flex_focus == 'FLEX':
                                    remove_mask = parsed_frame.iloc[:, 1:].apply(
                                        lambda row: not any(player in list(row) for player in player_remove), axis=1
                                    )
                                elif cpt_flex_focus == 'Overall':
                                    remove_mask = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda row: not any(player in list(row) for player in player_remove), axis=1
                                    )
                            else:
                                remove_mask = parsed_frame[st.session_state['player_columns']].apply(
                                    lambda row: not any(player in list(row) for player in player_remove), axis=1
                                )
                            parsed_frame = parsed_frame[remove_mask]
                        
                        if player_lock:
                            if type_var == 'Showdown':
                                if cpt_flex_focus == 'CPT':
                                    lock_mask = parsed_frame.iloc[:, 0].apply(
                                        lambda player: any(lock_player in str(player) for lock_player in player_lock)
                                    )
                                elif cpt_flex_focus == 'FLEX':
                                    lock_mask = parsed_frame.iloc[:, 1:].apply(
                                        lambda row: all(player in list(row) for player in player_lock), axis=1
                                    )
                                elif cpt_flex_focus == 'Overall':
                                    lock_mask = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda row: all(player in list(row) for player in player_lock), axis=1
                                    )
                            else:
                                lock_mask = parsed_frame[st.session_state['player_columns']].apply(
                                    lambda row: all(player in list(row) for player in player_lock), axis=1
                                )
                            parsed_frame = parsed_frame[lock_mask]
                        
                        if team_include:
                            if type_var == 'Showdown':
                                if cpt_flex_focus == 'CPT':
                                    team_frame = parsed_frame.iloc[:, 0].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    include_mask = team_frame.apply(
                                        lambda row: any(team in list(row) for team in team_include), axis=1
                                    )
                                elif cpt_flex_focus == 'FLEX':
                                    team_frame = parsed_frame.iloc[:, 1:].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    include_mask = team_frame.apply(
                                        lambda row: any(team in list(row) for team in team_include), axis=1
                                    )
                                elif cpt_flex_focus == 'Overall':
                                    team_frame = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    include_mask = team_frame.apply(
                                        lambda row: any(team in list(row) for team in team_include), axis=1
                                    )
                            else:
                                # Create a copy of the frame with player names replaced by teams, excluding SP1 and SP2
                                filtered_player_columns = [col for col in st.session_state['player_columns'] if col not in ['SP1', 'SP2']]
                                team_frame = parsed_frame[filtered_player_columns].apply(
                                    lambda x: x.map(st.session_state['map_dict']['team_map'])
                                )
                                # Create mask for lineups that contain any of the included teams
                                include_mask = team_frame.apply(
                                    lambda row: any(team in list(row) for team in team_include), axis=1
                                )
                            parsed_frame = parsed_frame[include_mask]
                        
                        if team_remove:
                            if type_var == 'Showdown':
                                if cpt_flex_focus == 'CPT':
                                    team_frame = parsed_frame.iloc[:, 0].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    remove_mask = team_frame.apply(
                                        lambda row: not any(team in list(row) for team in team_remove), axis=1
                                    )
                                elif cpt_flex_focus == 'FLEX':
                                    team_frame = parsed_frame.iloc[:, 1:].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    remove_mask = team_frame.apply(
                                        lambda row: not any(team in list(row) for team in team_remove), axis=1
                                    )
                                elif cpt_flex_focus == 'Overall':
                                    team_frame = parsed_frame[st.session_state['player_columns']].apply(
                                        lambda x: x.map(st.session_state['map_dict']['team_map'])
                                    )
                                    remove_mask = team_frame.apply(
                                        lambda row: not any(team in list(row) for team in team_remove), axis=1
                                    )
                            else:
                                # Create a copy of the frame with player names replaced by teams, excluding SP1 and SP2
                                filtered_player_columns = [col for col in st.session_state['player_columns'] if col not in ['SP1', 'SP2']]
                                team_frame = parsed_frame[filtered_player_columns].apply(
                                    lambda x: x.map(st.session_state['map_dict']['team_map'])
                                )
                                # Create mask for lineups that don't contain any of the removed teams
                                remove_mask = team_frame.apply(
                                    lambda row: not any(team in list(row) for team in team_remove), axis=1
                                )
                            parsed_frame = parsed_frame[remove_mask]
                        
                        if size_include:
                            parsed_frame = parsed_frame[parsed_frame['Size'].isin(size_include)]
                        st.session_state['export_base'] = parsed_frame.sort_values(by='median', ascending=False).reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['export_base'].copy()

            with st.expander('Trimming Options'):
                with st.form(key='trim_form'):
                    st.write("Sorting and trimming variables:")
                    perf_var, own_var = st.columns(2)
                    with perf_var:
                        performance_type = st.selectbox("Sorting variable", ['median', 'Own', 'Weighted Own'], key='sort_var')
                    with own_var:
                        own_type = st.selectbox("Trimming variable", ['Own', 'Geomean', 'Weighted Own', 'Diversity'], key='trim_var')

                    trim_slack_var = st.number_input("Trim slack (percentile addition to trimming variable ceiling)", value=0.0, min_value=0.0, max_value=1.0, step=0.1, key='trim_slack')

                    st.write("Sorting threshold range:")
                    min_sort, max_sort = st.columns(2)
                    with min_sort:
                        performance_threshold_low = st.number_input("Min", value=0.0, min_value=0.0, step=1.0, key='min_sort')
                    with max_sort:
                        performance_threshold_high = st.number_input("Max", value=float(st.session_state['trimming_dict_maxes'][performance_type]), min_value=0.0, step=1.0, key='max_sort')
                    
                    st.write("Trimming threshold range:")
                    min_trim, max_trim = st.columns(2)
                    with min_trim:
                        own_threshold_low = st.number_input("Min", value=0.0, min_value=0.0, step=1.0, key='min_trim')
                    with max_trim:
                        own_threshold_high = st.number_input("Max", value=float(st.session_state['trimming_dict_maxes'][own_type]), min_value=0.0, step=1.0, key='max_trim')
                    
                    submitted_col, export_col = st.columns(2)
                    st.info("Portfolio Button applies to your overall Portfolio, Export button applies to your Custom Export")
                    with submitted_col:
                        reg_submitted = st.form_submit_button("Portfolio")
                    with export_col:
                        exp_submitted = st.form_submit_button("Export")
                    if reg_submitted:
                        st.session_state['settings_base'] = False
                        st.write('initiated')
                        parsed_frame = st.session_state['working_frame'].copy()
                        parsed_frame = trim_portfolio(parsed_frame, trim_slack_var, performance_type, own_type, performance_threshold_high, performance_threshold_low, own_threshold_high, own_threshold_low)
                        st.session_state['working_frame'] = parsed_frame.sort_values(by='median', ascending=False)
                        st.session_state['export_merge'] = st.session_state['working_frame'].copy()
                    elif exp_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = st.session_state['export_base'].copy()
                        parsed_frame = trim_portfolio(parsed_frame, trim_slack_var, performance_type, own_type, performance_threshold_high, performance_threshold_low, own_threshold_high, own_threshold_low)
                        st.session_state['export_base'] = parsed_frame.sort_values(by='median', ascending=False)
                        st.session_state['export_merge'] = st.session_state['export_base'].copy()
            with st.expander('Presets'):
                st.info("Still heavily in testing here, I'll announce when they are ready for use.")
                with st.form(key='Small Field Preset'):
                    preset_choice = st.selectbox("Preset", options=['Small Field (Heavy Own)', 'Large Field (Manage Diversity)', 'Hedge Chalk (Manage Leverage)', 'Volatility (Heavy Lineup Edge)'], index=0)
                    lineup_target = st.number_input("Lineups to produce", value=150, min_value=1, step=1)
                    submitted_col, export_col = st.columns(2)
                    st.info("Portfolio Button applies to your overall Portfolio, Export button applies to your Custom Export")
                    with submitted_col:
                        reg_submitted = st.form_submit_button("Portfolio")
                    with export_col:
                        exp_submitted = st.form_submit_button("Export")
                    if reg_submitted:
                        st.session_state['settings_base'] = False
                        if preset_choice == 'Small Field (Heavy Own)':
                            parsed_frame = small_field_preset(st.session_state['working_frame'], lineup_target, excluded_cols, sport_var)
                        elif preset_choice == 'Large Field (Manage Diversity)':
                            parsed_frame = large_field_preset(st.session_state['working_frame'], lineup_target, excluded_cols, sport_var)
                        elif preset_choice == 'Volatility (Heavy Lineup Edge)':
                            parsed_frame = volatility_preset(st.session_state['working_frame'], lineup_target, excluded_cols, sport_var)
                        elif preset_choice == 'Hedge Chalk (Manage Leverage)':
                            parsed_frame = hedging_preset(st.session_state['working_frame'], lineup_target, st.session_state['projections_df'], sport_var)
                        elif preset_choice == 'Reduce Volatility (Manage Own)':
                            parsed_frame = reduce_volatility_preset(st.session_state['working_frame'], lineup_target, excluded_cols, sport_var)

                        st.session_state['working_frame'] = parsed_frame.reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['working_frame'].copy()
                    elif exp_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = st.session_state['export_base'].copy()
                        if preset_choice == 'Small Field (Heavy Own)':
                            parsed_frame = small_field_preset(st.session_state['export_base'], lineup_target, excluded_cols, sport_var)
                        elif preset_choice == 'Large Field (Manage Diversity)':
                            parsed_frame = large_field_preset(st.session_state['export_base'], lineup_target, excluded_cols, sport_var)
                        elif preset_choice == 'Volatility (Heavy Lineup Edge)':
                            parsed_frame = volatility_preset(st.session_state['export_base'], lineup_target, excluded_cols, sport_var)
                        elif preset_choice == 'Hedge Chalk (Manage Leverage)':
                            parsed_frame = hedging_preset(st.session_state['export_base'], lineup_target, st.session_state['projections_df'], sport_var)
                        elif preset_choice == 'Reduce Volatility (Manage Own)':
                            parsed_frame = reduce_volatility_preset(st.session_state['export_base'], lineup_target, excluded_cols, sport_var)

                        st.session_state['export_base'] = parsed_frame.reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['export_base'].copy()
            with st.expander('Stratify'):
                with st.form(key='Stratification'):
                    sorting_choice = st.selectbox("Stat Choice", options=['median', 'Own', 'Weighted Own', 'Geomean', 'Lineup Edge', 'Finish_percentile', 'Diversity'], index=0)
                    lineup_target = st.number_input("Lineups to produce", value=150, min_value=1, step=1)
                    strat_sample = st.slider("Sample range", value=[0.0, 100.0], min_value=0.0, max_value=100.0, step=1.0)
                    submitted_col, export_col = st.columns(2)
                    st.info("Portfolio Button applies to your overall Portfolio, Export button applies to your Custom Export")
                    with submitted_col:
                        reg_submitted = st.form_submit_button("Portfolio")
                    with export_col:
                        exp_submitted = st.form_submit_button("Export")
                    if reg_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = stratification_function(st.session_state['working_frame'], lineup_target, excluded_cols, sport_var, sorting_choice, strat_sample[0], strat_sample[1])
                        st.session_state['working_frame'] = parsed_frame.reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['working_frame'].copy()
                    elif exp_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = stratification_function(st.session_state['export_base'], lineup_target, excluded_cols, sport_var, sorting_choice, strat_sample[0], strat_sample[1])
                        st.session_state['export_base'] = parsed_frame.reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['export_base'].copy()
            
            with st.expander('Conditionals Manager (players)'):
                # a set of functions for removing lineups that contain a conditional between players and stacks
                with st.form(key='conditional_players_form'):
                    player_names = set()
                    for col in st.session_state['working_frame'].columns:
                        if col not in excluded_cols:
                            player_names.update(st.session_state['working_frame'][col].unique())
                    keep_remove_var = st.selectbox("Conditional:", options=['Keep', 'Remove'], index=0)
                    conditional_side_alpha = st.multiselect("Lineups containing:", options=sorted(list(player_names)), default=[])
                    cpt_flex_alpha = st.selectbox("in slot:", options=['Overall', 'CPT', 'FLEX'], index=0, key='cpt_flex_alpha')
                    conditional_var = st.selectbox("where they also contain:", options=['Any', 'All', 'None'], index=0)
                    conditional_side_beta = st.multiselect("of the following player(s):", options=sorted(list(player_names)), default=[])
                    cpt_flex_beta = st.selectbox("in slot:", options=['Overall', 'CPT', 'FLEX'], index=0, key='cpt_flex_beta')
                    
                    submitted_col, export_col = st.columns(2)
                    st.info("Portfolio Button applies to your overall Portfolio, Export button applies to your Custom Export")
                    with submitted_col:
                        reg_submitted = st.form_submit_button("Portfolio")
                    with export_col:
                        exp_submitted = st.form_submit_button("Export")
                    if reg_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = st.session_state['working_frame'].copy()

                        # Check if we have players selected for both alpha and beta sides
                        if conditional_side_alpha and conditional_side_beta:
                            # Create boolean mask for rows containing ALL players from alpha side
                            alpha_mask = pd.Series([True] * len(parsed_frame), index=parsed_frame.index)
                            for player in conditional_side_alpha:
                                if type_var == 'Showdown':
                                    if cpt_flex_alpha == 'Overall':
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    elif cpt_flex_alpha == 'CPT':
                                        player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                    elif cpt_flex_alpha == 'FLEX':
                                        player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                else:
                                    player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                alpha_mask = alpha_mask & player_present
                            
                            # Only apply beta logic to rows that match alpha condition
                            rows_to_process = alpha_mask
                            
                            # For rows that match alpha condition, check beta condition
                            if conditional_var == 'Any':
                                # Check if row contains ANY of the beta players
                                beta_mask = pd.Series([False] * len(parsed_frame), index=parsed_frame.index)
                                for player in conditional_side_beta:
                                    if type_var == 'Showdown':
                                        if cpt_flex_beta == 'Overall':
                                            player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                        elif cpt_flex_beta == 'CPT':
                                            player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                        elif cpt_flex_beta == 'FLEX':
                                            player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                    else:
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    beta_mask = beta_mask | player_present
                            elif conditional_var == 'All':
                                # Check if row contains ALL of the beta players
                                beta_mask = pd.Series([True] * len(parsed_frame), index=parsed_frame.index)
                                for player in conditional_side_beta:
                                    if type_var == 'Showdown':
                                        if cpt_flex_beta == 'Overall':
                                            player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                        elif cpt_flex_beta == 'CPT':
                                            player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                        elif cpt_flex_beta == 'FLEX':
                                            player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                    else:
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    beta_mask = beta_mask & player_present
                            elif conditional_var == 'None':
                                # Check if row contains NONE of the beta players
                                beta_mask = pd.Series([True] * len(parsed_frame), index=parsed_frame.index)
                                for player in conditional_side_beta:
                                    if type_var == 'Showdown':
                                        if cpt_flex_beta == 'Overall':
                                            player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                        elif cpt_flex_beta == 'CPT':
                                            player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                        elif cpt_flex_beta == 'FLEX':
                                            player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                    else:
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    beta_mask = beta_mask & (~player_present)
                            
                            # Combine conditions: alpha_mask AND beta_mask
                            final_condition = rows_to_process & beta_mask
                            
                            # Apply keep or remove logic
                            if keep_remove_var == 'Keep':
                                parsed_frame = parsed_frame[~rows_to_process | final_condition]
                            else:  # Remove
                                parsed_frame = parsed_frame[~final_condition]
                        
                        elif conditional_side_alpha:
                            # Only alpha side specified - filter based on presence of alpha players
                            alpha_mask = pd.Series([True] * len(parsed_frame), index=parsed_frame.index)
                            for player in conditional_side_alpha:
                                if type_var == 'Showdown':
                                    if cpt_flex_alpha == 'Overall':
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    elif cpt_flex_alpha == 'CPT':
                                        player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                    elif cpt_flex_alpha == 'FLEX':
                                        player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                else:
                                    player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                alpha_mask = alpha_mask & player_present
                            
                            if keep_remove_var == 'Keep':
                                parsed_frame = parsed_frame[alpha_mask]
                            else:  # Remove
                                parsed_frame = parsed_frame[~alpha_mask]

                        st.session_state['working_frame'] = parsed_frame.sort_values(by='median', ascending=False).reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['working_frame'].copy()
                    elif exp_submitted:
                        st.session_state['settings_base'] = False
                        parsed_frame = st.session_state['export_base'].copy()

                        # Check if we have players selected for both alpha and beta sides
                        if conditional_side_alpha and conditional_side_beta:
                            # Create boolean mask for rows containing ALL players from alpha side
                            alpha_mask = pd.Series([True] * len(parsed_frame), index=parsed_frame.index)
                            for player in conditional_side_alpha:
                                if type_var == 'Showdown':
                                    if cpt_flex_alpha == 'Overall':
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    elif cpt_flex_alpha == 'CPT':
                                        player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                    elif cpt_flex_alpha == 'FLEX':
                                        player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                else:
                                    player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                alpha_mask = alpha_mask & player_present
                            
                            # Only apply beta logic to rows that match alpha condition
                            rows_to_process = alpha_mask
                            
                            # For rows that match alpha condition, check beta condition
                            if conditional_var == 'Any':
                                # Check if row contains ANY of the beta players
                                beta_mask = pd.Series([False] * len(parsed_frame), index=parsed_frame.index)
                                for player in conditional_side_beta:
                                    if type_var == 'Showdown':
                                        if cpt_flex_beta == 'Overall':
                                            player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                        elif cpt_flex_beta == 'CPT':
                                            player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                        elif cpt_flex_beta == 'FLEX':
                                            player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                    else:
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    beta_mask = beta_mask | player_present
                            elif conditional_var == 'All':
                                # Check if row contains ALL of the beta players
                                beta_mask = pd.Series([True] * len(parsed_frame), index=parsed_frame.index)
                                for player in conditional_side_beta:
                                    if type_var == 'Showdown':
                                        if cpt_flex_beta == 'Overall':
                                            player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                        elif cpt_flex_beta == 'CPT':
                                            player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                        elif cpt_flex_beta == 'FLEX':
                                            player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                    else:
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    beta_mask = beta_mask & player_present
                            elif conditional_var == 'None':
                                # Check if row contains NONE of the beta players
                                beta_mask = pd.Series([True] * len(parsed_frame), index=parsed_frame.index)
                                for player in conditional_side_beta:
                                    if type_var == 'Showdown':
                                        if cpt_flex_beta == 'Overall':
                                            player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                        elif cpt_flex_beta == 'CPT':
                                            player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                        elif cpt_flex_beta == 'FLEX':
                                            player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                    else:
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    beta_mask = beta_mask & (~player_present)
                            
                            # Combine conditions: alpha_mask AND beta_mask
                            final_condition = rows_to_process & beta_mask
                            
                            # Apply keep or remove logic
                            if keep_remove_var == 'Keep':
                                parsed_frame = parsed_frame[~rows_to_process | final_condition]
                            else:  # Remove
                                parsed_frame = parsed_frame[~final_condition]
                        
                        elif conditional_side_alpha:
                            # Only alpha side specified - filter based on presence of alpha players
                            alpha_mask = pd.Series([True] * len(parsed_frame), index=parsed_frame.index)
                            for player in conditional_side_alpha:
                                if type_var == 'Showdown':
                                    if cpt_flex_alpha == 'Overall':
                                        player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                    elif cpt_flex_alpha == 'CPT':
                                        player_present = parsed_frame.iloc[:, 0].apply(lambda row: player in row)
                                    elif cpt_flex_alpha == 'FLEX':
                                        player_present = parsed_frame.iloc[:, 1:].apply(lambda row: player in row.values, axis=1)
                                else:
                                    player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                player_present = parsed_frame.apply(lambda row: player in row.values, axis=1)
                                alpha_mask = alpha_mask & player_present
                            
                            if keep_remove_var == 'Keep':
                                parsed_frame = parsed_frame[alpha_mask]
                            else:  # Remove
                                parsed_frame = parsed_frame[~alpha_mask]
                        
                        st.session_state['export_base'] = parsed_frame.sort_values(by='median', ascending=False).reset_index(drop=True)
                        st.session_state['export_merge'] = st.session_state['export_base'].copy()

            with st.expander('Exposure Management'):
                with st.form(key='Exposures'):
                    exposure_player = st.selectbox("Player", options=sorted(list(set(st.session_state['projections_df']['player_names'].unique()))), key='exposure_player')
                    exposure_target = st.number_input("Target Exposure", value=.50, min_value=0.0, max_value=1.0, step=0.01)
                    if 'Stack' in st.session_state['working_frame'].columns:
                        ignore_stacks = st.multiselect("Ignore Specific Stacks?", options=sorted(list(set(st.session_state['projections_df']['team'].unique()))), default=[])
                    else:
                        ignore_stacks = []
                    remove_teams_exposure = st.multiselect("Removed/Locked teams?", options=sorted(list(set(st.session_state['projections_df']['team'].unique()))), default=[])
                    specific_replacements = st.multiselect("Specific Replacements?", options=sorted(list(set(st.session_state['projections_df']['player_names'].unique()))), default=[])
                    # Considering making it so Showdown is CPT/FLEX not column specific but eh
                    specific_columns = st.multiselect("Specific Positions?", options=sorted(list(st.session_state['player_columns'])), default=[])
                    submitted_col, export_col = st.columns(2)
                    st.info("Portfolio Button applies to your overall Portfolio, Export button applies to your Custom Export")
                    with submitted_col:
                        reg_submitted = st.form_submit_button("Portfolio")
                    with export_col:
                        exp_submitted = st.form_submit_button("Export")
                    if reg_submitted:
                        st.session_state['settings_base'] = False
                        prior_frame = st.session_state['working_frame'].copy()
                        parsed_frame = exposure_spread(st.session_state['working_frame'], st.session_state['exposure_player'], exposure_target, ignore_stacks, remove_teams_exposure, specific_replacements, specific_columns, st.session_state['projections_df'], sport_var, type_var, salary_max, stacking_sports)
                        
                        if type_var == 'Classic':
                            if sport_var == 'CS2' or sport_var == 'LOL':
                                # Calculate salary (CPT uses cpt_salary_map, others use salary_map)
                                parsed_frame['salary'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_salary_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )
                                
                                # Calculate median (CPT uses cpt_proj_map, others use proj_map)
                                parsed_frame['median'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_proj_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )
                                
                                # Calculate ownership (CPT uses cpt_own_map, others use own_map)
                                parsed_frame['Own'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_own_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )

                            elif sport_var != 'CS2' and sport_var != 'LOL':
                                parsed_frame['salary'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row), axis=1)
                                parsed_frame['median'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row), axis=1)
                                parsed_frame['Own'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row), axis=1)
                                if 'stack_dict' in st.session_state:
                                    team_dict = dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['team']))
                                    if sport_var == 'LOL':
                                        parsed_frame['Stack'] = parsed_frame.apply(
                                            lambda row: Counter(
                                                team_dict.get(player, '') for player in row
                                                if team_dict.get(player, '') != ''
                                            ).most_common(1)[0][0] if any(team_dict.get(player, '') for player in row) else '',
                                            axis=1
                                        )
                                        parsed_frame['Size'] = parsed_frame.apply(
                                            lambda row: Counter(
                                                team_dict.get(player, '') for player in row
                                                if team_dict.get(player, '') != ''
                                            ).most_common(1)[0][1] if any(team_dict.get(player, '') for player in row) else 0,
                                            axis=1
                                        )
                                    else:
                                        parsed_frame['Stack'] = parsed_frame.apply(
                                            lambda row: Counter(
                                                team_dict.get(player, '') for player in row[2:]
                                                if team_dict.get(player, '') != ''
                                            ).most_common(1)[0][0] if any(team_dict.get(player, '') for player in row[2:]) else '',
                                            axis=1
                                        )
                                        parsed_frame['Size'] = parsed_frame.apply(
                                            lambda row: Counter(
                                                team_dict.get(player, '') for player in row[2:]
                                                if team_dict.get(player, '') != ''
                                            ).most_common(1)[0][1] if any(team_dict.get(player, '') for player in row[2:]) else 0,
                                            axis=1
                                        )
                        elif type_var == 'Showdown':
                            # Calculate salary (CPT uses cpt_salary_map, others use salary_map)
                            parsed_frame['salary'] = parsed_frame.apply(
                                lambda row: st.session_state['map_dict']['cpt_salary_map'].get(row.iloc[0], 0) + 
                                        sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row.iloc[1:]),
                                axis=1
                            )
                            
                            # Calculate median (CPT uses cpt_proj_map, others use proj_map)
                            parsed_frame['median'] = parsed_frame.apply(
                                lambda row: st.session_state['map_dict']['cpt_proj_map'].get(row.iloc[0], 0) + 
                                        sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row.iloc[1:]),
                                axis=1
                            )
                            
                            # Calculate ownership (CPT uses cpt_own_map, others use own_map)
                            parsed_frame['Own'] = parsed_frame.apply(
                                lambda row: st.session_state['map_dict']['cpt_own_map'].get(row.iloc[0], 0) + 
                                        sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row.iloc[1:]),
                                axis=1
                            )
                        st.session_state['working_frame'] = parsed_frame.reset_index(drop=True)
                        # st.session_state['working_frame']['Own'] = st.session_state['working_frame']['Own'].astype('float32')
                        st.session_state['working_frame']['median'] = st.session_state['working_frame']['median'].astype('float32')
                        st.session_state['working_frame']['salary'] = st.session_state['working_frame']['salary'].astype('uint16')
                        
                        # st.session_state['working_frame'] = predict_dupes(st.session_state['working_frame'], st.session_state['map_dict'], site_var, type_var, Contest_Size, strength_var, sport_var)
                        st.session_state['working_frame'] = reassess_edge(st.session_state['working_frame'], st.session_state['base_frame'], st.session_state['map_dict'], site_var, type_var, Contest_Size, strength_var, sport_var, salary_max)
                        st.session_state['export_merge'] = st.session_state['working_frame'].copy()
                    elif exp_submitted:
                        st.session_state['settings_base'] = False
                        prior_frame = st.session_state['export_base'].copy()
                        parsed_frame = exposure_spread(st.session_state['export_base'], st.session_state['exposure_player'], exposure_target, ignore_stacks, remove_teams_exposure, specific_replacements, specific_columns, st.session_state['projections_df'], sport_var, type_var, salary_max, stacking_sports)
                        
                        if type_var == 'Classic':
                            if sport_var == 'CS2' or sport_var == 'LOL':
                                parsed_frame['salary'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_salary_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )
                                
                                parsed_frame['median'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_proj_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )
                                
                                # Calculate ownership (CPT uses cpt_own_map, others use own_map)
                                parsed_frame['Own'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_own_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )

                            elif sport_var != 'CS2' and sport_var != 'LOL':
                                parsed_frame['salary'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row), axis=1)
                                parsed_frame['median'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row), axis=1)
                                parsed_frame['Own'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row), axis=1)
                                if 'stack_dict' in st.session_state:
                                    team_dict = dict(zip(st.session_state['projections_df']['player_names'], st.session_state['projections_df']['team']))
                                    if sport_var == 'LOL':
                                        parsed_frame['Stack'] = parsed_frame.apply(
                                            lambda row: Counter(
                                                team_dict.get(player, '') for player in row
                                                if team_dict.get(player, '') != ''
                                            ).most_common(1)[0][0] if any(team_dict.get(player, '') for player in row) else '',
                                            axis=1
                                        )
                                        parsed_frame['Size'] = parsed_frame.apply(
                                            lambda row: Counter(
                                                team_dict.get(player, '') for player in row
                                                if team_dict.get(player, '') != ''
                                            ).most_common(1)[0][1] if any(team_dict.get(player, '') for player in row) else 0,
                                            axis=1
                                        )
                                    else:
                                        parsed_frame['Stack'] = parsed_frame.apply(
                                            lambda row: Counter(
                                                team_dict.get(player, '') for player in row[2:]
                                                if team_dict.get(player, '') != ''
                                            ).most_common(1)[0][0] if any(team_dict.get(player, '') for player in row[2:]) else '',
                                            axis=1
                                        )
                                        parsed_frame['Size'] = parsed_frame.apply(
                                            lambda row: Counter(
                                                team_dict.get(player, '') for player in row[2:]
                                                if team_dict.get(player, '') != ''
                                            ).most_common(1)[0][1] if any(team_dict.get(player, '') for player in row[2:]) else 0,
                                            axis=1
                                        )
                        elif type_var == 'Showdown':
                            if sport_var == 'GOLF':
                                
                                parsed_frame['salary'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row), axis=1)
                                parsed_frame['median'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row), axis=1)
                                parsed_frame['Own'] = parsed_frame.apply(lambda row: sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row), axis=1)
                            else:
                                parsed_frame['salary'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_salary_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['salary_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )
                                
                                # Calculate median (CPT uses cpt_proj_map, others use proj_map)
                                parsed_frame['median'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_proj_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['proj_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )
                                
                                # Calculate ownership (CPT uses cpt_own_map, others use own_map)
                                parsed_frame['Own'] = parsed_frame.apply(
                                    lambda row: st.session_state['map_dict']['cpt_own_map'].get(row.iloc[0], 0) + 
                                            sum(st.session_state['map_dict']['own_map'].get(player, 0) for player in row.iloc[1:]),
                                    axis=1
                                )
                        st.session_state['export_base'] = parsed_frame.reset_index(drop=True)
                        # st.session_state['export_base']['Own'] = st.session_state['export_base']['Own'].astype('float32')
                        st.session_state['export_base']['median'] = st.session_state['export_base']['median'].astype('float32')
                        st.session_state['export_base']['salary'] = st.session_state['export_base']['salary'].astype('uint16')
                        
                        # st.session_state['export_base'] = predict_dupes(st.session_state['export_base'], st.session_state['map_dict'], site_var, type_var, Contest_Size, strength_var, sport_var)
                        st.session_state['export_base'] = reassess_edge(st.session_state['export_base'], st.session_state['base_frame'], st.session_state['map_dict'], site_var, type_var, Contest_Size, strength_var, sport_var, salary_max)
                        st.session_state['export_merge'] = st.session_state['export_base'].copy()
                        
        with st.container():
            if 'export_base' not in st.session_state:
                    st.session_state['export_base'] = pd.DataFrame(columns=st.session_state['working_frame'].columns)
            
            display_frame_source = st.selectbox("Display:", options=['Portfolio', 'Export Base'], key='display_frame_source')
            if display_frame_source == 'Portfolio':
                st.session_state['display_frame'] = st.session_state['working_frame']
                st.session_state['export_file'] = st.session_state['display_frame'].copy()
                
                for col in st.session_state['export_file'].columns:
                    if col not in excluded_cols:
                        st.session_state['export_file'][col] = st.session_state['export_file'][col].map(st.session_state['export_dict'])
            elif display_frame_source == 'Export Base':
                st.session_state['display_frame'] = st.session_state['export_base']
                st.session_state['export_file'] = st.session_state['display_frame'].copy()
                
                for col in st.session_state['export_file'].columns:
                    if col not in excluded_cols:
                        # Create position-specific export dictionary on the fly
                        position_dict = create_position_export_dict(col, st.session_state['csv_file'], site_var, type_var, sport_var)
                        st.session_state['export_file'][col] = st.session_state['export_file'][col].map(position_dict)
            
            if 'export_file' in st.session_state:
                download_port, merge_port, clear_export, add_rows_col, remove_rows_col, blank_export_col = st.columns([1, 1, 1, 2, 2, 6])
                with download_port:
                    st.download_button(label="Download Portfolio", data=st.session_state['export_file'].to_csv(index=False), file_name="portfolio.csv", mime="text/csv")

                with merge_port:
                    if st.button("Add all to Custom Export"):
                        st.session_state['export_base'] = pd.concat([st.session_state['export_base'], st.session_state['export_merge']])
                        st.session_state['export_base'] = st.session_state['export_base'].drop_duplicates()
                        st.session_state['export_base'] = st.session_state['export_base'].reset_index(drop=True)
                    
                with clear_export:
                    if st.button("Clear Custom Export"):
                        st.session_state['export_base'] = pd.DataFrame(columns=st.session_state['working_frame'].columns)
                        if display_frame_source == 'Portfolio':
                            st.session_state['display_frame'] = st.session_state['working_frame']
                        elif display_frame_source == 'Export Base':
                            st.session_state['display_frame'] = st.session_state['export_base']
                    
                with add_rows_col:
                    select_custom_index = st.multiselect("Select rows to add (based on first column):", options=st.session_state['display_frame'].index, default=[])
                    if st.button("Add selected to Custom Export"):
                        st.session_state['export_base'] = pd.concat([st.session_state['export_base'], st.session_state['display_frame'].loc[select_custom_index]])
                    st.session_state['export_base'] = st.session_state['export_base'].drop_duplicates()
                    st.session_state['export_base'] = st.session_state['export_base'].reset_index(drop=True)

                with remove_rows_col:
                    remove_custom_index = st.multiselect("Remove rows (based on first column):", options=st.session_state['display_frame'].index, default=[])
                    if st.button("Remove selected from Display"):
                        st.session_state['display_frame'] = st.session_state['display_frame'].drop(remove_custom_index)
                    st.session_state['display_frame'] = st.session_state['display_frame'].drop_duplicates()
                    st.session_state['display_frame'] = st.session_state['display_frame'].reset_index(drop=True)
                    

            total_rows = len(st.session_state['display_frame'])
            rows_per_page = 500
            total_pages = (total_rows + rows_per_page - 1) // rows_per_page  # Ceiling division

            # Initialize page number in session state if not exists
            if 'current_page' not in st.session_state:
                st.session_state.current_page = 1

            # Display current page range info and pagination control in a single line
            st.write(
                f"Showing rows {(st.session_state.current_page - 1) * rows_per_page + 1} "
                f"to {min(st.session_state.current_page * rows_per_page, total_rows)} of {total_rows}"
            )
            
            # Add page number input
            st.session_state.current_page = st.number_input(
                f"Page (1-{total_pages})", 
                min_value=1, 
                max_value=total_pages,
                value=st.session_state.current_page
            )

            # Calculate start and end indices for current page
            start_idx = (st.session_state.current_page - 1) * rows_per_page
            end_idx = min(start_idx + rows_per_page, total_rows)

            # Get the subset of data for the current page
            current_page_data = st.session_state['display_frame'].iloc[start_idx:end_idx]
            # Display the paginated dataframe first
            st.dataframe(
                current_page_data.style
                .background_gradient(axis=0)
                .background_gradient(cmap='RdYlGn')
                .background_gradient(cmap='RdYlGn_r', subset=['Finish_percentile', 'Own', 'Dupes'])
                .format(freq_format, precision=2),
                column_config={
                    "Finish_percentile": st.column_config.NumberColumn(
                        "Finish%",
                        help="Projected finishing percentile",
                        width="small",
                        min_value=0.0,
                        max_value=1.0
                    ),
                    "Lineup Edge": st.column_config.NumberColumn(
                        "Edge",
                        help="Projected lineup edge",
                        width="small",
                        min_value=-1.0,
                        max_value=1.0
                    ),
                    "Diversity": st.column_config.NumberColumn(
                        "Diversity",
                        help="Projected lineup diversity",
                        width="small",
                        min_value=0.0,
                        max_value=1.0
                    ),
                },
                height=499,
                use_container_width=True
            )
        player_stats_col, stack_stats_col, combos_col = st.tabs(['Player Stats', 'Stack Stats', 'Combos'])
        with player_stats_col:
            if st.button("Analyze Players", key='analyze_players'):
                player_stats = []
                
                if st.session_state['settings_base'] and 'origin_player_exposures' in st.session_state and display_frame_source == 'Portfolio':
                    st.session_state['player_summary'] = st.session_state['origin_player_exposures']
                else:
                    if type_var == 'Showdown':
                        if sport_var == 'GOLF':
                            for player in player_names:
                                player_mask = st.session_state['display_frame'][st.session_state['player_columns']].apply(
                                    lambda row: player in list(row), axis=1
                                )
                                
                                if player_mask.any():
                                    player_stats.append({
                                        'Player': player,
                                        'Position': st.session_state['map_dict']['pos_map'][player],
                                        'Lineup Count': player_mask.sum(),
                                        'Exposure': player_mask.sum() / len(st.session_state['display_frame']),
                                        'Avg Median': st.session_state['display_frame'][player_mask]['median'].mean(),
                                        'Avg Own': st.session_state['display_frame'][player_mask]['Own'].mean(),
                                        'Avg Dupes': st.session_state['display_frame'][player_mask]['Dupes'].mean(),
                                        'Avg Finish %': st.session_state['display_frame'][player_mask]['Finish_percentile'].mean(),
                                        'Avg Lineup Edge': st.session_state['display_frame'][player_mask]['Lineup Edge'].mean(),
                                        'Avg Diversity': st.session_state['display_frame'][player_mask]['Diversity'].mean(),
                                    })
                        else:
                            for player in player_names:
                                # Create mask for lineups where this player is Captain (first column)
                                cpt_mask = st.session_state['display_frame'][st.session_state['player_columns'][0]] == player
                                
                                if cpt_mask.any():
                                    player_stats.append({
                                        'Player': f"{player} (CPT)",
                                        'Position': st.session_state['map_dict']['pos_map'][player],
                                        'Lineup Count': cpt_mask.sum(),
                                        'Exposure': cpt_mask.sum() / len(st.session_state['display_frame']),
                                        'Avg Median': st.session_state['display_frame'][cpt_mask]['median'].mean(),
                                        'Avg Own': st.session_state['display_frame'][cpt_mask]['Own'].mean(),
                                        'Avg Dupes': st.session_state['display_frame'][cpt_mask]['Dupes'].mean(),
                                        'Avg Finish %': st.session_state['display_frame'][cpt_mask]['Finish_percentile'].mean(),
                                        'Avg Lineup Edge': st.session_state['display_frame'][cpt_mask]['Lineup Edge'].mean(),
                                        'Avg Diversity': st.session_state['display_frame'][cpt_mask]['Diversity'].mean(),
                                    })
                                
                                # Create mask for lineups where this player is FLEX (other columns)
                                flex_mask = st.session_state['display_frame'][st.session_state['player_columns'][1:]].apply(
                                    lambda row: player in list(row), axis=1
                                )
                                
                                if flex_mask.any():
                                    player_stats.append({
                                        'Player': f"{player} (FLEX)",
                                        'Position': st.session_state['map_dict']['pos_map'][player],
                                        'Lineup Count': flex_mask.sum(),
                                        'Exposure': flex_mask.sum() / len(st.session_state['display_frame']),
                                        'Avg Median': st.session_state['display_frame'][flex_mask]['median'].mean(),
                                        'Avg Own': st.session_state['display_frame'][flex_mask]['Own'].mean(),
                                        'Avg Dupes': st.session_state['display_frame'][flex_mask]['Dupes'].mean(),
                                        'Avg Finish %': st.session_state['display_frame'][flex_mask]['Finish_percentile'].mean(),
                                        'Avg Lineup Edge': st.session_state['display_frame'][flex_mask]['Lineup Edge'].mean(),
                                        'Avg Diversity': st.session_state['display_frame'][flex_mask]['Diversity'].mean(),
                                    })
                    else:
                        if sport_var == 'CS2' or sport_var == 'LOL':
                            # Handle Captain positions
                            for player in player_names:
                                # Create mask for lineups where this player is Captain (first column)
                                cpt_mask = st.session_state['display_frame'][st.session_state['player_columns'][0]] == player
                                
                                if cpt_mask.any():
                                    player_stats.append({
                                        'Player': f"{player} (CPT)",
                                        'Position': st.session_state['map_dict']['pos_map'][player],
                                        'Lineup Count': cpt_mask.sum(),
                                        'Exposure': cpt_mask.sum() / len(st.session_state['display_frame']),
                                        'Avg Median': st.session_state['display_frame'][cpt_mask]['median'].mean(),
                                        'Avg Own': st.session_state['display_frame'][cpt_mask]['Own'].mean(),
                                        'Avg Dupes': st.session_state['display_frame'][cpt_mask]['Dupes'].mean(),
                                        'Avg Finish %': st.session_state['display_frame'][cpt_mask]['Finish_percentile'].mean(),
                                        'Avg Lineup Edge': st.session_state['display_frame'][cpt_mask]['Lineup Edge'].mean(),
                                        'Avg Diversity': st.session_state['display_frame'][cpt_mask]['Diversity'].mean(),
                                    })
                                
                                # Create mask for lineups where this player is FLEX (other columns)
                                flex_mask = st.session_state['display_frame'][st.session_state['player_columns'][1:]].apply(
                                    lambda row: player in list(row), axis=1
                                )
                                
                                if flex_mask.any():
                                    player_stats.append({
                                        'Player': f"{player} (FLEX)",
                                        'Position': st.session_state['map_dict']['pos_map'][player],
                                        'Lineup Count': flex_mask.sum(),
                                        'Exposure': flex_mask.sum() / len(st.session_state['display_frame']),
                                        'Avg Median': st.session_state['display_frame'][flex_mask]['median'].mean(),
                                        'Avg Own': st.session_state['display_frame'][flex_mask]['Own'].mean(),
                                        'Avg Dupes': st.session_state['display_frame'][flex_mask]['Dupes'].mean(),
                                        'Avg Finish %': st.session_state['display_frame'][flex_mask]['Finish_percentile'].mean(),
                                        'Avg Lineup Edge': st.session_state['display_frame'][flex_mask]['Lineup Edge'].mean(),
                                        'Avg Diversity': st.session_state['display_frame'][flex_mask]['Diversity'].mean(),
                                    })
                        elif sport_var != 'CS2' and sport_var != 'LOL':
                            # Original Classic format processing
                            for player in player_names:
                                player_mask = st.session_state['display_frame'][st.session_state['player_columns']].apply(
                                    lambda row: player in list(row), axis=1
                                )
                                
                                if player_mask.any():
                                    player_stats.append({
                                        'Player': player,
                                        'Position': st.session_state['map_dict']['pos_map'][player],
                                        'Lineup Count': player_mask.sum(),
                                        'Exposure': player_mask.sum() / len(st.session_state['display_frame']),
                                        'Avg Median': st.session_state['display_frame'][player_mask]['median'].mean(),
                                        'Avg Own': st.session_state['display_frame'][player_mask]['Own'].mean(),
                                        'Avg Dupes': st.session_state['display_frame'][player_mask]['Dupes'].mean(),
                                        'Avg Finish %': st.session_state['display_frame'][player_mask]['Finish_percentile'].mean(),
                                        'Avg Lineup Edge': st.session_state['display_frame'][player_mask]['Lineup Edge'].mean(),
                                        'Avg Diversity': st.session_state['display_frame'][player_mask]['Diversity'].mean(),
                                    })
                    
                    player_summary = pd.DataFrame(player_stats)
                    player_summary = player_summary.sort_values('Lineup Count', ascending=False)
                    st.session_state['player_summary'] = player_summary.copy()
                    if 'origin_player_exposures' not in st.session_state:
                        st.session_state['origin_player_exposures'] = player_summary.copy()
                
                st.subheader("Player Summary")
                st.dataframe(
                    st.session_state['player_summary'].style
                    .background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Avg Finish %', 'Avg Own', 'Avg Dupes'])
                    .format({
                        'Avg Median': '{:.2f}',
                        'Avg Own': '{:.2f}',
                        'Avg Dupes': '{:.2f}',
                        'Avg Finish %': '{:.2%}',
                        'Avg Lineup Edge': '{:.2%}',
                        'Exposure': '{:.2%}',
                        'Avg Diversity': '{:.2%}'
                    }),
                    height=400,
                    use_container_width=True
                )
        
        with stack_stats_col:
            if 'Stack' in st.session_state['display_frame'].columns:
                if st.button("Analyze Stacks", key='analyze_stacks'):
                    stack_stats = []
                    stack_columns = [col for col in st.session_state['display_frame'].columns if col.startswith('Stack')]

                    if st.session_state['settings_base'] and 'origin_stack_exposures' in st.session_state and display_frame_source == 'Portfolio':
                        st.session_state['stack_summary'] = st.session_state['origin_stack_exposures']
                    else:
                        for stack in st.session_state['stack_dict'].values():
                            stack_mask = st.session_state['display_frame']['Stack'] == stack
                            if stack_mask.any():
                                stack_stats.append({
                                    'Stack': stack,
                                    'Lineup Count': stack_mask.sum(),
                                    'Exposure': stack_mask.sum() / len(st.session_state['display_frame']),
                                    'Avg Median': st.session_state['display_frame'][stack_mask]['median'].mean(),
                                    'Avg Own': st.session_state['display_frame'][stack_mask]['Own'].mean(),
                                    'Avg Dupes': st.session_state['display_frame'][stack_mask]['Dupes'].mean(),
                                    'Avg Finish %': st.session_state['display_frame'][stack_mask]['Finish_percentile'].mean(),
                                    'Avg Lineup Edge': st.session_state['display_frame'][stack_mask]['Lineup Edge'].mean(),
                                    'Avg Diversity': st.session_state['display_frame'][stack_mask]['Diversity'].mean(),
                                })
                        stack_summary = pd.DataFrame(stack_stats)
                        stack_summary = stack_summary.sort_values('Lineup Count', ascending=False).drop_duplicates()
                        st.session_state['stack_summary'] = stack_summary.copy()
                        if 'origin_stack_exposures' not in st.session_state:
                            st.session_state['origin_stack_exposures'] = stack_summary.copy()

                    st.subheader("Stack Summary")
                    st.dataframe(
                        st.session_state['stack_summary'].style
                        .background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Avg Finish %', 'Avg Own', 'Avg Dupes'])
                        .format({
                            'Avg Median': '{:.2f}',
                            'Avg Own': '{:.2f}',
                            'Avg Dupes': '{:.2f}',
                            'Avg Finish %': '{:.2%}',
                            'Avg Lineup Edge': '{:.2%}',
                            'Exposure': '{:.2%}',
                            'Avg Diversity': '{:.2%}'
                        }),
                        height=400,
                        use_container_width=True
                    )
            else:
                stack_summary = pd.DataFrame(columns=['Stack', 'Lineup Count', 'Avg Median', 'Avg Own', 'Avg Dupes', 'Avg Finish %', 'Avg Lineup Edge'])
            
            with combos_col:
                st.subheader("Player Combinations")
                
                # Add controls for combo analysis
                with st.form("combo_analysis_form"):
                    combo_size_col, columns_excluded_col, combo_analyze_col = st.columns(3)
                    with combo_size_col:
                        combo_size = st.selectbox("Combo Size", [2, 3], key='combo_size')
                    with columns_excluded_col:
                        try:
                            excluded_cols_extended = st.multiselect("Exclude Columns?", st.session_state['display_frame'].drop(columns=excluded_cols).columns, key='excluded_cols_extended')
                        except:
                            excluded_cols_extended = st.multiselect("Exclude Columns?", st.session_state['display_frame'].columns, key='excluded_cols_extended')
                    with combo_analyze_col:
                        submitted = st.form_submit_button("Analyze Combos")
                        if submitted:
                            st.session_state['combo_analysis'] = analyze_player_combos(
                                st.session_state['display_frame'], excluded_cols + excluded_cols_extended, combo_size
                            )
                
                # Display results
                if 'combo_analysis' in st.session_state:
                    st.dataframe(
                        st.session_state['combo_analysis'].style
                        .background_gradient(axis=0)
                        .background_gradient(cmap='RdYlGn')
                        .background_gradient(cmap='RdYlGn_r', subset=['Avg Finish %', 'Avg Own', 'Avg Dupes'])
                        .format({
                            'Avg Median': '{:.2f}',
                            'Avg Own': '{:.2f}',
                            'Avg Dupes': '{:.2f}',
                            'Avg Finish %': '{:.2%}',
                            'Avg Lineup Edge': '{:.2%}',
                            'Exposure': '{:.2%}',
                            'Avg Diversity': '{:.2%}'
                        }),
                        height=400,
                        use_container_width=True
                    )
                else:
                    st.info("Click 'Analyze Combos' to see the most common player combinations.")