nlbn 1.0.12

Fast and reliable EasyEDA/LCSC to KiCad converter with batch processing support
Documentation
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
use crate::error::{EasyedaError, Result};
use crate::easyeda::models::*;

pub struct SymbolImporter;

impl SymbolImporter {
    pub fn parse(data_str: &[String]) -> Result<EeSymbol> {
        log::debug!("Parsing symbol with {} shapes", data_str.len());

        let mut symbol = EeSymbol {
            name: String::new(),
            prefix: String::new(),
            pins: Vec::new(),
            rectangles: Vec::new(),
            circles: Vec::new(),
            ellipses: Vec::new(),
            arcs: Vec::new(),
            polylines: Vec::new(),
            polygons: Vec::new(),
            paths: Vec::new(),
            texts: Vec::new(),
        };

        for shape in data_str {
            if shape.is_empty() {
                continue;
            }

            // Split by "~" to get fields
            let fields: Vec<&str> = shape.split('~').collect();
            if fields.is_empty() {
                continue;
            }

            let designator = fields[0];

            log::debug!("Shape designator: '{}', fields: {}", designator, fields.len());

            match designator {
                "P" => {
                    // Pin: P~show~electric~x~y~rotation~gId~locked~spicePin~id
                    // Pins contain multiple segments separated by ^^
                    log::debug!("Parsing pin: {}", shape);
                    if let Ok(pin) = Self::parse_pin(shape) {
                        log::debug!("Successfully parsed pin: {} at ({}, {})", pin.number, pin.x, pin.y);
                        symbol.pins.push(pin);
                    } else {
                        log::warn!("Failed to parse pin from: {}", shape);
                    }
                }
                "R" => {
                    // Rectangle: R~x~y~width~height~id~locked~layerid~type~fill
                    if let Ok(rect) = Self::parse_rectangle(&fields) {
                        symbol.rectangles.push(rect);
                    }
                }
                "C" => {
                    // Circle: C~center_x~center_y~radius~stroke_color~stroke_width~stroke_style~fill_color~id~is_locked
                    log::debug!("Parsing circle with {} fields: {:?}", fields.len(), fields);
                    if let Ok(circle) = Self::parse_circle(&fields) {
                        log::debug!("Successfully parsed circle at ({}, {}), radius {}, fill {}",
                                   circle.cx, circle.cy, circle.radius, circle.fill);
                        symbol.circles.push(circle);
                    } else {
                        log::warn!("Failed to parse circle from: {}", shape);
                    }
                }
                "E" => {
                    // Ellipse: E~center_x~center_y~radius_x~radius_y~stroke_color~stroke_width~stroke_style~fill_color~id~is_locked
                    log::debug!("Parsing ellipse with {} fields: {:?}", fields.len(), fields);
                    if let Ok(ellipse) = Self::parse_ellipse(&fields) {
                        log::debug!("Successfully parsed ellipse at ({}, {}), rx {}, ry {}, fill {}",
                                   ellipse.cx, ellipse.cy, ellipse.rx, ellipse.ry, ellipse.fill);
                        symbol.ellipses.push(ellipse);
                    } else {
                        log::warn!("Failed to parse ellipse from: {}", shape);
                    }
                }
                "A" => {
                    // Arc can be in two formats:
                    // 1. Traditional: A~x~y~radius~startAngle~endAngle~id~locked~layerid~type
                    // 2. SVG path: A~M x y A rx ry angle large sweep x y~~color~width~...
                    log::debug!("Parsing arc with {} fields", fields.len());

                    // Check if second field starts with "M" (SVG path format)
                    if fields.len() > 1 && fields[1].trim().starts_with("M") {
                        log::debug!("Detected SVG path arc: {}", fields[1]);
                        if let Ok(path_arcs) = Self::parse_svg_arc(&fields) {
                            symbol.arcs.extend(path_arcs);
                        } else {
                            log::warn!("Failed to parse SVG arc from: {}", shape);
                        }
                    } else {
                        // Traditional format
                        if let Ok(arc) = Self::parse_arc(&fields) {
                            symbol.arcs.push(arc);
                        } else {
                            log::warn!("Failed to parse traditional arc from: {}", shape);
                        }
                    }
                }
                "PL" => {
                    // Polyline: PL~x1 y1 x2 y2 ...~width~id~locked~layerid~type
                    if let Ok(polyline) = Self::parse_polyline(&fields) {
                        symbol.polylines.push(polyline);
                    }
                }
                "PG" => {
                    // Polygon: PG~x1 y1 x2 y2 ...~width~id~locked~layerid~type~fill
                    if let Ok(polygon) = Self::parse_polygon(&fields) {
                        symbol.polygons.push(polygon);
                    }
                }
                "PT" => {
                    // Path (SVG path): PT~M x y L x y Z~color~width~...~fill
                    log::debug!("Parsing PT path with {} fields", fields.len());
                    if let Ok(polygon) = Self::parse_pt_path(&fields) {
                        symbol.polygons.push(polygon);
                    } else {
                        log::warn!("Failed to parse PT path from: {}", shape);
                    }
                }
                "T" => {
                    // Text: T~x~y~rotation~text~id~locked~layerid~type~fontSize
                    if let Ok(text) = Self::parse_text(&fields) {
                        symbol.texts.push(text);
                    }
                }
                "PATH" => {
                    // Path: PATH~width~layer~path_data~gId~locked
                    if let Ok(path) = Self::parse_path(&fields) {
                        symbol.paths.push(path);
                    }
                }
                "LIB" => {
                    // Library info: LIB~x~y~package~id~locked
                    if fields.len() > 3 {
                        symbol.name = fields[3].to_string();
                    }
                }
                _ => {}
            }
        }

        // Set default prefix if not found
        if symbol.prefix.is_empty() {
            symbol.prefix = "U".to_string();
        }

        log::info!("Parsed symbol: {} pins, {} rectangles, {} circles, {} ellipses, {} polylines",
                   symbol.pins.len(), symbol.rectangles.len(), symbol.circles.len(), symbol.ellipses.len(), symbol.polylines.len());

        Ok(symbol)
    }

