File size: 121,217 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
// SPDX-License-Identifier: LGPL-2.1-or-later

/**************************************************************************
 *   Copyright (c) 2018 Kresimir Tusek <kresimir.tusek@gmail.com>          *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "Adaptive.hpp"
#include <iostream>
#include <cmath>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <numbers>
#include <optional>

namespace ClipperLib
{
void TranslatePath(const Path& input, Path& output, IntPoint delta);
}

namespace AdaptivePath
{
using namespace ClipperLib;
using namespace std;
#define SAME_POINT_TOL_SQRD_SCALED 4.0
#define UNUSED(expr) (void)(expr)

//*****************************************
// Utils - inline
//*****************************************

inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)
{
    double Dx = double(pt1.X - pt2.X);
    double dy = double(pt1.Y - pt2.Y);
    return (Dx * Dx + dy * dy);
}

inline bool SetSegmentLength(const IntPoint& pt1, IntPoint& pt2, double new_length)
{
    double Dx = double(pt2.X - pt1.X);
    double dy = double(pt2.Y - pt1.Y);
    double l = sqrt(Dx * Dx + dy * dy);
    if (l > 0.0) {
        pt2.X = long(pt1.X + new_length * Dx / l);
        pt2.Y = long(pt1.Y + new_length * dy / l);
        return true;
    }
    return false;
}

inline bool HasAnyPath(const Paths& paths)
{
    for (Paths::size_type i = 0; i < paths.size(); i++) {
        if (!paths[i].empty()) {
            return true;
        }
    }
    return false;
}

inline double averageDV(const vector<double>& vec)
{
    double s = 0;
    std::size_t size = vec.size();
    if (size == 0) {
        return 0;
    }
    for (std::size_t i = 0; i < size; i++) {
        s += vec[i];
    }
    return s / double(size);
}

inline DoublePoint rotate(const DoublePoint& in, double rad)
{
    double c = cos(rad);
    double s = sin(rad);
    return DoublePoint(c * in.X - s * in.Y, s * in.X + c * in.Y);
}

// calculates path length for open path
inline double PathLength(const Path& path)
{
    double len = 0;
    if (path.size() < 2) {
        return len;
    }
    for (size_t i = 1; i < path.size(); i++) {
        len += sqrt(DistanceSqrd(path[i - 1], path[i]));
    }
    return len;
}

inline double PointSideOfLine(const IntPoint& p1, const IntPoint& p2, const IntPoint& pt)
{
    return double((pt.X - p1.X) * (p2.Y - p1.Y) - (pt.Y - p2.Y) * (p2.X - p1.X));
}

inline double Angle3Points(const DoublePoint& p1, const DoublePoint& p2, const DoublePoint& p3)
{
    double t1 = atan2(p2.Y - p1.Y, p2.X - p1.X);
    double t2 = atan2(p3.Y - p2.Y, p3.X - p2.X);
    double a = fabs(t2 - t1);
    return min(a, 2 * std::numbers::pi - a);
}

inline DoublePoint DirectionV(const IntPoint& pt1, const IntPoint& pt2)
{
    double DX = double(pt2.X - pt1.X);
    double DY = double(pt2.Y - pt1.Y);
    double l = sqrt(DX * DX + DY * DY);
    if (l < NTOL) {
        return DoublePoint(0, 0);
    }
    return DoublePoint(DX / l, DY / l);
}

inline void NormalizeV(DoublePoint& pt)
{
    double len = sqrt(pt.X * pt.X + pt.Y * pt.Y);
    if (len > NTOL) {
        pt.X /= len;
        pt.Y /= len;
    }
}

inline DoublePoint GetPathDirectionV(const Path& pth, size_t pointIndex)
{
    if (pth.size() < 2) {
        return DoublePoint(0, 0);
    }
    const IntPoint& p1 = pth.at(pointIndex > 0 ? pointIndex - 1 : pth.size() - 1);
    const IntPoint& p2 = pth.at(pointIndex);
    return DirectionV(p1, p2);
}

// Returns true if points 'a' and 'b' are coincident or nearly so.
bool isClose(const IntPoint& a, const IntPoint& b)
{
    return abs(a.X - b.X) <= 1 && abs(a.Y - b.Y) <= 1;
}

// Remove coincident and almost-coincident points from Paths.
void filterCloseValues(Paths& ppg)
{
    for (auto& pth : ppg) {
        while (true) {
            auto i = std::adjacent_find(pth.begin(), pth.end(), isClose);
            if (i == pth.end()) {
                break;
            }
            pth.erase(i);
        }
        // adjacent_find doesn't compare first with last element, so
        // do that manually.
        while (pth.size() > 1 && isClose(pth.front(), pth.back())) {
            pth.pop_back();
        }
    }
}

//*****************************************
// Utils
//*****************************************

class BoundBox
{
public:
    BoundBox()
    {
        minX = 0;
        maxX = 0;
        minY = 0;
        maxY = 0;
    }

    // generic: first point
    BoundBox(const IntPoint& p1)
    {
        minX = p1.X;
        maxX = p1.X;
        minY = p1.Y;
        maxY = p1.Y;
    }

    void SetFirstPoint(const IntPoint& p1)
    {
        minX = p1.X;
        maxX = p1.X;
        minY = p1.Y;
        maxY = p1.Y;
    }

    // generic: subsequent points
    void AddPoint(const IntPoint& pt)
    {
        minX = min(pt.X, minX);
        maxX = max(pt.X, maxX);
        minY = min(pt.Y, minY);
        maxY = max(pt.Y, maxY);
    }

    // line segment: two points
    BoundBox(const IntPoint& p1, const IntPoint& p2)
    {
        if (p1.X < p2.X) {
            minX = p1.X;
            maxX = p2.X;
        }
        else {
            minX = p2.X;
            maxX = p1.X;
        }
        if (p1.Y < p2.Y) {
            minY = p1.Y;
            maxY = p2.Y;
        }
        else {
            minY = p2.Y;
            maxY = p1.Y;
        }
    }

    // for circle: center and radius
    BoundBox(const IntPoint& center, long radius)
    {
        minX = center.X - radius;
        maxX = center.X + radius;
        minY = center.Y - radius;
        maxY = center.Y + radius;
    }

    // bounds check - intersection
    inline bool CollidesWith(const BoundBox& bb2)
    {
        return minX <= bb2.maxX && maxX >= bb2.minX && minY <= bb2.maxY && maxY >= bb2.minY;
    }

    // bounds check -  contains
    inline bool Contains(const BoundBox& bb2)
    {
        return minX <= bb2.minX && maxX >= bb2.maxX && minY <= bb2.minY && maxY >= bb2.maxY;
    }

    ClipperLib::cInt minX;
    ClipperLib::cInt maxX;
    ClipperLib::cInt minY;
    ClipperLib::cInt maxY;
};

std::ostream& operator<<(std::ostream& s, const BoundBox& p)
{
    s << "(" << p.minX << "," << p.minY << ") - (" << p.maxX << "," << p.maxY << ")";
    return s;
}

int getPathNestingLevel(const Path& path, const Paths& paths)
{
    int nesting = 0;
    for (const auto& other : paths) {
        if (!path.empty() && PointInPolygon(path.front(), other) != 0) {
            nesting++;
        }
    }
    return nesting;
}

void appendDirectChildPaths(Paths& outPaths, const Path& path, const Paths& paths)
{
    int nesting = getPathNestingLevel(path, paths);
    for (const auto& other : paths) {
        if (!path.empty() && !other.empty() && PointInPolygon(other.front(), path) != 0) {
            if (getPathNestingLevel(other, paths) == nesting + 1) {
                outPaths.push_back(other);
            }
        }
    }
}

void AverageDirection(const vector<DoublePoint>& unityVectors, DoublePoint& output)
{
    std::size_t size = unityVectors.size();
    output.X = 0;
    output.Y = 0;
    // sum vectors
    for (std::size_t i = 0; i < size; i++) {
        DoublePoint v = unityVectors[i];
        output.X += v.X;
        output.Y += v.Y;
    }
    // normalize
    double magnitude = sqrt(output.X * output.X + output.Y * output.Y);
    output.X /= magnitude;
    output.Y /= magnitude;
}

double DistancePointToLineSegSquared(
    const IntPoint& p1,
    const IntPoint& p2,
    const IntPoint& pt,
    IntPoint& closestPoint,
    double& ptParameter,
    bool clamp = true
)
{
    double D21X = double(p2.X - p1.X);
    double D21Y = double(p2.Y - p1.Y);
    double DP1X = double(pt.X - p1.X);
    double DP1Y = double(pt.Y - p1.Y);
    double lsegLenSqr = D21X * D21X + D21Y * D21Y;
    if (lsegLenSqr == 0) {  // segment is zero length, return point to point distance
        closestPoint = p1;
        ptParameter = 0;
        return DP1X * DP1X + DP1Y * DP1Y;
    }
    double parameter = DP1X * D21X + DP1Y * D21Y;
    if (clamp) {
        // clamp the parameter
        if (parameter < 0) {
            parameter = 0;
        }
        else if (parameter > lsegLenSqr) {
            parameter = lsegLenSqr;
        }
    }
    // point on line at parameter
    ptParameter = parameter / lsegLenSqr;
    closestPoint.X = long(p1.X + ptParameter * D21X);
    closestPoint.Y = long(p1.Y + ptParameter * D21Y);
    // calculate distance from point on line to pt
    double DX = double(pt.X - closestPoint.X);
    double DY = double(pt.Y - closestPoint.Y);
    return DX * DX + DY * DY;  // return distance squared
}

void ScaleUpPaths(Paths& paths, long scaleFactor)
{
    for (auto& pth : paths) {
        for (auto& pt : pth) {
            pt.X *= scaleFactor;
            pt.Y *= scaleFactor;
        }
    }
}

void ScaleDownPaths(Paths& paths, long scaleFactor)
{
    for (auto& pth : paths) {
        for (auto& pt : pth) {
            pt.X /= scaleFactor;
            pt.Y /= scaleFactor;
        }
    }
}


double DistancePointToPathsSqrd(
    const Paths& paths,
    const IntPoint& pt,
    IntPoint& closestPointOnPath,
    size_t& clpPathIndex,
    size_t& clpSegmentIndex,
    double& clpParameter
)
{
    double minDistSq = __DBL_MAX__;
    IntPoint clp;
    // iterate though paths
    for (Path::size_type i = 0; i < paths.size(); i++) {
        const Path* path = &paths[i];
        Path::size_type size = path->size();
        // iterate through segments
        for (Path::size_type j = 0; j < size; j++) {
            double ptPar;
            double distSq = DistancePointToLineSegSquared(
                path->at(j > 0 ? j - 1 : size - 1),
                path->at(j),
                pt,
                clp,
                ptPar
            );
            if (distSq < minDistSq) {
                clpPathIndex = i;
                clpSegmentIndex = j;
                clpParameter = ptPar;
                closestPointOnPath = clp;
                minDistSq = distSq;
            }
        }
    }
    return minDistSq;
}

// joins collinear segments (within the tolerance)
void CleanPath(const Path& inp, Path& outpt, double tolerance)
{
    if (inp.size() < 3) {
        outpt = inp;
        return;
    }
    outpt.clear();
    Path tmp;
    CleanPolygon(inp, tmp, tolerance);
    long size = long(tmp.size());

    // CleanPolygon will have empty result if all points are collinear,
    // 	need to add first and last point to the output
    if (size <= 2) {
        outpt.push_back(inp.front());
        outpt.push_back(inp.back());
        return;
    }

    // restore starting point
    double clpPar = 0;
    size_t clpSegmentIndex = 0;
    size_t clpPathIndex = 0;
    Paths tmpPaths;
    tmpPaths.push_back(tmp);
    IntPoint clp;
    // find point on cleaned poly that is closest to original starting point
    DistancePointToPathsSqrd(tmpPaths, inp.front(), clp, clpPathIndex, clpSegmentIndex, clpPar);


    // if closes point is not one of the polygon points, add it as separate first point
    if (DistanceSqrd(clp, tmp.at(clpSegmentIndex)) > 0
        && DistanceSqrd(clp, tmp.at(clpSegmentIndex > 0 ? clpSegmentIndex - 1 : size - 1)) > 0) {
        outpt.push_back(clp);
    }

    // add remaining points starting from closest
    long index;
    for (long i = 0; i < size; i++) {
        index = static_cast<long>(clpSegmentIndex + i);
        if (index >= size) {
            index -= size;
        }
        outpt.push_back(tmp.at(index));
    }


    if (DistanceSqrd(outpt.front(), inp.front()) > SAME_POINT_TOL_SQRD_SCALED) {
        outpt.insert(outpt.begin(), inp.front());
    }

    if (DistanceSqrd(outpt.back(), inp.back()) > SAME_POINT_TOL_SQRD_SCALED) {
        outpt.push_back(inp.back());
    }
}

bool Circle2CircleIntersect(
    const IntPoint& c1,
    const IntPoint& c2,
    double radius,
    pair<DoublePoint, DoublePoint>& intersections
)
{
    double DX = double(c2.X - c1.X);
    double DY = double(c2.Y - c1.Y);
    double d = sqrt(DX * DX + DY * DY);
    if (d < NTOL) {
        return false;  // same center
    }
    if (d >= radius) {
        return false;  // do not intersect, or intersect in one point (this case not relevant here)
    }
    double a_2 = sqrt(4 * radius * radius - d * d) / 2.0;
    intersections.first
        = DoublePoint(0.5 * (c1.X + c2.X) - DY * a_2 / d, 0.5 * (c1.Y + c2.Y) + DX * a_2 / d);
    intersections.second
        = DoublePoint(0.5 * (c1.X + c2.X) + DY * a_2 / d, 0.5 * (c1.Y + c2.Y) - DX * a_2 / d);
    return true;
}

bool Line2CircleIntersect(
    const IntPoint& c,
    double radius,
    const IntPoint& p1,
    const IntPoint& p2,
    vector<DoublePoint>& result,
    bool clamp = true
)
{
    // if more intersections returned, first is closer to p1

    // box  check for performance
    if (clamp) {
        BoundBox cBB(c, (ClipperLib::cInt)radius + 1);  // circle bound box
        BoundBox sBB(p1, p2);
        if (!sBB.CollidesWith(cBB)) {
            return false;
        }
    }

    double dx = double(p2.X - p1.X);
    double dy = double(p2.Y - p1.Y);
    double lcx = double(p1.X - c.X);
    double lcy = double(p1.Y - c.Y);
    double a = dx * dx + dy * dy;
    double b = 2 * dx * lcx + 2 * dy * lcy;
    double C = lcx * lcx + lcy * lcy - radius * radius;
    double sq = b * b - 4 * a * C;
    if (sq < 0) {
        return false;  // no solution
    }
    sq = sqrt(sq);
    double t1 = (-b - sq) / (2 * a);
    double t2 = (-b + sq) / (2 * a);
    result.clear();
    if (clamp) {
        if (t1 >= 0.0 && t1 <= 1.0) {
            result.emplace_back(p1.X + t1 * dx, p1.Y + t1 * dy);
        }
        if (t2 >= 0.0 && t2 <= 1.0) {
            result.emplace_back(p1.X + t2 * dx, p1.Y + t2 * dy);
        }
    }
    else {
        result.emplace_back(p1.X + t2 * dx, p1.Y + t2 * dy);
        result.emplace_back(p1.X + t2 * dx, p1.Y + t2 * dy);
    }
    return !result.empty();
}

// calculate center point of polygon
IntPoint Compute2DPolygonCentroid(const Path& vertices)
{
    DoublePoint centroid(0, 0);
    double signedArea = 0.0;
    double x0 = 0.0;  // Current vertex X
    double y0 = 0.0;  // Current vertex Y
    double x1 = 0.0;  // Next vertex X
    double y1 = 0.0;  // Next vertex Y
    double a = 0.0;   // Partial signed area

    // For all vertices
    size_t i = 0;
    Path::size_type size = vertices.size();
    for (i = 0; i < size; ++i) {
        x0 = double(vertices[i].X);
        y0 = double(vertices[i].Y);
        x1 = double(vertices[(i + 1) % size].X);
        y1 = double(vertices[(i + 1) % size].Y);
        a = x0 * y1 - x1 * y0;
        signedArea += a;
        centroid.X += (x0 + x1) * a;
        centroid.Y += (y0 + y1) * a;
    }

    signedArea *= 0.5;
    centroid.X /= (6.0 * signedArea);
    centroid.Y /= (6.0 * signedArea);
    return IntPoint(long(centroid.X), long(centroid.Y));
}

// point must be within first path (boundary) and must not be within all other paths (holes)
bool IsPointWithinCutRegion(const Paths& toolBoundPaths, const IntPoint& point)
{
    for (size_t i = 0; i < toolBoundPaths.size(); i++) {
        int pip = PointInPolygon(point, toolBoundPaths[i]);
        if (i == 0 && pip == 0) {
            return false;  // is outside or on boundary
        }
        if (i > 0 && pip != 0) {
            return false;  // is inside hole
        }
    }
    return true;
}

/* finds intersection of line segment with line segment */
bool IntersectionPoint(
    const IntPoint& s1p1,
    const IntPoint& s1p2,
    const IntPoint& s2p1,
    const IntPoint& s2p2,
    IntPoint& intersection
)
{
    double S1DX = double(s1p2.X - s1p1.X);
    double S1DY = double(s1p2.Y - s1p1.Y);
    double S2DX = double(s2p2.X - s2p1.X);
    double S2DY = double(s2p2.Y - s2p1.Y);
    double d = S1DY * S2DX - S2DY * S1DX;
    if (fabs(d) < NTOL) {
        return false;  // lines are parallel
    }

    double LPDX = double(s1p1.X - s2p1.X);
    double LPDY = double(s1p1.Y - s2p1.Y);
    double p1d = S2DY * LPDX - S2DX * LPDY;
    double p2d = S1DY * LPDX - S1DX * LPDY;
    if ((d < 0) && (p1d < d || p1d > 0 || p2d < d || p2d > 0)) {
        return false;  // intersection not within segment1
    }
    if ((d > 0) && (p1d < 0 || p1d > d || p2d < 0 || p2d > d)) {
        return false;  // intersection not within segment2
    }
    double t = p1d / d;
    intersection = IntPoint(long(s1p1.X + S1DX * t), long(s1p1.Y + S1DY * t));
    return true;
}

/* finds one/first intersection of line segment with paths */
bool IntersectionPoint(const Paths& paths, const IntPoint& p1, const IntPoint& p2, IntPoint& intersection)
{
    BoundBox segBB(p1, p2);
    for (size_t i = 0; i < paths.size(); i++) {
        const Path* path = &paths[i];
        size_t size = path->size();
        if (size < 2) {
            continue;
        }
        BoundBox pathBB(path->front());
        for (size_t j = 0; j < size; j++) {

            const IntPoint* pp2 = &path->at(j);

            // box check for performance
            pathBB.AddPoint(*pp2);
            if (!pathBB.CollidesWith(segBB)) {
                continue;
            }

            const IntPoint* pp1 = &path->at(j > 0 ? j - 1 : size - 1);
            double LDY = double(p2.Y - p1.Y);
            double LDX = double(p2.X - p1.X);
            double PDX = double(pp2->X - pp1->X);
            double PDY = double(pp2->Y - pp1->Y);
            double d = LDY * PDX - PDY * LDX;
            if (fabs(d) < NTOL) {
                continue;  // lines are parallel
            }

            double LPDX = double(p1.X - pp1->X);
            double LPDY = double(p1.Y - pp1->Y);
            double p1d = PDY * LPDX - PDX * LPDY;
            double p2d = LDY * LPDX - LDX * LPDY;
            if ((d < 0) && (p1d < d || p1d > 0 || p2d < d || p2d > 0)) {
                continue;  // intersection not within segment
            }
            if ((d > 0) && (p1d < 0 || p1d > d || p2d < 0 || p2d > d)) {
                continue;  // intersection not within segment
            }
            double t = p1d / d;
            intersection = IntPoint(long(p1.X + LDX * t), long(p1.Y + LDY * t));
            return true;
        }
    }
    return false;
}

void SmoothPaths(Paths& paths, double stepSize, long pointCount, long iterations)
{
    Paths output;
    output.resize(paths.size());
    const long scale = 1000;
    const double stepScaled = stepSize * scale;

    ScaleUpPaths(paths, scale);
    vector<pair<size_t /*path index*/, IntPoint>> points;
    for (size_t i = 0; i < paths.size(); i++) {
        for (const auto& pt : paths[i]) {
            if (points.empty()) {
                points.emplace_back(i, pt);
                continue;
            }
            const auto back = points.back();
            const IntPoint& lastPt = back.second;


            const double l = sqrt(DistanceSqrd(lastPt, pt));

            if (l < 0.5 * stepScaled) {
                if (points.size() > 1) {
                    points.pop_back();
                }
                points.emplace_back(i, pt);
                continue;
            }
            size_t lastPathIndex = back.first;
            const long steps = max(long(l / stepScaled), 1L);
            const long left = pointCount * iterations * 2;
            const long right = steps - pointCount * iterations * 2;
            for (long idx = 0; idx <= steps; idx++) {
                if (idx > left && idx < right) {
                    idx = right;
                    continue;
                }
                const double p = double(idx) / steps;
                const IntPoint ptx(
                    long(lastPt.X + double(pt.X - lastPt.X) * p),
                    long(lastPt.Y + double(pt.Y - lastPt.Y) * p)
                );

                if (idx == 0 && DistanceSqrd(back.second, ptx) < scale && points.size() > 1) {
                    points.pop_back();
                }

                if (p < 0.5) {
                    points.emplace_back(lastPathIndex, ptx);
                }
                else {
                    points.emplace_back(i, ptx);
                }
            }
        }
    }
    if (points.empty()) {
        return;
    }
    const long size = long(points.size());
    for (long iter = 0; iter < iterations; iter++) {
        for (long i = 1; i < size - 1; i++) {
            IntPoint& cp = points[i].second;
            IntPoint avgPoint(cp);
            long cnt = 1;

            long ptsToAverage = pointCount;
            if (i <= ptsToAverage) {
                ptsToAverage = max(i - 1, 0L);
            }
            else if (i + ptsToAverage >= size - 1) {
                ptsToAverage = size - 1 - i;
            }
            for (long j = i - ptsToAverage; j <= i + ptsToAverage; j++) {
                if (j == i) {
                    continue;
                }
                long index = j;
                if (index < 0) {
                    index = 0;
                }
                if (index >= size) {
                    index = size - 1;
                }
                IntPoint& p = points[index].second;
                avgPoint.X += p.X;
                avgPoint.Y += p.Y;
                cnt++;
            }
            cp.X = avgPoint.X / cnt;
            cp.Y = avgPoint.Y / cnt;
        }
    }

    for (const auto& pr : points) {
        output[pr.first].push_back(pr.second);
    }
    for (size_t i = 0; i < paths.size(); i++) {
        CleanPath(output[i], paths[i], 1.4 * scale);
    }
    ScaleDownPaths(paths, scale);
}

bool PopPathWithClosestPoint(
    Paths& paths /*closest path is removed from collection and shifted to
                    start with closest point */
    ,
    IntPoint p1,
    Path& result
)
{

    if (paths.empty()) {
        return false;
    }

    double minDistSqrd = __DBL_MAX__;
    size_t closestPathIndex = 0;
    long closestPointIndex = 0;
    for (size_t pathIndex = 0; pathIndex < paths.size(); pathIndex++) {
        Path& path = paths.at(pathIndex);
        for (size_t i = 0; i < path.size(); i++) {
            double dist = DistanceSqrd(p1, path.at(i));
            if (dist < minDistSqrd) {
                minDistSqrd = dist;
                closestPathIndex = pathIndex;
                closestPointIndex = long(i);
            }
        }
    }

    result.clear();
    // make new path starting with that point
    Path& closestPath = paths.at(closestPathIndex);
    for (size_t i = 0; i < closestPath.size(); i++) {
        long index = closestPointIndex + long(i);
        if (index >= long(closestPath.size())) {
            index -= long(closestPath.size());
        }
        result.push_back(closestPath.at(index));
    }
    // remove the closest path
    paths.erase(paths.begin() + closestPathIndex);
    return true;
}

void DeduplicatePaths(const Paths& inputs, Paths& outputs)
{
    outputs.clear();
    for (const auto& new_pth : inputs) {
        bool duplicate = false;
        // if all points of new path exist on some of the old paths, path is considered duplicate
        for (const auto& old_pth : outputs) {
            bool all_points_exists = true;
            for (const auto pt1 : new_pth) {
                bool pointExists = false;
                for (const auto pt2 : old_pth) {
                    if (DistanceSqrd(pt1, pt2) < SAME_POINT_TOL_SQRD_SCALED) {
                        pointExists = true;
                        break;
                    }
                }
                if (!pointExists) {
                    all_points_exists = false;
                    break;
                }
            }
            if (all_points_exists) {
                duplicate = true;
                break;
            }
        }

        if (!duplicate && !new_pth.empty()) {
            outputs.push_back(new_pth);
        }
    }
}

void ConnectPaths(Paths input, Paths& output)
{
    output.clear();
    bool newPath = true;
    Path joined;
    while (!input.empty()) {
        if (newPath) {
            if (!joined.empty()) {
                output.push_back(joined);
            }
            joined.clear();
            for (auto pt : input.front()) {
                joined.push_back(pt);
            }
            input.erase(input.begin());
            newPath = false;
        }
        bool anyMatch = false;
        for (size_t i = 0; i < input.size(); i++) {
            Path& n = input.at(i);
            if (DistanceSqrd(n.front(), joined.back()) < SAME_POINT_TOL_SQRD_SCALED) {
                for (auto pt : n) {
                    joined.push_back(pt);
                }
                input.erase(input.begin() + i);
                anyMatch = true;
                break;
            }
            else if (DistanceSqrd(n.back(), joined.back()) < SAME_POINT_TOL_SQRD_SCALED) {
                ReversePath(n);
                for (auto pt : n) {
                    joined.push_back(pt);
                }
                input.erase(input.begin() + i);
                anyMatch = true;
                break;
            }
            else if (DistanceSqrd(n.front(), joined.front()) < SAME_POINT_TOL_SQRD_SCALED) {
                for (auto pt : n) {
                    joined.insert(joined.begin(), pt);
                }
                input.erase(input.begin() + i);
                anyMatch = true;
                break;
            }
            else if (DistanceSqrd(n.back(), joined.front()) < SAME_POINT_TOL_SQRD_SCALED) {
                ReversePath(n);
                for (auto pt : n) {
                    joined.insert(joined.begin(), pt);
                }
                input.erase(input.begin() + i);
                anyMatch = true;
                break;
            }
        }
        if (!anyMatch) {
            newPath = true;
        }
    }
    if (!joined.empty()) {
        output.push_back(joined);
    }
}

// helper class for measuring performance
class PerfCounter
{
public:
    PerfCounter(string p_name)
    {
        name = p_name;
        count = 0;
        running = false;
        start_ticks = 0;
        total_ticks = 0;
    }
    inline void Start()
    {
#ifdef DEV_MODE
        start_ticks = clock();
        if (running) {
            cerr << "PerfCounter already running:" << name << endl;
        }
        running = true;
#endif
    }
    inline void Stop()
    {
#ifdef DEV_MODE
        if (!running) {
            cerr << "PerfCounter not running:" << name << endl;
        }
        total_ticks += clock() - start_ticks;
        start_ticks = clock();
        count++;
        running = false;
#endif
    }
    void DumpResults()
    {
        double total_time = double(total_ticks) / CLOCKS_PER_SEC;
        cout << "Perf: " << name.c_str() << " total_time: " << total_time
             << " sec, call_count:" << count << " per_call:" << double(total_time / count) << endl;
        start_ticks = clock();
        total_ticks = 0;
        count = 0;
    }

private:
    string name;
    clock_t start_ticks;
    clock_t total_ticks;
    size_t count;
    bool running = false;
};

PerfCounter Perf_ProcessPolyNode("ProcessPolyNode");
PerfCounter Perf_CalcCutAreaCirc("CalcCutArea");
PerfCounter Perf_CalcCutAreaClip("CalcCutAreaClip");
PerfCounter Perf_NextEngagePoint("NextEngagePoint");
PerfCounter Perf_PointIterations("PointIterations");
PerfCounter Perf_ExpandCleared("ExpandCleared");
PerfCounter Perf_DistanceToBoundary("DistanceToBoundary");
PerfCounter Perf_AppendToolPath("AppendToolPath");
PerfCounter Perf_IsAllowedToCutTrough("IsAllowedToCutTrough");
PerfCounter Perf_IsClearPath("IsClearPath");