    fn parse_pin(pin_data: &str) -> Result<EePin> {
        // Pin data contains multiple segments separated by ^^
        // Segment 0: P~is_displayed~type~spice_pin_number~pos_x~pos_y~rotation~id~is_locked
        // Segment 1: dot_x~dot_y
        // Segment 2: path~color
        // Segment 3: is_displayed~pos_x~pos_y~rotation~text~text_anchor~font~font_size
        // Segment 4: number fields
        // Segment 5: dot_bis (is_displayed~circle_x~circle_y)
        // Segment 6: clock (is_displayed~path)

        let segments: Vec<&str> = pin_data.split("^^").collect();
        if segments.is_empty() {
            return Err(EasyedaError::InvalidData("Empty pin data".to_string()).into());
        }

        // Parse first segment (pin settings)
        let fields: Vec<&str> = segments[0].split('~').collect();
        if fields.len() < 7 {
            return Err(EasyedaError::InvalidData(format!("Invalid pin data, only {} fields in segment 0", fields.len())).into());
        }

        // Field indices: P~is_displayed~type~spice_pin_number~pos_x~pos_y~rotation~id~is_locked
        let number = fields[3].to_string(); // spice_pin_number
        let x = fields[4].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid pin X coordinate".to_string()))?;
        let y = fields[5].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid pin Y coordinate".to_string()))?;
        let rotation = fields[6].parse::<i32>().unwrap_or(0);

        // Extract electric type from field 2
        let electric_type = fields[2].to_string();

        // Extract pin name from segment 3 if available
        let name = if segments.len() > 3 {
            let name_fields: Vec<&str> = segments[3].split('~').collect();
            if name_fields.len() > 4 {
                name_fields[4].to_string() // text field
            } else {
                "PIN".to_string()
            }
        } else {
            "PIN".to_string()
        };

        // Extract pin length from segment 2 (path) if available
        let length = if segments.len() > 2 {
            let path_fields: Vec<&str> = segments[2].split('~').collect();
            if !path_fields.is_empty() {
                // Path format is like "M 0,0 h -10" or "M 0,0 v 10"
                // Extract the number after 'h' (horizontal) or 'v' (vertical)
                let path = path_fields[0];

                // Try 'h' first (horizontal)
                if let Some(h_pos) = path.rfind('h') {
                    let num_str = &path[h_pos+1..].trim();
                    let parsed_length = num_str.parse::<f64>().unwrap_or(100.0).abs();
                    log::debug!("Pin {} ({}): path='{}', extracted length={}", number, name, path, parsed_length);
                    parsed_length
                }
                // Try 'v' (vertical)
                else if let Some(v_pos) = path.rfind('v') {
                    let num_str = &path[v_pos+1..].trim();
                    let parsed_length = num_str.parse::<f64>().unwrap_or(100.0).abs();
                    log::debug!("Pin {} ({}): path='{}', extracted length={}", number, name, path, parsed_length);
                    parsed_length
                }
                else {
                    log::debug!("Pin {} ({}): path='{}' has no 'h' or 'v', using default length=100", number, name, path);
                    100.0
                }
            } else {
                100.0
            }
        } else {
            100.0
        };

        Ok(EePin {
            number,
            name,
            x,
            y,
            rotation,
            length,
            name_visible: true,
            number_visible: true,
            electric_type,
            dot: false,
            clock: false,
        })
    }