//***********************************
// Cleared area bounding support
//***********************************
class ClearedArea
{
public:
    ClearedArea(ClipperLib::cInt p_toolRadiusScaled)
    {
        toolRadiusScaled = p_toolRadiusScaled;
    };

    void SetClearedPaths(const Paths& paths)
    {
        clearedPaths = paths;
        bboxPathsInvalid = true;
        bboxClippedInvalid = true;
    }
    void ExpandCleared(const Path toClearToolPath)
    {
        if (toClearToolPath.empty()) {
            return;
        }
        Perf_ExpandCleared.Start();
        clipof.Clear();
        clipof.AddPath(toClearToolPath, JoinType::jtRound, EndType::etOpenRound);
        Paths toolCoverPoly;
        clipof.Execute(toolCoverPoly, toolRadiusScaled + 1);
        clip.Clear();
        clip.AddPaths(clearedPaths, PolyType::ptSubject, true);
        clip.AddPaths(toolCoverPoly, PolyType::ptClip, true);
        clip.Execute(ClipType::ctUnion, clearedPaths);
        CleanPolygons(clearedPaths);
        bboxPathsInvalid = true;
        bboxClippedInvalid = true;
        Perf_ExpandCleared.Stop();
    }

    // gets the path sections inside the ext. tool bounding box
    Paths& GetBoundedClearedPaths(const IntPoint& toolPos)
    {
        BoundBox toolBB(toolPos, toolRadiusScaled);
        if (!bboxPathsInvalid && clearedBBPathsInFocus.Contains(toolBB)) {
            return clearedBoundedPaths;
        }
        ClipperLib::cInt delta = focusBBFactor1 * toolRadiusScaled;
        clearedBBPathsInFocus.SetFirstPoint(IntPoint(toolPos.X - delta, toolPos.Y - delta));
        clearedBBPathsInFocus.AddPoint(IntPoint(toolPos.X + delta, toolPos.Y + delta));

        BoundBox bb(toolPos, focusBBFactor2 * toolRadiusScaled);
        clearedBoundedPaths.clear();
        for (const auto& pth : clearedPaths) {
            if (pth.size() < 2) {
                continue;
            }
            Path bPath;
            size_t size = pth.size();
            for (size_t i = 0; i < size + 1; i++) {
                IntPoint last = (i > 0 ? pth[i - 1] : pth.back());
                IntPoint next = i < size ? pth[i] : pth.front();
                BoundBox ptbox(last, next);
                if (ptbox.CollidesWith(bb)) {
                    if (bPath.empty() || bPath.back() != last) {
                        bPath.push_back(last);
                    }
                    bPath.push_back(next);
                }
                else {
                    if (!bPath.empty()) {
                        clearedBoundedPaths.push_back(bPath);
                        bPath.clear();
                    }
                }
            }
            if (!bPath.empty()) {
                clearedBoundedPaths.push_back(bPath);
                bPath.clear();
            }
        }
        bboxPathsInvalid = false;
        return clearedBoundedPaths;
    }

    // get cleared area/poly bounded to toolbox
    Paths& GetBoundedClearedAreaClipped(const IntPoint& toolPos)
    {
        BoundBox toolBB(toolPos, toolRadiusScaled);
        if (!bboxClippedInvalid && clearedBBClippedInFocus.Contains(toolBB)) {
            return clearedBoundedClipped;
        }
        ClipperLib::cInt delta = focusBBFactor1 * toolRadiusScaled;
        clearedBBClippedInFocus.SetFirstPoint(IntPoint(toolPos.X - delta, toolPos.Y - delta));
        clearedBBClippedInFocus.AddPoint(IntPoint(toolPos.X + delta, toolPos.Y + delta));

        // a little larger area is bounded than checked
        ClipperLib::cInt delta2 = focusBBFactor2 * toolRadiusScaled;
        Path bbPath;
        bbPath.push_back(IntPoint(toolPos.X - delta2, toolPos.Y - delta2));
        bbPath.push_back(IntPoint(toolPos.X + delta2, toolPos.Y - delta2));
        bbPath.push_back(IntPoint(toolPos.X + delta2, toolPos.Y + delta2));
        bbPath.push_back(IntPoint(toolPos.X - delta2, toolPos.Y + delta2));
        clip.Clear();
        clip.AddPath(bbPath, PolyType::ptSubject, true);
        clip.AddPaths(clearedPaths, PolyType::ptClip, true);
        clip.Execute(ClipType::ctIntersection, clearedBoundedClipped);
        bboxClippedInvalid = false;
        return clearedBoundedClipped;
    }

    // get full cleared area
    Paths& GetCleared()
    {
        return clearedPaths;
    }

private:
    Clipper clip;
    ClipperOffset clipof;
    Paths clearedPaths;
    Paths clearedBoundedClipped;
    Paths clearedBoundedPaths;

    ClipperLib::cInt toolRadiusScaled;
    BoundBox clearedBBClippedInFocus;
    BoundBox clearedBBPathsInFocus;

    bool bboxClippedInvalid = false;
    bool bboxPathsInvalid = false;
    // size of the focus BB
    const ClipperLib::cInt focusBBFactor1 = 8;
    const ClipperLib::cInt focusBBFactor2 = 9;
};

//***************************************
// Linear Interpolation - area vs angle
//***************************************
class Interpolation
{
public:
    const double MIN_ANGLE = -std::numbers::pi / 4;
    const double MAX_ANGLE = std::numbers::pi / 4;

    void clear()
    {
        m_min.reset();
        m_max.reset();
    }
    bool bothSides()
    {
        return m_min && m_max && m_min->second < 0 && m_max->second >= 0;
    }
    // adds point keeping the incremental order of areas for interpolation to work correctly
    void addPoint(double error, std::pair<double, IntPoint> angle, bool allowSkip = false)
    {
        if (!m_min) {
            m_min = {angle, error};
        }
        else if (!m_max) {
            m_max = {angle, error};
            if (m_min->second > m_max->second) {
                auto tmp = m_min;
                m_min = m_max;
                m_max = tmp;
            }
        }
        else if (bothSides()) {
            if (error < 0) {
                m_min = {angle, error};
            }
            else {
                m_max = {angle, error};
            }
        }
        else {
            if (allowSkip && abs(error) > abs(m_min->second) && abs(error) > abs(m_max->second)) {
                return;
            }
            if (abs(m_min->second) > abs(m_max->second)) {
                m_min.reset();
            }
            else {
                m_max.reset();
            }
            addPoint(error, angle);
        }
    }

    double interpolateAngle()
    {
        if (!m_min) {
            return MIN_ANGLE;
        }

        if (!m_max) {
            return MAX_ANGLE;
        }
        double p = (0 - m_min->second) / (m_max->second - m_min->second);

        // Ensure search is sufficiently efficient -- this is a compromise
        // between binary search (p = 0.5, guaranteed search completion in log
        // time) and following linear interpolation completely (often faster
        // since area cut is locally linear in movement angle)
        const double minInterp = .2;
        p = max(min(p, 1 - minInterp), minInterp);

        return m_min->first.first * (1 - p) + m_max->first.first * p;
    }

    double clampAngle(double angle)
    {
        return max(min(angle, MAX_ANGLE), MIN_ANGLE);
    }

    size_t getPointCount()
    {
        return (m_min ? 1 : 0) + (m_max ? 1 : 0);
    }

public:
    // {{angle, clipper point}, error}
    std::optional<std::pair<std::pair<double, IntPoint>, double>> m_min;
    std::optional<std::pair<std::pair<double, IntPoint>, double>> m_max;
};

//***************************************
// Engage Point
//***************************************

class EngagePoint
{
public:
    struct EngageState
    {
        size_t currentPathIndex = 0;
        size_t currentSegmentIndex = 0;
        double segmentPos = 0;
        double totalDistance = 0;
        double currentPathLength = 0;
        int passes = 0;

        double metric = 0;  // engage point metric

        bool operator<(const EngageState& other) const
        {
            return (metric < other.metric);
        }
    };
    EngagePoint(const Paths& p_toolBoundPaths)
    {
        SetPaths(p_toolBoundPaths);

        state.currentPathIndex = 0;
        state.currentSegmentIndex = 0;
        state.segmentPos = 0;
        state.totalDistance = 0;
        calculateCurrentPathLength();
    }

    void SetPaths(const Paths& paths)
    {
        toolBoundPaths = paths;
        state.currentPathIndex = 0;
        state.currentSegmentIndex = 0;
        state.segmentPos = 0;
        state.totalDistance = 0;
        state.passes = 0;
        calculateCurrentPathLength();
    }

    EngageState GetState()
    {
        return state;
    }

    void SetState(const EngageState& new_state)
    {
        state = new_state;
    }

    void ResetPasses()
    {
        state.passes = 0;
    }
    void moveToClosestPoint(const IntPoint& pt, double step)
    {

        Path result;
        IntPoint current = pt;
        // chain paths according to distance in between
        Paths toChain = toolBoundPaths;
        toolBoundPaths.clear();
        // if(toChain.size()>0) {
        // 	toolBoundPaths.push_back(toChain.front());
        // 	toChain.erase(toChain.begin());
        // }
        while (PopPathWithClosestPoint(toChain, current, result)) {
            toolBoundPaths.push_back(result);
            if (!result.empty()) {
                current = result.back();
            }
        }

        double minDistSq = __DBL_MAX__;
        size_t minPathIndex = state.currentPathIndex;
        size_t minSegmentIndex = state.currentSegmentIndex;
        double minSegmentPos = state.segmentPos;
        state.totalDistance = 0;
        for (;;) {
            while (moveForward(step)) {
                double distSqrd = DistanceSqrd(pt, getCurrentPoint());
                if (distSqrd < minDistSq) {
                    minDistSq = distSqrd;
                    minPathIndex = state.currentPathIndex;
                    minSegmentIndex = state.currentSegmentIndex;
                    minSegmentPos = state.segmentPos;
                }
            }
            if (!nextPath()) {
                break;
            }
        }
        state.currentPathIndex = minPathIndex;
        state.currentSegmentIndex = minSegmentIndex;
        state.segmentPos = minSegmentPos;
        calculateCurrentPathLength();
        ResetPasses();
    }
    bool nextEngagePoint(
        Adaptive2d* parent,
        ClearedArea& clearedArea,
        double step,
        double minCutArea,
        double maxCutArea,
        int maxPases = 2
    )
    {
        Perf_NextEngagePoint.Start();
        double prevArea = 0;  // we want to make sure that we catch the point where the area is on
                              // raising slope
        IntPoint initialPoint(-1000000000, -1000000000);
        for (;;) {
            if (!moveForward(step)) {
                if (!nextPath()) {
                    state.passes++;
                    if (state.passes >= maxPases) {
                        Perf_NextEngagePoint.Stop();
                        return false;  // nothing more to cut
                    }
                    prevArea = 0;
                }
            }
            IntPoint cpt = getCurrentPoint();
            double area = parent->CalcCutArea(clip, initialPoint, cpt, clearedArea);
            if (area > minCutArea && area < maxCutArea && area > prevArea) {
                Perf_NextEngagePoint.Stop();
                return true;
            }
            prevArea = area;
        }
    }
    IntPoint getCurrentPoint()
    {
        const Path* pth = &toolBoundPaths.at(state.currentPathIndex);
        const IntPoint* p1 = &pth->at(
            state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 : pth->size() - 1
        );
        const IntPoint* p2 = &pth->at(state.currentSegmentIndex);
        double segLength = sqrt(DistanceSqrd(*p1, *p2));
        return IntPoint(
            long(p1->X + state.segmentPos * double(p2->X - p1->X) / segLength),
            long(p1->Y + state.segmentPos * double(p2->Y - p1->Y) / segLength)
        );
    }

    DoublePoint getCurrentDir()
    {
        const Path* pth = &toolBoundPaths.at(state.currentPathIndex);
        const IntPoint* p1 = &pth->at(
            state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 : pth->size() - 1
        );
        const IntPoint* p2 = &pth->at(state.currentSegmentIndex);
        double segLength = sqrt(DistanceSqrd(*p1, *p2));
        return DoublePoint(double(p2->X - p1->X) / segLength, double(p2->Y - p1->Y) / segLength);
    }

    bool moveForward(double distance)
    {
        const Path* pth = &toolBoundPaths.at(state.currentPathIndex);
        if (distance < NTOL) {
            throw std::invalid_argument("distance must be positive");
        }
        state.totalDistance += distance;
        double segmentLength = currentSegmentLength();
        while (state.segmentPos + distance > segmentLength) {
            state.currentSegmentIndex++;
            if (state.currentSegmentIndex >= pth->size()) {
                state.currentSegmentIndex = 0;
            }
            distance = distance - (segmentLength - state.segmentPos);
            state.segmentPos = 0;
            segmentLength = currentSegmentLength();
        }
        state.segmentPos += distance;
        return state.totalDistance <= 1.2 * state.currentPathLength;
    }

    bool nextPath()
    {
        state.currentPathIndex++;
        state.currentSegmentIndex = 0;
        state.segmentPos = 0;
        state.totalDistance = 0;
        if (state.currentPathIndex >= toolBoundPaths.size()) {
            state.currentPathIndex = 0;
            calculateCurrentPathLength();
            return false;
        }
        calculateCurrentPathLength();
        return true;
    }

private:
    Paths toolBoundPaths;
    EngageState state;
    Clipper clip;
    void calculateCurrentPathLength()
    {
        const Path* pth = &toolBoundPaths.at(state.currentPathIndex);
        size_t size = pth->size();
        state.currentPathLength = 0;
        for (size_t i = 0; i < size; i++) {
            const IntPoint* p1 = &pth->at(i > 0 ? i - 1 : size - 1);
            const IntPoint* p2 = &pth->at(i);
            state.currentPathLength += sqrt(DistanceSqrd(*p1, *p2));
        }
    }

    double currentSegmentLength()
    {
        const Path* pth = &toolBoundPaths.at(state.currentPathIndex);
        const IntPoint* p1 = &pth->at(
            state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 : pth->size() - 1
        );
        const IntPoint* p2 = &pth->at(state.currentSegmentIndex);
        return sqrt(DistanceSqrd(*p1, *p2));
    }
};

//***************************************
// Adaptive2d main class - implementation
//***************************************

Adaptive2d::Adaptive2d()
{}

double Adaptive2d::CalcCutArea(
    Clipper& clip,
    const IntPoint& c1,
    const IntPoint& c2,
    ClearedArea& clearedArea,
    bool preventConventional
)
{

    double dist = DistanceSqrd(c1, c2);
    if (dist < NTOL) {
        return 0;
    }

    Perf_CalcCutAreaCirc.Start();

    /// new alg
    double rsqrd = toolRadiusScaled * toolRadiusScaled;
    double area = 0;
    Paths interPaths;
    IntPoint clp;                // to hold closest point
    vector<DoublePoint> inters;  // to hold intersection results
    BoundBox c2BB(c2, toolRadiusScaled);
    BoundBox c1BB(c1, toolRadiusScaled);
    Paths& clearedBounded = clearedArea.GetBoundedClearedAreaClipped(c2);
    for (const Path& path : clearedBounded) {
        size_t size = path.size();
        if (size == 0) {
            continue;
        }

        //** bound box check
        // construct bound box for path
        BoundBox pathBB(path.front());
        for (const auto& pt : path) {
            pathBB.AddPoint(pt);
        }
        if (!c2BB.CollidesWith(c2)) {
            continue;  // this path cannot colide with tool
        }
        //** end of BB check

        size_t curPtIndex = 0;
        bool found = false;
        // step 1: we find the starting point on the cleared path that is outside new tool shape
        // (c2)
        for (size_t i = 0; i < size; i++) {
            if (DistanceSqrd(path[curPtIndex], c2) > rsqrd) {
                found = true;
                break;
            }
            curPtIndex++;
            if (curPtIndex >= size) {
                curPtIndex = 0;
            }
        }
        if (!found) {
            continue;  // try another path
        }

        // step 2: iterate through path from starting point and find the part of the path inside the
        // c2
        size_t prevPtIndex = curPtIndex;
        Path* interPath = NULL;
        bool prev_inside = false;
        const IntPoint* p1 = &path[prevPtIndex];
        double par;  // to hold parameter output
        for (size_t i = 0; i < size; i++) {
            curPtIndex++;
            if (curPtIndex >= size) {
                curPtIndex = 0;
            }
            const IntPoint* p2 = &path[curPtIndex];
            BoundBox segBB(*p1, *p2);
            if (!prev_inside) {  // prev state: outside, find first point inside C2
                if (segBB.CollidesWith(c2BB)
                    && DistancePointToLineSegSquared(*p1, *p2, c2, clp, par)
                        <= rsqrd) {  // current segment inside, start
                    prev_inside = true;
                    interPaths.push_back(Path());
                    if (interPaths.size() > 1) {
                        break;  // we will use poly clipping alg. if there are more intersecting
                                // paths
                    }
                    interPath = &interPaths.back();
                    // current segment inside c2, prev point outside, find intersection:
                    if (Line2CircleIntersect(c2, toolRadiusScaled, *p1, *p2, inters)) {
                        interPath->push_back(IntPoint(long(inters[0].X), long(inters[0].Y)));
                        if (inters.size() > 1) {
                            interPath->push_back(IntPoint(long(inters[1].X), long(inters[1].Y)));
                            prev_inside = false;
                        }
                        else {
                            interPath->push_back(IntPoint(*p2));
                        }
                    }
                    else {  // no intersection - must be edge case, add p2
                        interPath->push_back(IntPoint(*p2));
                    }
                }
            }
            else if (interPath != NULL) {                // state: inside
                if ((DistanceSqrd(c2, *p2) <= rsqrd)) {  // next point still inside, add it and
                                                         // continue, no state change
                    interPath->push_back(IntPoint(*p2));
                }
                else {  // prev point inside, current point outside, find intersection
                    if (Line2CircleIntersect(c2, toolRadiusScaled, *p1, *p2, inters)) {
                        if (inters.size() > 1) {
                            interPath->push_back(IntPoint(long(inters[1].X), long(inters[1].Y)));
                        }
                        else {
                            interPath->push_back(IntPoint(long(inters[0].X), long(inters[0].Y)));
                        }
                    }
                    prev_inside = false;
                }
            }
            prevPtIndex = curPtIndex;
            p1 = p2;
        }
        if (interPaths.size() > 1) {
            break;  // we will use poly clipping alg. if there are more intersecting paths with the
                    // tool (rare case)
        }
    }
    Perf_CalcCutAreaCirc.Stop();
    if (interPaths.size() == 1 && interPaths.front().size() > 1) {
        Perf_CalcCutAreaCirc.Start();
        Path* interPath = &interPaths.front();
        // interPath - now contains the part of cleared path inside the C2
        size_t ipc2_size = interPath->size();
        const IntPoint& fpc2 = interPath->front();  // first point
        const IntPoint& lpc2 = interPath->back();   // last point
        // path length
        double interPathLen = 0;
        for (size_t j = 1; j < ipc2_size; j++) {
            interPathLen += sqrt(DistanceSqrd(interPath->at(j - 1), interPath->at(j)));
        }

        Paths inPaths;
        inPaths.reserve(200);
        inPaths.push_back(*interPath);
        Path pthToSubtract;
        pthToSubtract.push_back(fpc2);

        double fi1 = atan2(fpc2.Y - c2.Y, fpc2.X - c2.X);
        double fi2 = atan2(lpc2.Y - c2.Y, lpc2.X - c2.X);
        double minFi = fi1;
        double maxFi = fi2;
        if (maxFi < minFi) {
            maxFi += 2 * std::numbers::pi;
        }

        if (preventConventional && interPathLen >= MIN_STEP_CLIPPER) {
            // detect conventional mode cut - we want only climb mode
            IntPoint midPoint(
                long(c2.X + toolRadiusScaled * cos(0.5 * (maxFi + minFi))),
                long(c2.Y + toolRadiusScaled * sin(0.5 * (maxFi + minFi)))
            );
            if (PointSideOfLine(c1, c2, midPoint) < 0) {
                area = __DBL_MAX__;
                Perf_CalcCutAreaCirc.Stop();
                // #ifdef DEV_MODE
                // 	cout << "Break: @(" << double(c2.X)/scaleFactor << "," <<
                // double(c2.Y)/scaleFactor  << ") conventional mode" << endl; #endif
                return area;
            }
        }

        double scanDistance = 2.5 * toolRadiusScaled;
        // stepping through path discretized to stepDistance
        double stepDistance = min(double(MIN_STEP_CLIPPER), interPathLen / 24) + 1;
        const IntPoint* prevPt = &interPath->front();
        double distance = 0;
        for (size_t j = 1; j < ipc2_size; j++) {
            const IntPoint* cpt = &interPath->at(j);
            double segLen = sqrt(DistanceSqrd(*cpt, *prevPt));
            if (segLen < NTOL) {
                continue;  // skip point - segment too short
            }
            for (double pos_unclamped = 0.0; pos_unclamped < segLen + stepDistance;
                 pos_unclamped += stepDistance) {
                double pos = pos_unclamped;
                if (pos > segLen) {
                    distance += stepDistance - (pos - segLen);
                    pos = segLen;  // make sure we get exact end point
                }
                else {
                    distance += stepDistance;
                }
                double dx = double(cpt->X - prevPt->X);
                double dy = double(cpt->Y - prevPt->Y);
                IntPoint segPoint(
                    long(prevPt->X + dx * pos / segLen),
                    long(prevPt->Y + dy * pos / segLen)
                );
                IntPoint scanPoint(
                    long(c2.X + scanDistance * cos(minFi + distance * (maxFi - minFi) / interPathLen)),
                    long(c2.Y + scanDistance * sin(minFi + distance * (maxFi - minFi) / interPathLen))
                );

                IntPoint intersC2(segPoint.X, segPoint.Y);
                IntPoint intersC1(segPoint.X, segPoint.Y);

                // there should be intersection with C2
                if (Line2CircleIntersect(c2, toolRadiusScaled, segPoint, scanPoint, inters)) {
                    if (inters.size() > 1) {
                        intersC2.X = long(inters[1].X);
                        intersC2.Y = long(inters[1].Y);
                    }
                    else {
                        intersC2.X = long(inters[0].X);
                        intersC2.Y = long(inters[0].Y);
                    }
                }
                else {
                    pthToSubtract.push_back(segPoint);
                }

                if (Line2CircleIntersect(c1, toolRadiusScaled, segPoint, scanPoint, inters)) {
                    if (inters.size() > 1) {
                        intersC1.X = long(inters[1].X);
                        intersC1.Y = long(inters[1].Y);
                    }
                    else {
                        intersC1.X = long(inters[0].X);
                        intersC1.Y = long(inters[0].Y);
                    }
                    if (DistanceSqrd(segPoint, intersC2) < DistanceSqrd(segPoint, intersC1)) {
                        pthToSubtract.push_back(intersC2);
                    }
                    else {
                        pthToSubtract.push_back(intersC1);
                    }
                }
                else {  // add the segpoint if no intersection with C1
                    pthToSubtract.push_back(segPoint);
                }
            }
            prevPt = cpt;
        }

        pthToSubtract.push_back(lpc2);  // add last point
        pthToSubtract.push_back(c2);

        double segArea = Area(pthToSubtract);
        double A = (maxFi - minFi) * rsqrd / 2;  // sector area
        area += A - fabs(segArea);
        Perf_CalcCutAreaCirc.Stop();
    }
    else if (interPaths.size() > 1) {
        Perf_CalcCutAreaClip.Start();
        // old way of calculating cut area based on polygon clipping
        // used in case when there are multiple intersections of tool with cleared poly (very rare
        // case, but important)
        // 1. find difference between old and new tool shape
        Path oldTool;
        Path newTool;
        TranslatePath(toolGeometry, oldTool, c1);
        TranslatePath(toolGeometry, newTool, c2);
        clip.Clear();
        clip.AddPath(newTool, PolyType::ptSubject, true);
        clip.AddPath(oldTool, PolyType::ptClip, true);
        Paths toolDiff;
        clip.Execute(ClipType::ctDifference, toolDiff);

        // 2. difference to cleared
        clip.Clear();
        clip.AddPaths(toolDiff, PolyType::ptSubject, true);
        clip.AddPaths(clearedBounded, PolyType::ptClip, true);
        Paths cutAreaPoly;
        clip.Execute(ClipType::ctDifference, cutAreaPoly);

        // calculate resulting area
        area = 0;
        for (Path& path : cutAreaPoly) {
            area += fabs(Area(path));
        }
        Perf_CalcCutAreaClip.Stop();
    }
    return area;
}

void Adaptive2d::ApplyStockToLeave(Paths& inputPaths)
{
    ClipperOffset clipof;
    if (stockToLeave > NTOL) {
        clipof.Clear();
        clipof.AddPaths(inputPaths, JoinType::jtRound, EndType::etClosedPolygon);
        if (opType == OperationType::otClearingOutside
            || opType == OperationType::otProfilingOutside) {
            clipof.Execute(inputPaths, stockToLeave * scaleFactor);
        }
        else {
            clipof.Execute(inputPaths, -stockToLeave * scaleFactor);
        }
    }
    else {
        // fix for clipper glitches
        clipof.Clear();
        clipof.AddPaths(inputPaths, JoinType::jtRound, EndType::etClosedPolygon);
        clipof.Execute(inputPaths, -1);
        filterCloseValues(inputPaths);
        clipof.Clear();
        clipof.AddPaths(inputPaths, JoinType::jtRound, EndType::etClosedPolygon);
        clipof.Execute(inputPaths, 1);
        filterCloseValues(inputPaths);
    }
}

//********************************************
// Adaptive2d - Execute
//********************************************