    fn parse_rectangle(fields: &[&str]) -> Result<EeRectangle> {
        if fields.len() < 7 {
            return Err(EasyedaError::InvalidData("Invalid rectangle data".to_string()).into());
        }

        log::debug!("Parsing rectangle with {} fields: {:?}", fields.len(), fields);

        // R~pos_x~pos_y~rx~ry~width~height~stroke_color~stroke_width~stroke_style~fill_color~id~locked
        let x = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid rectangle X".to_string()))?;
        let y = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid rectangle Y".to_string()))?;
        // fields[3] and fields[4] are rx, ry (corner radius) - skip them
        let width = fields[5].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid rectangle width".to_string()))?;
        let height = fields[6].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid rectangle height".to_string()))?;

        // fill_color is at index 10
        let fill = fields.len() > 10 && !fields[10].is_empty() && fields[10] != "none";

        log::debug!("Rectangle fill_color field[10] = '{}', fill = {}",
            if fields.len() > 10 { fields[10] } else { "N/A" }, fill);

        Ok(EeRectangle {
            x,
            y,
            width,
            height,
            stroke_width: 1.0,
            fill,
            layer_id: 0,
        })
    }

    fn parse_circle(fields: &[&str]) -> Result<EeCircle> {
        if fields.len() < 4 {
            return Err(EasyedaError::InvalidData("Invalid circle data".to_string()).into());
        }

        // C~center_x~center_y~radius~stroke_color~stroke_width~stroke_style~fill_color~id~is_locked
        let cx = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid circle CX".to_string()))?;
        let cy = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid circle CY".to_string()))?;
        let radius = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid circle radius".to_string()))?;

        // fill_color is at index 7, check if it's not empty and not "none"
        let fill = fields.len() > 7 && !fields[7].is_empty() && fields[7] != "none";

        log::debug!("Circle fill_color field[7] = '{}', fill = {}",
            if fields.len() > 7 { fields[7] } else { "N/A" }, fill);

        Ok(EeCircle {
            cx,
            cy,
            radius,
            stroke_width: 1.0,
            fill,
            layer_id: 0,
        })
    }

    fn parse_ellipse(fields: &[&str]) -> Result<EeEllipse> {
        if fields.len() < 5 {
            return Err(EasyedaError::InvalidData("Invalid ellipse data".to_string()).into());
        }

        // E~center_x~center_y~radius_x~radius_y~stroke_color~stroke_width~stroke_style~fill_color~id~is_locked
        let cx = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid ellipse CX".to_string()))?;
        let cy = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid ellipse CY".to_string()))?;
        let rx = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid ellipse RX".to_string()))?;
        let ry = fields[4].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid ellipse RY".to_string()))?;

        // fill_color is at index 8, check if it's not empty and not "none"
        let fill = fields.len() > 8 && !fields[8].is_empty() && fields[8] != "none";

        log::debug!("Ellipse fill_color field[8] = '{}', fill = {}",
            if fields.len() > 8 { fields[8] } else { "N/A" }, fill);

        Ok(EeEllipse {
            cx,
            cy,
            rx,
            ry,
            stroke_width: 1.0,
            fill,
        })
    }