std::list<AdaptiveOutput> Adaptive2d::Execute(
    const DPaths& stockPaths,
    const DPaths& paths,
    std::function<bool(TPaths)> progressCallbackFn
)
{
    //**********************************
    // Initializations
    //**********************************

    // keep the tolerance in workable range
    tolerance = max(tolerance, 0.01);
    tolerance = min(tolerance, 1.0);

    // 1/"tolerance" = number of min-size adaptive steps per stepover
    scaleFactor = MIN_STEP_CLIPPER / tolerance / min(1.0, stepOverFactor * toolDiameter);

    current_region = 0;
    cout << "Tool Diameter: " << toolDiameter << endl;
    cout << "Min step size: " << round(MIN_STEP_CLIPPER / scaleFactor * 1000 * 10) / 10 << " um"
         << endl;
    cout << flush;

    toolRadiusScaled = long(toolDiameter * scaleFactor / 2);
    stepOverScaled = toolRadiusScaled * stepOverFactor;
    progressCallback = &progressCallbackFn;
    lastProgressTime = clock();
    stopProcessing = false;

    if (helixRampTargetDiameter < NTOL) {
        helixRampTargetDiameter = toolDiameter;
    }
    helixRampTargetDiameter = min(helixRampTargetDiameter, toolDiameter);
    helixRampMinDiameter = max(helixRampMinDiameter, toolDiameter / 8);
    helixRampTargetDiameter = max(helixRampTargetDiameter, helixRampMinDiameter);

    helixRampMaxRadiusScaled = long(helixRampTargetDiameter * scaleFactor / 2);
    helixRampMinRadiusScaled = long(helixRampMinDiameter * scaleFactor / 2);
    if (finishingProfile) {
        finishPassOffsetScaled = long(stepOverScaled / 10);
    }

    ClipperOffset clipof;
    Clipper clip;

    // generate tool shape
    clipof.Clear();
    Path p;
    p << IntPoint(0, 0);
    clipof.AddPath(p, JoinType::jtRound, EndType::etOpenRound);
    Paths toolGeometryPaths;
    clipof.Execute(toolGeometryPaths, toolRadiusScaled);
    toolGeometry = toolGeometryPaths[0];
    // calculate reference area
    Path slotCut;
    TranslatePath(toolGeometryPaths[0], slotCut, IntPoint(toolRadiusScaled / 2, 0));
    clip.Clear();
    clip.AddPath(toolGeometryPaths[0], PolyType::ptSubject, true);
    clip.AddPath(slotCut, PolyType::ptClip, true);
    Paths crossing;
    clip.Execute(ClipType::ctDifference, crossing);
    referenceCutArea = fabs(Area(crossing[0]));
    optimalCutAreaPD = 2 * stepOverFactor * referenceCutArea / toolRadiusScaled;
#ifdef DEV_MODE
    cout << "optimalCutAreaPD:" << optimalCutAreaPD << " scaleFactor:" << scaleFactor
         << " toolRadiusScaled:" << toolRadiusScaled
         << " helixRampMaxRadiusScaled:" << helixRampMaxRadiusScaled << endl;
#endif
    //******************************
    // Convert input paths to clipper
    //******************************
    Paths converted;
    for (size_t i = 0; i < paths.size(); i++) {
        Path cpth;
        for (size_t j = 0; j < paths[i].size(); j++) {
            std::pair<double, double> pt = paths[i][j];
            cpth.push_back(IntPoint(long(pt.first * scaleFactor), long(pt.second * scaleFactor)));
        }
        Path cpth2;
        CleanPath(cpth, cpth2, FINISHING_CLEAN_PATH_TOLERANCE);
        converted.push_back(cpth2);
    }

    DeduplicatePaths(converted, inputPaths);
    ConnectPaths(inputPaths, inputPaths);
    SimplifyPolygons(inputPaths);
    ApplyStockToLeave(inputPaths);

    //*************************
    // convert stock paths
    //*************************
    stockInputPaths.clear();
    for (size_t i = 0; i < stockPaths.size(); i++) {
        Path cpth;
        for (size_t j = 0; j < stockPaths[i].size(); j++) {
            std::pair<double, double> pt = stockPaths[i][j];
            cpth.push_back(IntPoint(long(pt.first * scaleFactor), long(pt.second * scaleFactor)));
        }

        stockInputPaths.push_back(cpth);
    }

    SimplifyPolygons(stockInputPaths);
    // CleanPolygons(stockInputPaths,0.707);

    //***************************************
    //	Resolve hierarchy and run processing
    //***************************************
    double cornerRoundingOffset = 0.15 * toolRadiusScaled / 2;
    if (opType == OperationType::otClearingInside || opType == OperationType::otClearingOutside) {

        // prepare stock boundary overshooted paths
        clipof.Clear();
        clipof.AddPaths(stockInputPaths, JoinType::jtSquare, EndType::etClosedPolygon);
        double overshootDistance = 4 * toolRadiusScaled + stockToLeave * scaleFactor;
        if (forceInsideOut) {
            overshootDistance = 0;
        }
        Paths stockOvershoot;
        clipof.Execute(stockOvershoot, overshootDistance);
        ReversePaths(stockOvershoot);

        if (opType == OperationType::otClearingOutside) {
            // add stock paths, with overshooting
            for (const auto& p : stockOvershoot) {
                inputPaths.push_back(p);
            }
        }
        else if (opType == OperationType::otClearingInside) {
            // potential TODO: check if there are open paths, and try to close it through
            // overshooted stock boundary
        }

        clipof.Clear();
        clipof.AddPaths(inputPaths, JoinType::jtRound, EndType::etClosedPolygon);
        Paths paths;
        clipof.Execute(paths, -toolRadiusScaled - finishPassOffsetScaled - cornerRoundingOffset);
        for (const auto& current : paths) {
            int nesting = getPathNestingLevel(current, paths);
            if (nesting % 2 != 0 && (polyTreeNestingLimit == 0 || nesting <= polyTreeNestingLimit)) {
                Paths toolBoundPaths;
                toolBoundPaths.push_back(current);
                if (polyTreeNestingLimit != nesting) {
                    appendDirectChildPaths(toolBoundPaths, current, paths);
                }

                // offset back outwards - corner rounding
                clipof.Clear();
                clipof.AddPaths(toolBoundPaths, JoinType::jtRound, EndType::etClosedPolygon);
                clipof.Execute(toolBoundPaths, cornerRoundingOffset);

                // restore original bound paths
                // bounding paths - i.e. area that must be cleared inside
                // it's not the same as input paths due to filtering (nesting logic) and corner
                // rounding
                Paths boundPaths;
                clipof.Clear();
                clipof.AddPaths(toolBoundPaths, JoinType::jtRound, EndType::etClosedPolygon);
                clipof.Execute(boundPaths, toolRadiusScaled + finishPassOffsetScaled);
                ProcessPolyNode(boundPaths, toolBoundPaths);
            }
        }
    }

    if (opType == OperationType::otProfilingInside || opType == OperationType::otProfilingOutside) {
        double offset = opType == OperationType::otProfilingInside
            ? -2 * (helixRampMaxRadiusScaled + toolRadiusScaled) - MIN_STEP_CLIPPER
            : 2 * (helixRampMaxRadiusScaled + toolRadiusScaled) + MIN_STEP_CLIPPER;
        for (const auto& current : inputPaths) {
            int nesting = getPathNestingLevel(current, inputPaths);
            if (nesting % 2 != 0 && (polyTreeNestingLimit == 0 || nesting <= polyTreeNestingLimit)) {
                Paths profilePaths;
                profilePaths.push_back(current);
                if (polyTreeNestingLimit != nesting) {
                    appendDirectChildPaths(profilePaths, current, inputPaths);
                }
                for (size_t i = 0; i < profilePaths.size(); i++) {
                    double efOffset = i == 0 ? offset : -offset;
                    clipof.Clear();
                    clipof.AddPath(profilePaths[i], JoinType::jtSquare, EndType::etClosedPolygon);
                    Paths off1;
                    clipof.Execute(off1, efOffset);
                    // make poly between original path and offset path
                    Paths boundPaths;
                    clip.Clear();
                    if (efOffset < 0) {
                        clip.AddPath(profilePaths[i], PolyType::ptSubject, true);
                        clip.AddPaths(off1, PolyType::ptClip, true);
                    }
                    else {
                        clip.AddPaths(off1, PolyType::ptSubject, true);
                        clip.AddPath(profilePaths[i], PolyType::ptClip, true);
                    }
                    clip.Execute(ClipType::ctDifference, boundPaths, PolyFillType::pftEvenOdd);

                    /** tool bounds */
                    Paths toolBoundPaths;
                    clipof.Clear();
                    clipof.AddPaths(boundPaths, JoinType::jtRound, EndType::etClosedPolygon);
                    clipof.Execute(
                        toolBoundPaths,
                        -toolRadiusScaled - finishPassOffsetScaled - cornerRoundingOffset
                    );

                    /** offset back outwards - corner rounding */
                    clipof.Clear();
                    clipof.AddPaths(toolBoundPaths, JoinType::jtRound, EndType::etClosedPolygon);
                    clipof.Execute(toolBoundPaths, cornerRoundingOffset);

                    // restore original bound paths
                    // bounding paths - i.e. area that must be cleared inside
                    // it's not the same as above due to corner rounding
                    clipof.Clear();
                    clipof.AddPaths(toolBoundPaths, JoinType::jtRound, EndType::etClosedPolygon);
                    clipof.Execute(boundPaths, toolRadiusScaled + finishPassOffsetScaled);

                    ProcessPolyNode(boundPaths, toolBoundPaths);
                }
            }
        }
    }
    return results;
}

bool Adaptive2d::FindEntryPoint(
    TPaths& progressPaths,
    const Paths& toolBoundPaths,
    const Paths& boundPaths,
    ClearedArea& clearedArea /*output-initial cleared area by helix*/,
    IntPoint& entryPoint /*output*/,
    IntPoint& toolPos,
    DoublePoint& toolDir,
    long& helixRadiusScaled
)
{
    Paths incOffset;
    Paths lastValidOffset;
    Clipper clip;
    ClipperOffset clipof;
    bool found = false;
    Paths clearedPaths;
    Paths checkPaths = toolBoundPaths;
    for (int iter = 0; iter < 10; iter++) {
        clipof.Clear();
        clipof.AddPaths(checkPaths, JoinType::jtSquare, EndType::etClosedPolygon);
        double step = MIN_STEP_CLIPPER;
        double currentDelta = -1;
        clipof.Execute(incOffset, currentDelta);
        while (!incOffset.empty()) {
            clipof.Execute(incOffset, currentDelta);
            if (!incOffset.empty()) {
                lastValidOffset = incOffset;
            }
            currentDelta -= step;
        }
        for (size_t i = 0; i < lastValidOffset.size(); i++) {
            if (!lastValidOffset[i].empty()) {
                entryPoint = Compute2DPolygonCentroid(lastValidOffset[i]);
                found = true;
                break;
            }
        }
        // check if the start point is in any of the holes
        // this may happen in case when toolBoundPaths are symmetric (boundary + holes)
        // we need to break simetry and try again
        for (size_t j = 0; j < checkPaths.size(); j++) {
            int pip = PointInPolygon(entryPoint, checkPaths[j]);
            if ((j == 0 && pip == 0) || (j > 0 && pip != 0)) {
                found = false;
                break;
            }
        }
        // check if helix fits
        const auto checkHelixFit = [&](long testHelixRadiusScaled) {
            clipof.Clear();
            Path p1;
            p1.push_back(entryPoint);
            clipof.AddPath(p1, JoinType::jtRound, EndType::etOpenRound);
            clipof.Execute(clearedPaths, (double)(testHelixRadiusScaled + toolRadiusScaled));
            CleanPolygons(clearedPaths);
            // we got first cleared area - check if it is crossing boundary
            clip.Clear();
            clip.AddPaths(clearedPaths, PolyType::ptSubject, true);
            clip.AddPaths(boundPaths, PolyType::ptClip, true);
            Paths crossing;
            clip.Execute(ClipType::ctDifference, crossing);

            return crossing.empty();
        };

        if (found) {
            // check that helix fits, and make initial polygon cleared by helix ramp
            if (!checkHelixFit(helixRampMinRadiusScaled)) {
                // min-size helix does not fit
                found = false;
            }
            else {
                // find the largest helix that fits
                // minSize = largest known fit; maxSize = largest possible fit
                long minSize = helixRampMinRadiusScaled;
                long maxSize = helixRampMaxRadiusScaled;
                while (minSize < maxSize) {
                    long testSize = (minSize + maxSize + 1) / 2;  // always testSize > minSize
                    if (checkHelixFit(testSize)) {
                        minSize = testSize;
                    }
                    else {
                        maxSize = testSize - 1;  // always maxSize >= minSize
                    }
                }
                helixRadiusScaled = minSize;
                checkHelixFit(helixRadiusScaled);  // set clearedPaths for final size
                clearedArea.SetClearedPaths(clearedPaths);
            }
        }

        if (!found) {  // break simetry and try again
            clip.Clear();
            clip.AddPaths(checkPaths, PolyType::ptSubject, true);
            auto bounds = clip.GetBounds();
            clip.Clear();
            Path rect;
            rect << IntPoint(bounds.left, bounds.bottom);
            rect << IntPoint(bounds.left, (bounds.top + bounds.bottom) / 2);
            rect << IntPoint((bounds.left + bounds.right) / 2, (bounds.top + bounds.bottom) / 2);
            rect << IntPoint((bounds.left + bounds.right) / 2, bounds.bottom);
            clip.AddPath(rect, PolyType::ptSubject, true);
            clip.AddPaths(checkPaths, PolyType::ptClip, true);
            clip.Execute(ClipType::ctIntersection, checkPaths);
        }
        if (found) {
            break;
        }
    }

    if (!found) {
        cerr << "Start point not found!" << endl;
    }
    if (found) {
        // visualize/progress for helix
        clipof.Clear();
        Path hp;
        hp << entryPoint;
        clipof.AddPath(hp, JoinType::jtRound, EndType::etOpenRound);
        Paths hps;
        clipof.Execute(hps, helixRadiusScaled);
        AddPathsToProgress(progressPaths, hps);

        toolPos = IntPoint(entryPoint.X, entryPoint.Y - helixRadiusScaled);
        toolDir = DoublePoint(1.0, 0.0);
    }
    return found;
}

bool Adaptive2d::FindEntryPointOutside(
    TPaths& progressPaths,
    const Paths& toolBoundPaths,
    const Paths& boundPaths,
    ClearedArea& clearedArea /*output-initial cleared area by helix*/,
    IntPoint& entryPoint /*output*/,
    IntPoint& toolPos,
    DoublePoint& toolDir
)
{

    UNUSED(progressPaths);  // to silence compiler warning
    UNUSED(boundPaths);     // to silence compiler warning

    Clipper clip;
    ClipperOffset clipof;
    Paths clearedPaths;
    // check if boundary shape to cut is outside the stock
    for (const auto& pth : toolBoundPaths) {
        for (size_t i = 0; i < pth.size(); i++) {
            IntPoint checkPoint = pth[i];
            IntPoint lastPoint = i > 0 ? pth[i - 1] : pth.back();
            // if point is outside the stock
            if (PointInPolygon(checkPoint, stockInputPaths.front()) == 0) {

                clipof.Clear();
                clipof.AddPaths(stockInputPaths, JoinType::jtSquare, EndType::etClosedPolygon);
                clipof.Execute(clearedPaths, 1000 * toolRadiusScaled);

                clip.Clear();
                clip.AddPaths(clearedPaths, PolyType::ptSubject, true);
                clip.AddPaths(stockInputPaths, PolyType::ptClip, true);
                clip.Execute(ClipType::ctDifference, clearedPaths);
                CleanPolygons(clearedPaths);
                SimplifyPolygons(clearedPaths);
                clearedArea.SetClearedPaths(clearedPaths);
                entryPoint = checkPoint;
                toolPos = entryPoint;
                // find tool dir
                double len = sqrt(DistanceSqrd(lastPoint, checkPoint));
                toolDir = DoublePoint(
                    (checkPoint.X - lastPoint.X) / len,
                    (checkPoint.Y - lastPoint.Y) / len
                );
                return true;
            }
        }
    }
    return false;
}

//************************************************************
//  IsClearPath - returns true if path is clear from obstacles
//***********************************************************
bool Adaptive2d::IsClearPath(const Path& tp, ClearedArea& cleared, double safetyClearance)
{
    Perf_IsClearPath.Start();
    Clipper clip;
    ClipperOffset clipof;
    clipof.AddPath(tp, JoinType::jtRound, EndType::etOpenRound);
    Paths toolShape;
    clipof.Execute(toolShape, toolRadiusScaled + safetyClearance);
    clip.AddPaths(toolShape, PolyType::ptSubject, true);
    clip.AddPaths(cleared.GetCleared(), PolyType::ptClip, true);
    Paths crossing;
    clip.Execute(ClipType::ctDifference, crossing);
    double collisionArea = 0;
    for (auto& p : crossing) {
        collisionArea += fabs(Area(p));
    }
    Perf_IsClearPath.Stop();
    return collisionArea < 1.0;
}

bool Adaptive2d::IsAllowedToCutTrough(
    const IntPoint& p1,
    const IntPoint& p2,
    ClearedArea& cleared,
    const Paths& toolBoundPaths,
    double areaFactor,
    bool skipBoundsCheck
)
{
    Perf_IsAllowedToCutTrough.Start();

    if (!skipBoundsCheck && !IsPointWithinCutRegion(toolBoundPaths, p2)) {
        // last point outside boundary - its not clear to cut
        Perf_IsAllowedToCutTrough.Stop();
        return false;
    }
    else if (!skipBoundsCheck && !IsPointWithinCutRegion(toolBoundPaths, p1)) {
        // first point outside boundary - its not clear to cut
        Perf_IsAllowedToCutTrough.Stop();
        return false;
    }
    else {
        Clipper clip;
        double distance = sqrt(DistanceSqrd(p1, p2));
        double stepSize = min(0.5 * stepOverScaled, 8 * MIN_STEP_CLIPPER);
        if (distance < stepSize / 2) {  // not significant cut
            Perf_IsAllowedToCutTrough.Stop();
            return true;
        }
        if (distance < stepSize) {  // adjust for numeric instability with small distances
            areaFactor *= 2;
        }

        IntPoint toolPos1 = p1;
        long steps = long(distance / stepSize) + 1;
        stepSize = distance / steps;
        for (long i = 1; i <= steps; i++) {
            double p = double(i) / steps;
            IntPoint toolPos2(
                long(p1.X + double(p2.X - p1.X) * p),
                long(p1.Y + double(p2.Y - p1.Y) * p)
            );
            double area = CalcCutArea(clip, toolPos1, toolPos2, cleared, false);
            // if we are cutting above optimal -> not clear to cut
            if (area > areaFactor * stepSize * optimalCutAreaPD) {
                Perf_IsAllowedToCutTrough.Stop();
                return false;
            }
            // if tool is outside boundary -> its not clear to cut
            if (!skipBoundsCheck && !IsPointWithinCutRegion(toolBoundPaths, toolPos2)) {
                Perf_IsAllowedToCutTrough.Stop();
                return false;
            }
            toolPos1 = toolPos2;
        }
    }
    Perf_IsAllowedToCutTrough.Stop();
    return true;
}

bool Adaptive2d::ResolveLinkPath(
    const IntPoint& startPoint,
    const IntPoint& endPoint,
    ClearedArea& clearedArea,
    Path& output
)
{
    vector<pair<IntPoint, IntPoint>> queue;
    queue.emplace_back(startPoint, endPoint);
    Path checkPath;
    double totalLength = 0;
    double directDistance = sqrt(DistanceSqrd(startPoint, endPoint));
    Paths linkPaths;

    double scanStep = 2 * MIN_STEP_CLIPPER;
    if (scanStep > scaleFactor * 0.1) {
        scanStep = scaleFactor * 0.1;
    }
    if (scanStep < scaleFactor * 0.01) {
        scanStep = scaleFactor * 0.01;
    }
    long limit = 10000;

    double clearance = stepOverScaled;
    double offClearance = 2 * stepOverScaled;
    if (offClearance > directDistance / 2) {
        offClearance = directDistance / 2;
        clearance = 0;
    }

    long cnt = 0;

    // to hold CLP results
    IntPoint clp;
    size_t pindex;
    size_t sindex;
    double par;

    // put a time limit on the resolving the link path
    clock_t time_limit = (clock_t)(max(keepToolDownDistRatio, 3.0) * CLOCKS_PER_SEC / 6);

    clock_t time_out = clock() + time_limit;

    while (!queue.empty()) {
        if (stopProcessing) {
            return false;
        }
        if (clock() > time_out) {
            cout << "Unable to resolve tool down linking path (limit reached)." << endl;
            return false;
        }

        cnt++;
        if (cnt > limit) {
            cout << "Unable to resolve tool down linking path @(" << endPoint.X / scaleFactor << ","
                 << endPoint.Y / scaleFactor << ") (" << limit << " points limit reached)." << endl;
            return false;
        }
        pair<IntPoint, IntPoint> pointPair = queue.back();
        queue.pop_back();

        // check for self intersections - if found discard the link path
        for (size_t i = 0; i < linkPaths.size(); i++) {
            if (linkPaths[i].front() != pointPair.first && linkPaths[i].back() != pointPair.first
                && linkPaths[i].front() != pointPair.second && linkPaths[i].back() != pointPair.second
                && IntersectionPoint(
                    linkPaths[i].front(),
                    linkPaths[i].back(),
                    pointPair.first,
                    pointPair.second,
                    clp
                )) {
                cout << "Unable to resolve tool down linking path (self-intersects)." << endl;
                return false;
            }
        }

        DoublePoint direction = DirectionV(pointPair.first, pointPair.second);
        checkPath.clear();
        if (pointPair.first == startPoint) {
            checkPath.push_back(IntPoint(
                pointPair.first.X + offClearance * direction.X,
                pointPair.first.Y + offClearance * direction.Y
            ));
        }
        else {
            checkPath.push_back(pointPair.first);
        }
        if (pointPair.second == endPoint) {
            checkPath.push_back(IntPoint(
                pointPair.second.X - offClearance * direction.X,
                pointPair.second.Y - offClearance * direction.Y
            ));
        }
        else {
            checkPath.push_back(pointPair.second);
        }

        if (IsClearPath(checkPath, clearedArea, clearance)) {
            totalLength += sqrt(DistanceSqrd(pointPair.first, pointPair.second));
            if (totalLength > keepToolDownDistRatio * directDistance) {
                return false;
            }
            Path link;
            link.push_back(pointPair.first);
            link.push_back(pointPair.second);
            linkPaths.push_back(link);
        }
        else {
            if (sqrt(DistanceSqrd(pointPair.first, pointPair.second)) < 4) {
                // segment became too short but still not clear
                return false;
            }
            DoublePoint pDir(-direction.Y, direction.X);
            // find mid point
            IntPoint midPoint(
                0.5 * double(pointPair.first.X + pointPair.second.X),
                0.5 * double(pointPair.first.Y + pointPair.second.Y)
            );
            for (long i = 1;; i++) {
                if (stopProcessing) {
                    return false;
                }
                double offset = i * scanStep;
                IntPoint checkPoint1(midPoint.X + offset * pDir.X, midPoint.Y + offset * pDir.Y);
                IntPoint checkPoint2(midPoint.X - offset * pDir.X, midPoint.Y - offset * pDir.Y);

                if (DistancePointToPathsSqrd(clearedArea.GetCleared(), checkPoint1, clp, pindex, sindex, par)
                    < DistancePointToPathsSqrd(
                        clearedArea.GetCleared(),
                        checkPoint2,
                        clp,
                        pindex,
                        sindex,
                        par
                    )) {
                    // exchange points
                    IntPoint tmp = checkPoint2;
                    checkPoint2 = checkPoint1;
                    checkPoint1 = tmp;
                }

                checkPath.clear();
                checkPath.push_back(checkPoint1);
                if (IsClearPath(checkPath, clearedArea, clearance + 1)) {  // check if point clear
                    queue.emplace_back(pointPair.first, checkPoint1);
                    queue.emplace_back(checkPoint1, pointPair.second);
                    break;
                }
                else {  // check the other side

                    checkPath.clear();
                    checkPath.push_back(checkPoint2);
                    if (IsClearPath(checkPath, clearedArea, clearance + 1)) {
                        queue.emplace_back(pointPair.first, checkPoint2);
                        queue.emplace_back(checkPoint2, pointPair.second);
                        break;
                    }
                }
                if (offset > keepToolDownDistRatio * directDistance) {
                    return false;  // can't find keep tool down link
                }
            }
        }
    }
    if (linkPaths.empty()) {
        return false;
    }
    ConnectPaths(linkPaths, linkPaths);
    output = linkPaths[0];
    return true;
}

bool Adaptive2d::MakeLeadPath(
    bool leadIn,
    const IntPoint& startPoint,
    const DoublePoint& startDir,
    const IntPoint& beaconPoint,
    ClearedArea& clearedArea,
    const Paths& toolBoundPaths,
    Path& output
)
{
    IntPoint currentPoint = startPoint;
    DoublePoint targetDir = DirectionV(currentPoint, beaconPoint);
    double distanceToBeacon = sqrt(DistanceSqrd(startPoint, beaconPoint));
    double stepSize = 0.2 * stepOverScaled + 1;
    double maxPathLen = stepOverScaled;
    DoublePoint nextDir = startDir;
    IntPoint nextPoint
        = IntPoint(currentPoint.X + nextDir.X * stepSize, currentPoint.Y + nextDir.Y * stepSize);
    Path checkPath;
    double adaptFactor = 0.4;
    double alfa = std::numbers::pi / 64;
    double pathLen = 0;
    checkPath.push_back(nextPoint);
    for (int i = 0; i < 10000; i++) {
        if (IsAllowedToCutTrough(
                IntPoint(
                    currentPoint.X + MIN_STEP_CLIPPER * nextDir.X,
                    currentPoint.Y + MIN_STEP_CLIPPER * nextDir.Y
                ),
                nextPoint,
                clearedArea,
                toolBoundPaths
            )) {
            if (output.empty()) {
                output.push_back(currentPoint);
            }
            output.push_back(nextPoint);
            currentPoint = nextPoint;
            pathLen += stepSize;
            targetDir = DirectionV(currentPoint, beaconPoint);
            nextDir = DoublePoint(
                nextDir.X + adaptFactor * targetDir.X,
                nextDir.Y + adaptFactor * targetDir.Y
            );
            NormalizeV(nextDir);
            if (pathLen > maxPathLen) {
                break;
            }
            if (pathLen > distanceToBeacon / 2) {
                break;
            }
        }
        else {
            nextDir = rotate(nextDir, leadIn ? -alfa : alfa);
        }
        nextPoint
            = IntPoint(currentPoint.X + nextDir.X * stepSize, currentPoint.Y + nextDir.Y * stepSize);
    }
    if (output.empty()) {
        output.push_back(startPoint);
    }
    return true;
}
void Adaptive2d::AppendToolPath(
    TPaths& progressPaths,
    AdaptiveOutput& output,
    const Path& passToolPath,
    ClearedArea& clearedBefore,
    ClearedArea& clearedAfter,
    const Paths& toolBoundPaths
)
{
    if (passToolPath.size() < 2) {
        return;
    }
    Perf_AppendToolPath.Start();
    UNUSED(progressPaths);  // to silence compiler warning,var is occasionally used in dev. for
                            // debugging

    IntPoint endPoint(passToolPath[0]);
    // if there is a previous path - need to resolve linking move to new path
    if (!output.AdaptivePaths.empty() && output.AdaptivePaths.back().second.size() > 1) {
        auto& lastTPath = output.AdaptivePaths.back();

        auto& lastPrevTPoint = lastTPath.second.at(lastTPath.second.size() - 2);
        auto& lastTPoint = lastTPath.second.back();

        IntPoint startPrevPoint(
            long(lastPrevTPoint.first * scaleFactor),
            long(lastPrevTPoint.second * scaleFactor)
        );
        IntPoint startPoint(long(lastTPoint.first * scaleFactor), long(lastTPoint.second * scaleFactor));

        // first we try to cut through the linking move for short distances
        bool linkFound = false;
        double linkDistance = sqrt(DistanceSqrd(startPoint, endPoint));
        if (linkDistance < NTOL) {
            linkFound = true;
        }

        if (!linkFound) {
            size_t clpPathIndex;
            size_t clpSegmentIndex;
            double clpParameter;
            IntPoint clp;

            double beaconOffset = stepOverScaled;
            if (beaconOffset > linkDistance) {
                beaconOffset = linkDistance;
            }

            double pathLen = PathLength(passToolPath);
            if (beaconOffset > pathLen / 2) {
                beaconOffset = pathLen / 2;
            }
            if (beaconOffset > linkDistance / 2) {
                beaconOffset = linkDistance / 2;
            }

            DistancePointToPathsSqrd(
                toolBoundPaths,
                startPoint,
                clp,
                clpPathIndex,
                clpSegmentIndex,
                clpParameter
            );
            DoublePoint startDir = GetPathDirectionV(toolBoundPaths[clpPathIndex], clpSegmentIndex);

            DistancePointToPathsSqrd(
                toolBoundPaths,
                endPoint,
                clp,
                clpPathIndex,
                clpSegmentIndex,
                clpParameter
            );
            DoublePoint endDir = GetPathDirectionV(toolBoundPaths[clpPathIndex], clpSegmentIndex);

            IntPoint startBeacon(
                startPoint.X - beaconOffset * (startDir.Y - startDir.X),
                startPoint.Y + beaconOffset * (startDir.X + startDir.Y)
            );
            IntPoint endBeacon(
                endPoint.X - beaconOffset * (endDir.X + endDir.Y),
                endPoint.Y + beaconOffset * (endDir.X - endDir.Y)
            );
            Path leadOutPath;
            MakeLeadPath(false, startPoint, startDir, startBeacon, clearedBefore, toolBoundPaths, leadOutPath);

            Path leadInPath;
            MakeLeadPath(
                true,
                endPoint,
                DoublePoint(-endDir.X, -endDir.Y),
                endBeacon,
                clearedBefore,
                toolBoundPaths,
                leadInPath
            );
            ReversePath(leadInPath);

            Path linkPath;
            MotionType linkType = MotionType::mtCutting;

            // this is not needed:
            // clearedBefore.ExpandCleared(leadInPath);
            // clearedBefore.ExpandCleared(leadOutPath);

            if (ResolveLinkPath(leadOutPath.back(), leadInPath.front(), clearedBefore, linkPath)) {
                linkType = MotionType::mtLinkClear;
                double remainingLeadInExtension = stepOverScaled / 2;
                while (linkPath.size() >= 2 && remainingLeadInExtension > NTOL) {
                    IntPoint p1 = linkPath.at(linkPath.size() - 2);
                    IntPoint p2 = linkPath.at(linkPath.size() - 1);
                    double l = sqrt(DistanceSqrd(p1, p2));
                    if (l >= remainingLeadInExtension) {
                        IntPoint splitPoint(
                            p1.X + (p2.X - p1.X) * (l - remainingLeadInExtension) / l,
                            p1.Y + (p2.Y - p1.Y) * (l - remainingLeadInExtension) / l
                        );
                        linkPath.pop_back();
                        linkPath.push_back(splitPoint);
                        leadInPath.insert(leadInPath.begin(), splitPoint);
                        remainingLeadInExtension = 0;
                        Path checkPath;
                        checkPath.push_back(p2);
                        checkPath.push_back(splitPoint);
                        if (!IsClearPath(checkPath, clearedBefore, 0)) {
                            remainingLeadInExtension = stepOverScaled / 2;
                        }
                    }
                    else {
                        linkPath.pop_back();
                        leadInPath.insert(leadInPath.begin(), p1);
                        remainingLeadInExtension -= l;
                        if (remainingLeadInExtension < NTOL) {
                            Path checkPath;
                            checkPath.push_back(p2);
                            checkPath.push_back(p1);
                            if (!IsClearPath(checkPath, clearedBefore, 0)) {
                                remainingLeadInExtension = stepOverScaled / 2;
                            }
                        }
                    }
                }
            }
            else {
                linkType = MotionType::mtLinkNotClear;
                double dist = sqrt(DistanceSqrd(leadOutPath.back(), leadInPath.front()));
                if (dist < 2 * stepOverScaled
                    && IsAllowedToCutTrough(
                        IntPoint(
                            leadOutPath.back().X + (leadInPath.front().X - leadOutPath.back().X) / dist,
                            leadOutPath.back().Y + (leadInPath.front().Y - leadOutPath.back().Y) / dist
                        ),
                        IntPoint(
                            leadInPath.front().X - (leadInPath.front().X - leadOutPath.back().X) / dist,
                            leadInPath.front().Y - (leadInPath.front().Y - leadOutPath.back().Y) / dist
                        ),
                        clearedBefore,
                        toolBoundPaths
                    )) {
                    linkType = MotionType::mtCutting;
                }
                // add direct linking move at clear height

                linkPath.clear();
                linkPath.push_back(leadOutPath.back());
                linkPath.push_back(leadInPath.front());
            }

            /* paths smoothing*/
            Paths linkPaths;
            linkPaths.push_back(leadOutPath);
            linkPaths.push_back(linkPath);
            linkPaths.push_back(leadInPath);

            if (linkType == MotionType::mtLinkClear) {
                SmoothPaths(linkPaths, 0.1 * stepOverScaled, 1, 4);
            }

            leadOutPath = linkPaths[0];
            linkPath = linkPaths[1];
            leadInPath = linkPaths[2];

            // add lead-out move
            TPath linkPath1;
            linkPath1.first = MotionType::mtCutting;
            for (const auto& pt : leadOutPath) {
                linkPath1.second.emplace_back(double(pt.X) / scaleFactor, double(pt.Y) / scaleFactor);
            }
            output.AdaptivePaths.push_back(linkPath1);

            // add linking path
            TPath linkPath2;
            linkPath2.first = linkType;
            for (const auto& pt : linkPath) {
                linkPath2.second.emplace_back(double(pt.X) / scaleFactor, double(pt.Y) / scaleFactor);
            }
            output.AdaptivePaths.push_back(linkPath2);

            // add lead-in move
            TPath linkPath3;
            linkPath3.first = MotionType::mtCutting;
            for (const auto& pt : leadInPath) {
                linkPath3.second.emplace_back(double(pt.X) / scaleFactor, double(pt.Y) / scaleFactor);
            }

            output.AdaptivePaths.push_back(linkPath3);

            clearedAfter.ExpandCleared(leadInPath);
            clearedAfter.ExpandCleared(leadOutPath);

            linkFound = true;
        }
        if (!linkFound) {  // nothing clear so far - check direct link with no interim points -
                           // either this is clear or we need to raise the tool
            Path tp;
            tp << startPoint;
            tp << endPoint;
            MotionType mt = IsClearPath(tp, clearedBefore) ? MotionType::mtLinkClear
                                                           : MotionType::mtLinkNotClear;

            // make cutting move through small clear links
            if (mt == MotionType::mtLinkClear && linkDistance < toolRadiusScaled) {
                mt = MotionType::mtCutting;
                clearedAfter.ExpandCleared(tp);
            }

            TPath linkPath;
            linkPath.first = mt;
            linkPath.second.emplace_back(
                double(startPoint.X) / scaleFactor,
                double(startPoint.Y) / scaleFactor
            );
            linkPath.second.emplace_back(
                double(endPoint.X) / scaleFactor,
                double(endPoint.Y) / scaleFactor
            );
            output.AdaptivePaths.push_back(linkPath);
        }
    }
    TPath cutPath;
    cutPath.first = MotionType::mtCutting;
    for (const auto& p : passToolPath) {
        DPoint nextT;
        nextT.first = double(p.X) / scaleFactor;
        nextT.second = double(p.Y) / scaleFactor;
        cutPath.second.push_back(nextT);
    }

    if (!cutPath.second.empty()) {
        output.AdaptivePaths.push_back(cutPath);
    }
    Perf_AppendToolPath.Stop();
}