    fn parse_arc(fields: &[&str]) -> Result<EeArc> {
        if fields.len() < 6 {
            return Err(EasyedaError::InvalidData("Invalid arc data".to_string()).into());
        }

        let x = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid arc X".to_string()))?;
        let y = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid arc Y".to_string()))?;
        let radius = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid arc radius".to_string()))?;
        let start_angle = fields[4].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid arc start angle".to_string()))?;
        let end_angle = fields[5].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid arc end angle".to_string()))?;

        Ok(EeArc {
            x,
            y,
            radius,
            start_angle,
            end_angle,
            stroke_width: 1.0,
        })
    }

    fn parse_svg_arc(fields: &[&str]) -> Result<Vec<EeArc>> {
        use crate::easyeda::svg_parser::{parse_svg_path, SvgCommand};

        if fields.len() < 2 {
            return Err(EasyedaError::InvalidData("Invalid SVG arc data".to_string()).into());
        }

        let svg_path = fields[1];
        let commands = parse_svg_path(svg_path)?;

        let mut arcs = Vec::new();
        let mut current_pos = (0.0, 0.0);

        for cmd in commands {
            match cmd {
                SvgCommand::MoveTo { x, y } => {
                    current_pos = (x, y);
                }
                SvgCommand::Arc { rx, ry, angle: _, large_arc: _, sweep, x, y } => {
                    // Convert SVG arc to center-based arc
                    // For simplicity, approximate with center at midpoint
                    let cx = (current_pos.0 + x) / 2.0;
                    let cy = (current_pos.1 + y) / 2.0;
                    let radius = ((rx + ry) / 2.0).abs();

                    // Calculate angles from start and end points
                    let start_angle = ((current_pos.1 - cy).atan2(current_pos.0 - cx)).to_degrees();
                    let end_angle = ((y - cy).atan2(x - cx)).to_degrees();

                    // Adjust angles based on sweep direction
                    let (start_angle, end_angle) = if sweep {
                        if end_angle < start_angle {
                            (start_angle, end_angle + 360.0)
                        } else {
                            (start_angle, end_angle)
                        }
                    } else {
                        if start_angle < end_angle {
                            (start_angle + 360.0, end_angle)
                        } else {
                            (start_angle, end_angle)
                        }
                    };

                    arcs.push(EeArc {
                        x: cx,
                        y: cy,
                        radius,
                        start_angle,
                        end_angle,
                        stroke_width: 1.0,
                    });

                    current_pos = (x, y);
                }
                SvgCommand::LineTo { x, y } => {
                    current_pos = (x, y);
                }
                SvgCommand::ClosePath => {}
            }
        }

        Ok(arcs)
    }

    fn parse_polyline(fields: &[&str]) -> Result<EePolyline> {
        if fields.len() < 2 {
            return Err(EasyedaError::InvalidData("Invalid polyline data".to_string()).into());
        }

        let points_str = fields[1];
        let points = Self::parse_points(points_str)?;

        let stroke_width = if fields.len() > 2 {
            fields[2].parse::<f64>().unwrap_or(1.0)
        } else {
            1.0
        };

        Ok(EePolyline {
            points,
            stroke_width,
        })
    }

    fn parse_polygon(fields: &[&str]) -> Result<EePolygon> {
        if fields.len() < 2 {
            return Err(EasyedaError::InvalidData("Invalid polygon data".to_string()).into());
        }

        let points_str = fields[1];
        let points = Self::parse_points(points_str)?;

        let stroke_width = if fields.len() > 2 {
            fields[2].parse::<f64>().unwrap_or(1.0)
        } else {
            1.0
        };

        let fill = fields.len() > 7 && fields[7] == "1";

        Ok(EePolygon {
            points,
            stroke_width,
            fill,
        })
    }

    fn parse_pt_path(fields: &[&str]) -> Result<EePolygon> {
        use crate::easyeda::svg_parser::{parse_svg_path, SvgCommand};

        if fields.len() < 2 {
            return Err(EasyedaError::InvalidData("Invalid path data".to_string()).into());
        }

        let svg_path = fields[1];
        let commands = parse_svg_path(svg_path)?;

        let mut points = Vec::new();
        let mut has_close_path = false;

        for cmd in commands {
            match cmd {
                SvgCommand::MoveTo { x, y } => {
                    points.push((x, y));
                }
                SvgCommand::LineTo { x, y } => {
                    points.push((x, y));
                }
                SvgCommand::Arc { x, y, .. } => {
                    // For paths, just add the end point
                    points.push((x, y));
                }
                SvgCommand::ClosePath => {
                    has_close_path = true;
                }
            }
        }

        // If path has ClosePath command (Z), close the polygon by adding the first point again
        if has_close_path && !points.is_empty() {
            let first_point = points[0];
            points.push(first_point);
        }

        let stroke_width = if fields.len() > 3 {
            fields[3].parse::<f64>().unwrap_or(1.0)
        } else {
            1.0
        };

        // If path has ClosePath command (Z), it should be filled
        // This is typical for shapes like triangles in diode symbols
        let fill = has_close_path;

        Ok(EePolygon {
            points,
            stroke_width,
            fill,
        })
    }

    fn parse_text(fields: &[&str]) -> Result<EeText> {
        if fields.len() < 5 {
            return Err(EasyedaError::InvalidData("Invalid text data".to_string()).into());
        }

        let x = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid text X".to_string()))?;
        let y = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid text Y".to_string()))?;
        let rotation = fields[3].parse::<i32>().unwrap_or(0);
        let text = fields[4].to_string();

        let font_size = if fields.len() > 8 {
            fields[8].parse::<f64>().unwrap_or(12.0)
        } else {
            12.0
        };

        Ok(EeText {
            text,
            x,
            y,
            rotation,
            font_size,
            stroke_width: 0.0,
            layer_id: 0,
        })
    }

    fn parse_path(fields: &[&str]) -> Result<EePath> {
        if fields.len() < 4 {
            return Err(EasyedaError::InvalidData("Invalid path data".to_string()).into());
        }

        // PATH~width~layer~path_data~gId~locked
        let stroke_width = fields[1].parse::<f64>().unwrap_or(1.0);
        let path_data = fields[3].to_string();

        // Check if path is filled (usually paths are not filled in symbols)
        let fill = false;

        Ok(EePath {
            path_data,
            stroke_width,
            fill,
        })
    }

    fn parse_points(points_str: &str) -> Result<Vec<(f64, f64)>> {
        let coords: Vec<&str> = points_str.split_whitespace().collect();
        let mut points = Vec::new();

        for i in (0..coords.len()).step_by(2) {
            if i + 1 < coords.len() {
                let x = coords[i].parse::<f64>()
                    .map_err(|_| EasyedaError::InvalidData("Invalid point X".to_string()))?;
                let y = coords[i + 1].parse::<f64>()
                    .map_err(|_| EasyedaError::InvalidData("Invalid point Y".to_string()))?;
                points.push((x, y));
            }
        }

        Ok(points)
    }
}

pub struct FootprintImporter;

impl FootprintImporter {
    pub fn parse(shape_data: &[String]) -> Result<EeFootprint> {
        let mut footprint = EeFootprint {
            name: String::new(),
            pads: Vec::new(),
            tracks: Vec::new(),
            circles: Vec::new(),
            arcs: Vec::new(),
            rectangles: Vec::new(),
            texts: Vec::new(),
            holes: Vec::new(),
            vias: Vec::new(),
            svg_nodes: Vec::new(),
        };

        for shape in shape_data {
            let fields: Vec<&str> = shape.split('~').collect();
            if fields.is_empty() {
                continue;
            }

            let designator = fields[0];

            match designator {
                "PAD" => {
                    if let Ok(pad) = Self::parse_pad(&fields) {
                        footprint.pads.push(pad);
                    }
                }
                "TRACK" => {
                    if let Ok(track) = Self::parse_track(&fields) {
                        footprint.tracks.push(track);
                    }
                }
                "CIRCLE" => {
                    if let Ok(circle) = Self::parse_circle(&fields) {
                        footprint.circles.push(circle);
                    }
                }
                "ARC" => {
                    if let Ok(arc) = Self::parse_arc(&fields) {
                        footprint.arcs.push(arc);
                    }
                }
                "RECT" => {
                    if let Ok(rect) = Self::parse_rectangle(&fields) {
                        footprint.rectangles.push(rect);
                    }
                }
                "TEXT" => {
                    if let Ok(text) = Self::parse_text(&fields) {
                        footprint.texts.push(text);
                    }
                }
                "HOLE" => {
                    if let Ok(hole) = Self::parse_hole(&fields) {
                        footprint.holes.push(hole);
                    }
                }
                "VIA" => {
                    if let Ok(via) = Self::parse_via(&fields) {
                        footprint.vias.push(via);
                    }
                }
                "SVGNODE" => {
                    if let Ok(svg_node) = Self::parse_svg_node(&fields) {
                        footprint.svg_nodes.push(svg_node);
                    }
                }
                _ => {}
            }
        }

        Ok(footprint)
    }