void Adaptive2d::CheckReportProgress(TPaths& progressPaths, bool force)
{
    if (!force && (clock() - lastProgressTime < PROGRESS_TICKS)) {
        return;  // not yet
    }
    lastProgressTime = clock();
    if (progressPaths.empty()) {
        return;
    }
    if (progressCallback) {
        if ((*progressCallback)(progressPaths)) {
            stopProcessing = true;  // call python function, if returns true signal stop processing
        }
    }
    // clean the paths - keep the last point
    if (progressPaths.back().second.empty()) {
        return;
    }
    TPath* lastPath = &progressPaths.back();
    DPoint* lastPoint = &lastPath->second.back();
    DPoint next(lastPoint->first, lastPoint->second);
    while (progressPaths.size() > 1) {
        progressPaths.pop_back();
    }
    while (!progressPaths.front().second.empty()) {
        progressPaths.front().second.pop_back();
    }
    progressPaths.front().first = MotionType::mtCutting;
    progressPaths.front().second.push_back(next);
}

void Adaptive2d::AddPathsToProgress(TPaths& progressPaths, Paths paths, MotionType mt)
{
    for (const auto& pth : paths) {
        if (!pth.empty()) {
            progressPaths.push_back(TPath());
            progressPaths.back().first = mt;
            for (const auto pt : pth) {
                progressPaths.back().second.emplace_back(
                    double(pt.X) / scaleFactor,
                    double(pt.Y) / scaleFactor
                );
            }
            progressPaths.back().second.emplace_back(
                double(pth.front().X) / scaleFactor,
                double(pth.front().Y) / scaleFactor
            );
        }
    }
}

void Adaptive2d::AddPathToProgress(TPaths& progressPaths, const Path pth, MotionType mt)
{
    if (!pth.empty()) {
        progressPaths.push_back(TPath());
        progressPaths.back().first = mt;
        for (const auto pt : pth) {
            progressPaths.back().second.emplace_back(
                double(pt.X) / scaleFactor,
                double(pt.Y) / scaleFactor
            );
        }
    }
}