    fn parse_pad(fields: &[&str]) -> Result<EePad> {
        if fields.len() < 9 {
            return Err(EasyedaError::InvalidData("Invalid pad data".to_string()).into());
        }

        // PAD~shape~center_x~center_y~width~height~layer_id~net~number~hole_radius~points~rotation~...
        // Actual field mapping based on real data:
        // [0]=PAD, [1]=shape, [2]=x, [3]=y, [4]=width, [5]=height, [6]=layer_id, [7]=net, [8]=number, [9]=hole_radius, [10]=points, [11]=rotation
        let shape = fields[1].to_string();
        let x = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid pad X".to_string()))?;
        let y = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid pad Y".to_string()))?;
        let width = fields[4].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid pad width".to_string()))?;
        let height = fields[5].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid pad height".to_string()))?;
        let layer_id = fields[6].parse::<i32>()
            .map_err(|_| EasyedaError::InvalidData("Invalid pad layer_id".to_string()))?;

        // Field 8 is the pad number
        let number = if fields.len() > 8 {
            fields[8].to_string()
        } else {
            String::new()
        };

        // Field 9 is hole_radius
        let hole_radius = if fields.len() > 9 {
            let val = fields[9].parse::<f64>().unwrap_or(0.0);
            if val > 0.0 { Some(val) } else { None }
        } else {
            None
        };

        // Field 10 is points (for polygon pads)
        let points = if fields.len() > 10 {
            fields[10].to_string()
        } else {
            String::new()
        };

        // Field 11 is rotation
        let rotation = if fields.len() > 11 {
            fields[11].parse::<f64>().unwrap_or(0.0)
        } else {
            0.0
        };

        // Field 13 is hole_length (for elliptical drills) - field 12 is id
        let hole_length = if fields.len() > 13 {
            let val = fields[13].parse::<f64>().unwrap_or(0.0);
            if val > 0.0 { Some(val) } else { None }
        } else {
            None
        };

        Ok(EePad {
            number,
            shape,
            x,
            y,
            width,
            height,
            rotation,
            hole_radius,
            hole_length,
            points,
            layer_id,
        })
    }

    fn parse_track(fields: &[&str]) -> Result<EeTrack> {
        if fields.len() < 5 {
            return Err(EasyedaError::InvalidData("Invalid track data".to_string()).into());
        }

        // TRACK~stroke_width~layer_id~net~points~id~locked
        let stroke_width = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid track width".to_string()))?;
        let layer_id = fields[2].parse::<i32>()
            .map_err(|_| EasyedaError::InvalidData("Invalid track layer_id".to_string()))?;
        let net = fields[3].to_string();
        let points = fields[4].to_string();

        Ok(EeTrack {
            stroke_width,
            layer_id,
            net,
            points,
        })
    }

    fn parse_circle(fields: &[&str]) -> Result<EeCircle> {
        if fields.len() < 5 {
            return Err(EasyedaError::InvalidData("Invalid circle data".to_string()).into());
        }

        // CIRCLE~cx~cy~radius~stroke_width~layer_id~id~is_locked
        let cx = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid circle CX".to_string()))?;
        let cy = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid circle CY".to_string()))?;
        let radius = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid circle radius".to_string()))?;
        let stroke_width = if fields.len() > 4 {
            fields[4].parse::<f64>().unwrap_or(1.0)
        } else {
            1.0
        };
        let layer_id = if fields.len() > 5 {
            fields[5].parse::<i32>().unwrap_or(3)
        } else {
            3
        };

        Ok(EeCircle {
            cx,
            cy,
            radius,
            stroke_width,
            fill: false,
            layer_id,
        })
    }

    fn parse_arc(fields: &[&str]) -> Result<EeFootprintArc> {
        if fields.len() < 5 {
            return Err(EasyedaError::InvalidData("Invalid arc data".to_string()).into());
        }

        // ARC~stroke_width~layer_id~net~path~helper_dots~id~is_locked
        let stroke_width = fields[1].parse::<f64>().unwrap_or(1.0);
        let layer_id = fields[2].parse::<i32>().unwrap_or(3);
        let path = fields[4].to_string();

        Ok(EeFootprintArc {
            stroke_width,
            layer_id,
            path,
        })
    }

    fn parse_rectangle(fields: &[&str]) -> Result<EeRectangle> {
        if fields.len() < 6 {
            return Err(EasyedaError::InvalidData("Invalid rectangle data".to_string()).into());
        }

        // RECT~x~y~width~height~stroke_width~id~layer_id~is_locked
        let x = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid rectangle X".to_string()))?;
        let y = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid rectangle Y".to_string()))?;
        let width = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid rectangle width".to_string()))?;
        let height = fields[4].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid rectangle height".to_string()))?;
        let stroke_width = if fields.len() > 5 {
            fields[5].parse::<f64>().unwrap_or(1.0)
        } else {
            1.0
        };
        let layer_id = if fields.len() > 7 {
            fields[7].parse::<i32>().unwrap_or(3)
        } else {
            3
        };

        Ok(EeRectangle {
            x,
            y,
            width,
            height,
            stroke_width,
            fill: false,
            layer_id,
        })
    }

    fn parse_text(fields: &[&str]) -> Result<EeText> {
        if fields.len() < 11 {
            return Err(EasyedaError::InvalidData("Invalid text data".to_string()).into());
        }

        // TEXT~type~center_x~center_y~stroke_width~rotation~mirror~layer_id~net~font_size~text~...
        let x = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid text X".to_string()))?;
        let y = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid text Y".to_string()))?;
        let stroke_width = fields[4].parse::<f64>().unwrap_or(0.0);
        let rotation = fields[5].parse::<i32>().unwrap_or(0);
        let layer_id = fields[7].parse::<i32>().unwrap_or(3);
        let font_size = fields[9].parse::<f64>().unwrap_or(12.0);
        let text = fields[10].to_string();

        Ok(EeText {
            text,
            x,
            y,
            rotation,
            font_size,
            stroke_width,
            layer_id,
        })
    }

    fn parse_hole(fields: &[&str]) -> Result<EeHole> {
        if fields.len() < 4 {
            return Err(EasyedaError::InvalidData("Invalid hole data".to_string()).into());
        }

        let x = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid hole X".to_string()))?;
        let y = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid hole Y".to_string()))?;
        let radius = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid hole radius".to_string()))?;

        Ok(EeHole {
            x,
            y,
            radius,
        })
    }

    fn parse_via(fields: &[&str]) -> Result<EeVia> {
        if fields.len() < 6 {
            return Err(EasyedaError::InvalidData("Invalid via data".to_string()).into());
        }

        // VIA~x~y~diameter~net~radius~id~locked
        let x = fields[1].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid via X".to_string()))?;
        let y = fields[2].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid via Y".to_string()))?;
        let diameter = fields[3].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid via diameter".to_string()))?;
        let net = fields[4].to_string();
        let radius = fields[5].parse::<f64>()
            .map_err(|_| EasyedaError::InvalidData("Invalid via radius".to_string()))?;

        Ok(EeVia {
            x,
            y,
            diameter,
            net,
            radius,
        })
    }

    fn parse_svg_node(fields: &[&str]) -> Result<EeSvgNode> {
        if fields.len() < 3 {
            return Err(EasyedaError::InvalidData("Invalid SVG node data".to_string()).into());
        }

        let path = fields[2].to_string();
        let layer = fields[1].to_string();

        Ok(EeSvgNode {
            path,
            stroke_width: 1.0,
            layer,
        })
    }
}