void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths)
{
    Perf_ProcessPolyNode.Start();
    current_region++;
    cout << "** Processing region: " << current_region << endl;

    // node paths are already constrained to tool boundary path for adaptive path before finishing
    // pass
    Clipper clip;
    ClipperOffset clipof;

    IntPoint entryPoint;
    long helixRadiusScaled;
    TPaths progressPaths;
    progressPaths.reserve(10000);

    CleanPolygons(toolBoundPaths);
    SimplifyPolygons(toolBoundPaths);

    CleanPolygons(boundPaths);
    SimplifyPolygons(boundPaths);

    AddPathsToProgress(progressPaths, toolBoundPaths, MotionType::mtLinkClear);

    IntPoint toolPos;
    DoublePoint toolDir;
    ClearedArea cleared(toolRadiusScaled);
    bool outsideEntry = false;
    bool firstEngagePoint = true;
    Paths engageBounds = toolBoundPaths;

    if (!forceInsideOut
        && FindEntryPointOutside(
            progressPaths,
            toolBoundPaths,
            boundPaths,
            cleared,
            entryPoint,
            toolPos,
            toolDir
        )) {
        if (!Orientation(engageBounds[0])) {
            ReversePath(engageBounds[0]);
        }
        // add initial offset of cleared area to engage paths
        Paths outsideEngage;
        clipof.Clear();
        clipof.AddPaths(stockInputPaths, JoinType::jtRound, EndType::etClosedPolygon);
        clipof.Execute(outsideEngage, toolRadiusScaled - stepOverFactor * toolRadiusScaled);
        CleanPolygons(outsideEngage);
        ReversePaths(outsideEngage);
        for (const auto& p : outsideEngage) {
            engageBounds.push_back(p);
        }
        outsideEntry = true;
    }
    else {
        if (!FindEntryPoint(
                progressPaths,
                toolBoundPaths,
                boundPaths,
                cleared,
                entryPoint,
                toolPos,
                toolDir,
                helixRadiusScaled
            )) {
            Perf_ProcessPolyNode.Stop();
            return;
        }
    }

    EngagePoint engage(engageBounds);  // engage point stepping instance

    if (outsideEntry) {
        engage.moveToClosestPoint(toolPos, 2 * MIN_STEP_CLIPPER);
        engage.moveForward(MIN_STEP_CLIPPER);
        toolPos = engage.getCurrentPoint();
        toolDir = engage.getCurrentDir();
        entryPoint = toolPos;
    }

    // cout << "Entry point:" << double(entryPoint.X)/scaleFactor << "," <<
    // double(entryPoint.Y)/scaleFactor << endl;

    AdaptiveOutput output;
    output.ReturnMotionType = 0;
    output.HelixCenterPoint.first = double(entryPoint.X) / scaleFactor;
    output.HelixCenterPoint.second = double(entryPoint.Y) / scaleFactor;

    long stepScaled = long(MIN_STEP_CLIPPER);
    IntPoint engagePoint;

    IntPoint newToolPos;
    DoublePoint newToolDir;

    CheckReportProgress(progressPaths, true);

    IntPoint startPoint = toolPos;
    output.StartPoint = DPoint(double(startPoint.X) / scaleFactor, double(startPoint.Y) / scaleFactor);

    Path passToolPath;  // to store pass toolpath
    Path toClearPath;
    IntPoint clp;                 // to store closest point
    vector<DoublePoint> gyro;     // used to average tool direction
    vector<double> angleHistory;  // use to predict deflection angle
    double angle = std::numbers::pi;
    engagePoint = toolPos;
    Interpolation interp;  // interpolation instance

    long total_iterations = 0;
    long total_points = 0;
    long total_exceeded = 0;
    long total_output_points = 0;
    long over_cut_count = 0;
    long bad_engage_count = 0;
    double prevDistFromStart = 0;
    double refinement_factor = 1;
    bool prevDistTrend = false;

    double perf_total_len = 0;
#ifdef DEV_MODE
    clock_t start_clock = clock();
#endif
    ClearedArea clearedBeforePass(toolRadiusScaled);
    clearedBeforePass.SetClearedPaths(cleared.GetCleared());

    //*******************************
    // LOOP - PASSES
    //*******************************
    for (long pass = 0; pass < PASSES_LIMIT; pass++) {
        if (stopProcessing) {
            break;
        }

        passToolPath.clear();
        toClearPath.clear();
        angleHistory.clear();

        // append a new path to progress info paths
        if (progressPaths.empty()) {
            progressPaths.push_back(TPath());
        }
        else {
            // append new path if previous not empty
            if (!progressPaths.back().second.empty()) {
                progressPaths.push_back(TPath());
            }
        }

        angle = std::numbers::pi / 4;  // initial pass angle
        bool recalcArea = false;
        double cumulativeCutArea = 0;
        // init gyro
        gyro.clear();
        for (int i = 0; i < DIRECTION_SMOOTHING_BUFLEN; i++) {
            gyro.push_back(toolDir);
        }

        size_t clpPathIndex;
        size_t clpSegmentIndex;
        double clpParameter;
        double passLength = 0;
        double noCutDistance = 0;
        clearedBeforePass.SetClearedPaths(cleared.GetCleared());
        //*******************************
        // LOOP - POINTS
        //*******************************
        for (long point_index = 0; point_index < POINTS_PER_PASS_LIMIT; point_index++) {
            if (stopProcessing) {
                break;
            }

            total_points++;
            AverageDirection(gyro, toolDir);
            Perf_DistanceToBoundary.Start();

            double distanceToBoundary = sqrt(
                DistancePointToPathsSqrd(toolBoundPaths, toolPos, clp, clpPathIndex, clpSegmentIndex, clpParameter)
            );
            DoublePoint boundaryDir = GetPathDirectionV(toolBoundPaths[clpPathIndex], clpSegmentIndex);
            double distBoundaryPointToEngage = sqrt(DistanceSqrd(clp, engagePoint));

            Perf_DistanceToBoundary.Stop();
            double distanceToEngage = sqrt(DistanceSqrd(toolPos, engagePoint));

            double targetAreaPD = optimalCutAreaPD;

            // set the step size: 1x to 8x base size
            double slowDownDistance = max(double(toolRadiusScaled) / 4, MIN_STEP_CLIPPER * 8);
            if (distanceToBoundary < slowDownDistance || distanceToEngage < slowDownDistance) {
                stepScaled = long(MIN_STEP_CLIPPER);
            }
            else if (fabs(angle) > NTOL) {
                stepScaled = long(MIN_STEP_CLIPPER / fabs(angle));
            }
            else {
                stepScaled = long(MIN_STEP_CLIPPER * 8);
            }

            // clamp the step size - for stability
            if (stepScaled > min(long(toolRadiusScaled / 4), long(MIN_STEP_CLIPPER * 8))) {
                stepScaled = min(long(toolRadiusScaled / 4), long(MIN_STEP_CLIPPER * 8));
            }
            if (stepScaled < MIN_STEP_CLIPPER) {
                stepScaled = long(MIN_STEP_CLIPPER);
            }

            //*****************************
            // ANGLE vs AREA ITERATIONS
            //*****************************
            double predictedAngle = averageDV(angleHistory);
            double maxError = AREA_ERROR_FACTOR * optimalCutAreaPD;
            double area = 0;
            double areaPD = 0;
            interp.clear();
            /******************************/
            Perf_PointIterations.Start();
            int iteration;
            double prev_error = __DBL_MAX__;
            bool pointNotInterp;
            for (iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
                total_iterations++;
                if (iteration == 0) {
                    angle = predictedAngle;
                    pointNotInterp = true;
                }
                else if (iteration == 1) {
                    angle = interp.MIN_ANGLE;  // max engage
                    pointNotInterp = true;
                }
                else if (iteration == 2) {
                    if (interp.bothSides()) {
                        angle = interp.interpolateAngle();
                        pointNotInterp = false;
                    }
                    else {
                        angle = interp.MAX_ANGLE;  // min engage
                        pointNotInterp = true;
                    }
                }
                else {
                    angle = interp.interpolateAngle();
                    pointNotInterp = false;
                }
                angle = interp.clampAngle(angle);

                newToolDir = rotate(toolDir, angle);
                newToolPos = IntPoint(
                    long(toolPos.X + newToolDir.X * stepScaled),
                    long(toolPos.Y + newToolDir.Y * stepScaled)
                );

                // Skip iteration if this IntPoint has already been processed
                bool intRepeat = false;
                if (interp.m_min && newToolPos == interp.m_min->first.second) {
                    interp.m_min = {{angle, newToolPos}, interp.m_min->second};
                    intRepeat = true;
                }
                if (interp.m_max && newToolPos == interp.m_max->first.second) {
                    interp.m_max = {{angle, newToolPos}, interp.m_max->second};
                    intRepeat = true;
                }

                if (intRepeat) {
                    if (interp.m_min && interp.m_max
                        && abs(interp.m_min->first.second.X - interp.m_max->first.second.X) <= 1
                        && abs(interp.m_min->first.second.Y - interp.m_max->first.second.Y) <= 1) {
                        if (pointNotInterp) {
                            // if this happens while testing min/max of the range it doesn't mean
                            // anything; only exit early if interpolation is down to adjacent
                            // integers
                            continue;
                        }
                        // exit early, selecting the better of the two adjacent integers
                        double error;
                        if (abs(interp.m_min->second) < abs(interp.m_max->second)) {
                            newToolDir = rotate(toolDir, interp.m_min->first.first);
                            newToolPos = interp.m_min->first.second;
                            error = interp.m_min->second;
                        }
                        else {
                            newToolDir = rotate(toolDir, interp.m_max->first.first);
                            newToolPos = interp.m_max->first.second;
                            error = interp.m_max->second;
                        }
                        areaPD = error + targetAreaPD;
                        area = areaPD * double(stepScaled);
                        break;
                    }
                    continue;
                }

                area = CalcCutArea(clip, toolPos, newToolPos, cleared);

                areaPD = area / double(stepScaled);  // area per distance
                double error = areaPD - targetAreaPD;
                interp.addPoint(error, {angle, newToolPos}, pointNotInterp);
                // cout << " iter:" << iteration << " angle:" << angle << " area:" << areaPD
                //      << " target:" << targetAreaPD << " error:" << error << " max:" << maxError
                //      << endl;
                if (fabs(error) < maxError) {
                    angleHistory.push_back(angle);
                    if (angleHistory.size() > ANGLE_HISTORY_POINTS) {
                        angleHistory.erase(angleHistory.begin());
                    }
                    break;
                }
                if (iteration == MAX_ITERATIONS - 1) {
                    total_exceeded++;
                }
                prev_error = error;
            }
            Perf_PointIterations.Stop();

            recalcArea = false;
            // approach end boundary tangentially
            double relDistToBoundary = 4 * distanceToBoundary / stepOverScaled;
            if (relDistToBoundary <= 1.0 && passLength > 2 * stepOverFactor
                && distanceToEngage > 2 * stepOverScaled
                && distBoundaryPointToEngage > 2 * stepOverScaled) {
                double wb = 1 - relDistToBoundary;
                newToolDir = DoublePoint(
                    newToolDir.X + wb * boundaryDir.X,
                    newToolDir.Y + wb * boundaryDir.Y
                );
                NormalizeV(newToolDir);
                newToolPos = IntPoint(
                    long(toolPos.X + newToolDir.X * stepScaled),
                    long(toolPos.Y + newToolDir.Y * stepScaled)
                );
                recalcArea = true;
            }

            //**********************************************
            // CHECK AND RECORD NEW TOOL POS
            //**********************************************
            long rotateStep = 0;
            while (!IsPointWithinCutRegion(toolBoundPaths, newToolPos) && rotateStep < 180) {
                rotateStep++;
                // if new tool pos. outside boundary rotate until back in
                recalcArea = true;
                newToolDir = rotate(newToolDir, std::numbers::pi / 90);
                newToolPos = IntPoint(
                    long(toolPos.X + newToolDir.X * stepScaled),
                    long(toolPos.Y + newToolDir.Y * stepScaled)
                );
            }
            if (rotateStep >= 180) {
#ifdef DEV_MODE
                cerr << "Warning: unexpected number of rotate iterations." << endl;
#endif
                break;
            }

            if (recalcArea) {
                area = CalcCutArea(clip, toolPos, newToolPos, cleared);
            }

            // safety condition
            if (area > stepScaled * optimalCutAreaPD && areaPD > 2 * optimalCutAreaPD) {
                over_cut_count++;
                break;
            }

            // update cleared paths when trend of distance from start point changes sign (starts to
            // get closer, or start to get farther)
            double distFromStart = sqrt(DistanceSqrd(toolPos, startPoint));
            bool distanceTrend = distFromStart > prevDistFromStart ? true : false;

            if (distanceTrend != prevDistTrend) {
                cleared.ExpandCleared(toClearPath);
                toClearPath.clear();
            }
            prevDistTrend = distanceTrend;
            prevDistFromStart = distFromStart;

            if (area > 0.5 * MIN_CUT_AREA_FACTOR * optimalCutAreaPD) {  // cut is ok - record it
                noCutDistance = 0;
                if (toClearPath.empty()) {
                    toClearPath.push_back(toolPos);
                }
                toClearPath.push_back(newToolPos);

                cumulativeCutArea += area;

                // append to toolpaths
                if (passToolPath.empty()) {
                    // in outside entry first successful cut defines the "helix center" and start
                    // point in this case helix diameter is 0 (straight line downwards)
                    if (output.AdaptivePaths.empty() && outsideEntry) {
                        entryPoint = toolPos;
                        output.HelixCenterPoint.first = double(entryPoint.X) / scaleFactor;
                        output.HelixCenterPoint.second = double(entryPoint.Y) / scaleFactor;
                        output.StartPoint = DPoint(
                            double(entryPoint.X) / scaleFactor,
                            double(entryPoint.Y) / scaleFactor
                        );
                    }
                    passToolPath.push_back(toolPos);
                }
                passToolPath.push_back(newToolPos);
                perf_total_len += stepScaled;
                passLength += stepScaled;
                toolPos = newToolPos;

                // append to progress info paths
                if (progressPaths.empty()) {
                    progressPaths.push_back(TPath());
                }
                progressPaths.back().second.emplace_back(
                    double(newToolPos.X) / scaleFactor,
                    double(newToolPos.Y) / scaleFactor
                );

                // append gyro
                gyro.push_back(newToolDir);
                gyro.erase(gyro.begin());
                CheckReportProgress(progressPaths);
            }
            else {
#ifdef DEV_MODE
                // if(point_index==0) {
                // 	engage_no_cut_count++;
                // 	cout<<"Break:no cut #" << engage_no_cut_count << ", bad engage, pass:" << pass
                // << " over_cut_count:" << over_cut_count << endl;
                // }
#endif
                // cout<<"Break: no cut @" << point_index << endl;
                if (noCutDistance > stepOverScaled) {
                    break;
                }
                noCutDistance += stepScaled;
            }
        } /* end of points loop*/

        if (!toClearPath.empty()) {
            cleared.ExpandCleared(toClearPath);
            toClearPath.clear();
        }
        if (cumulativeCutArea > MIN_CUT_AREA_FACTOR * optimalCutAreaPD) {
            Path cleaned;
            CleanPath(passToolPath, cleaned, CLEAN_PATH_TOLERANCE);
            total_output_points += long(cleaned.size());
            AppendToolPath(progressPaths, output, cleaned, clearedBeforePass, cleared, toolBoundPaths);
            CheckReportProgress(progressPaths);
            bad_engage_count = 0;
            engage.ResetPasses();
        }
        else {
            bad_engage_count++;
        }

        if (bad_engage_count > 10000) {
            cerr << "Break (next valid engage point not found)." << endl;
            break;
        }

        /*****NEXT ENGAGE POINT******/
        if (firstEngagePoint) {
            engage.moveToClosestPoint(newToolPos, stepScaled + 1);
            firstEngagePoint = false;
        }
        else {
            double moveDistance = ENGAGE_SCAN_DISTANCE_FACTOR * stepOverScaled * refinement_factor;

            if (!engage.nextEngagePoint(
                    this,
                    cleared,
                    moveDistance,
                    ENGAGE_AREA_THR_FACTOR * optimalCutAreaPD,
                    4 * referenceCutArea * stepOverFactor
                )) {
                // check if there are any uncleared area left
                Paths remaining;
                for (const auto& p : cleared.GetCleared()) {
                    if (!p.empty() && IsPointWithinCutRegion(toolBoundPaths, p.front())
                        && DistancePointToPathsSqrd(
                               boundPaths,
                               p.front(),
                               clp,
                               clpPathIndex,
                               clpSegmentIndex,
                               clpParameter
                           ) > 4 * toolRadiusScaled * toolRadiusScaled) {
                        remaining.push_back(p);
                    }
                };
                if (remaining.empty()) {
                    cout << "All cleared." << endl;
                    break;
                }
                else {
                    cout << "Clearing " << remaining.size() << " remaining internal path(s)." << endl;
                }

                // try to find new engage point along the remaining
                clipof.Clear();
                clipof.AddPaths(remaining, JoinType::jtRound, EndType::etClosedPolygon);
                clipof.Execute(remaining, toolRadiusScaled - 0.5 * stepOverScaled);

                ReversePaths(remaining);
                engage.SetPaths(remaining);
                engage.moveToClosestPoint(newToolPos, stepScaled + 1);
                if (!engage.nextEngagePoint(
                        this,
                        cleared,
                        moveDistance,
                        ENGAGE_AREA_THR_FACTOR * optimalCutAreaPD,
                        4 * referenceCutArea * stepOverFactor
                    )) {
                    break;
                }
            }
        }
        toolPos = engage.getCurrentPoint();
        toolDir = engage.getCurrentDir();
    }

    //**********************************
    //*  FINISHING PASS                *
    //**********************************
    if (finishingProfile) {
        Paths finishingPaths;
        clipof.Clear();
        clipof.AddPaths(boundPaths, JoinType::jtRound, EndType::etClosedPolygon);
        clipof.Execute(finishingPaths, -toolRadiusScaled);

        clipof.Clear();
        clipof.AddPaths(finishingPaths, JoinType::jtRound, EndType::etClosedPolygon);
        clipof.Execute(toolBoundPaths, -1);

        IntPoint lastPoint = toolPos;
        Path finShiftedPath;

        bool allCutsAllowed = true;
        while (!stopProcessing && PopPathWithClosestPoint(finishingPaths, lastPoint, finShiftedPath)) {
            if (finShiftedPath.empty()) {
                continue;
            }
            // skip finishing passes outside the stock boundary - no sense to cut where is no
            // material
            bool allPointsOutside = true;
            IntPoint p1 = finShiftedPath.front();
            for (const auto& pt : finShiftedPath) {

                // midpoint
                if (IsPointWithinCutRegion(
                        stockInputPaths,
                        IntPoint((p1.X + pt.X) / 2, (p1.Y + pt.Y) / 2)
                    )) {
                    allPointsOutside = false;
                    break;
                }
                // current point
                if (IsPointWithinCutRegion(stockInputPaths, pt)) {
                    allPointsOutside = false;
                    break;
                }

                p1 = pt;
            }
            if (allPointsOutside) {
                continue;
            }

            progressPaths.push_back(TPath());
            // show in progress cb
            for (auto& pt : finShiftedPath) {
                progressPaths.back().second.emplace_back(
                    double(pt.X) / scaleFactor,
                    double(pt.Y) / scaleFactor
                );
            }

            if (!finShiftedPath.empty()) {
                finShiftedPath << finShiftedPath.front();  // make sure its closed
            }

            Path finCleaned;
            CleanPath(finShiftedPath, finCleaned, FINISHING_CLEAN_PATH_TOLERANCE);

            // sanity check for finishing paths - check the area of finishing cut
            for (size_t i = 1; i < finCleaned.size(); i++) {
                if (!IsAllowedToCutTrough(
                        finCleaned.at(i - 1),
                        finCleaned.at(i),
                        cleared,
                        toolBoundPaths,
                        2.0,
                        true
                    )) {
                    allCutsAllowed = false;
                }
            }

            // make sure it's closed
            finCleaned.push_back(finCleaned.front());
            AppendToolPath(progressPaths, output, finCleaned, cleared, cleared, toolBoundPaths);

            cleared.ExpandCleared(finCleaned);

            if (!finCleaned.empty()) {
                lastPoint.X = finCleaned.back().X;
                lastPoint.Y = finCleaned.back().Y;
            }
        }

        Path returnPath;
        returnPath << lastPoint;
        returnPath << entryPoint;
        output.ReturnMotionType = IsClearPath(returnPath, cleared) ? MotionType::mtLinkClear
                                                                   : MotionType::mtLinkNotClear;

        // dump performance results
#ifdef DEV_MODE
        Perf_ProcessPolyNode.Stop();
        Perf_ProcessPolyNode.DumpResults();
        Perf_PointIterations.DumpResults();
        Perf_CalcCutAreaCirc.DumpResults();
        Perf_CalcCutAreaClip.DumpResults();
        Perf_NextEngagePoint.DumpResults();
        Perf_ExpandCleared.DumpResults();
        Perf_DistanceToBoundary.DumpResults();
        Perf_AppendToolPath.DumpResults();
        Perf_IsAllowedToCutTrough.DumpResults();
        Perf_IsClearPath.DumpResults();
#endif
        CheckReportProgress(progressPaths, true);
#ifdef DEV_MODE
        double duration = ((double)(clock() - start_clock)) / CLOCKS_PER_SEC;
        cout << "PolyNode perf:" << perf_total_len / double(scaleFactor) / duration << " mm/sec"
             << " processed_points:" << total_points << " output_points:" << total_output_points
             << " total_iterations:" << total_iterations
             << " iter_per_point:" << (double(total_iterations) / ((double(total_points) + 0.001)))
             << " total_exceeded:" << total_exceeded << " ("
             << 100 * double(total_exceeded) / double(total_points) << "%)" << endl;
#else
        (void)total_output_points;
        (void)over_cut_count;
        (void)total_exceeded;
        (void)total_points;
        (void)total_iterations;
        (void)perf_total_len;
#endif

        // warn about invalid paths being detected
        if (!allCutsAllowed) {
            cerr << "Warning: some cuts may be above optimal step-over. Please double check the "
                    "results."
                 << endl
                 << "Hint: try to modify accuracy and/or step-over." << endl;
        }
    }
    results.push_back(output);
}

}  // namespace AdaptivePath