xdl-matlab 0.1.1

Extended Data Language (XDL) - Rust implementation
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
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
//! MATLAB to XDL Transpiler
//!
//! Converts MATLAB syntax to XDL-compatible code

use crate::function_map::get_xdl_function;
use crate::lexer::{Lexer, Token, TokenKind};

pub struct Transpiler {
    tokens: Vec<Token>,
    position: usize,
    output: String,
    indent_level: usize,
    // Subplot state for tiledlayout
    subplot_rows: usize,
    subplot_cols: usize,
    current_tile: usize,
}

impl Transpiler {
    pub fn new(tokens: Vec<Token>) -> Self {
        Self {
            tokens,
            position: 0,
            output: String::new(),
            indent_level: 0,
            subplot_rows: 1,
            subplot_cols: 1,
            current_tile: 0,
        }
    }

    fn current_token(&self) -> Token {
        self.tokens.get(self.position).cloned().unwrap_or(Token {
            kind: TokenKind::EOF,
            lexeme: String::new(),
            line: 0,
            column: 0,
        })
    }

    fn advance(&mut self) {
        if self.position < self.tokens.len() {
            self.position += 1;
        }
    }

    fn emit(&mut self, s: &str) {
        self.output.push_str(s);
    }

    fn emit_line(&mut self, s: &str) {
        self.emit(&"  ".repeat(self.indent_level));
        self.emit(s);
        self.emit("\n");
    }

    pub fn transpile(&mut self) -> Result<String, String> {
        while self.position < self.tokens.len() {
            let token = self.current_token();

            match &token.kind {
                TokenKind::Comment(c) => {
                    self.emit_line(&format!("; {}", c));
                    self.advance();
                }
                TokenKind::Function => {
                    self.transpile_function()?;
                }
                TokenKind::For => {
                    self.transpile_for_loop()?;
                }
                TokenKind::While => {
                    self.transpile_while_loop()?;
                }
                TokenKind::If => {
                    self.transpile_if_statement()?;
                }
                TokenKind::Switch => {
                    self.transpile_switch_statement()?;
                }
                TokenKind::Try => {
                    self.transpile_try_catch()?;
                }
                TokenKind::Break => {
                    self.emit_line("BREAK");
                    self.advance();
                    // Skip optional semicolon/newline
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Semicolon | TokenKind::Newline
                    ) {
                        self.advance();
                    }
                }
                TokenKind::Continue => {
                    self.emit_line("CONTINUE");
                    self.advance();
                    // Skip optional semicolon/newline
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Semicolon | TokenKind::Newline
                    ) {
                        self.advance();
                    }
                }
                TokenKind::Return => {
                    self.emit_line("RETURN");
                    self.advance();
                    // Skip optional semicolon/newline
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Semicolon | TokenKind::Newline
                    ) {
                        self.advance();
                    }
                }
                TokenKind::Identifier(_) | TokenKind::LeftBracket => {
                    self.transpile_statement()?;
                }
                TokenKind::Newline | TokenKind::Semicolon => {
                    self.advance();
                }
                TokenKind::EOF => break,
                _ => {
                    self.advance();
                }
            }
        }

        Ok(self.output.clone())
    }

    fn transpile_function(&mut self) -> Result<(), String> {
        self.advance(); // skip 'function'

        // Parse output variables [out1, out2, ...] = funcname(...)
        // or just funcname(...)
        let mut outputs = Vec::new();

        // Check for output variables
        if matches!(self.current_token().kind, TokenKind::LeftBracket) {
            self.advance(); // skip '['
            while !matches!(self.current_token().kind, TokenKind::RightBracket) {
                if let TokenKind::Identifier(name) = &self.current_token().kind {
                    outputs.push(name.clone());
                    self.advance();
                }
                if matches!(self.current_token().kind, TokenKind::Comma) {
                    self.advance();
                }
            }
            self.advance(); // skip ']'

            // Expect '='
            if matches!(self.current_token().kind, TokenKind::Assign) {
                self.advance();
            }
        } else if let TokenKind::Identifier(name) = &self.current_token().kind {
            // Check if next is '=' (single output)
            let next_pos = self.position + 1;
            if next_pos < self.tokens.len()
                && matches!(self.tokens[next_pos].kind, TokenKind::Assign)
            {
                outputs.push(name.clone());
                self.advance(); // skip output name
                self.advance(); // skip '='
            }
        }

        // Get function name
        let func_name = if let TokenKind::Identifier(name) = &self.current_token().kind {
            name.clone()
        } else {
            return Err("Expected function name".to_string());
        };
        self.advance();

        // Get parameters
        let mut params = Vec::new();
        if matches!(self.current_token().kind, TokenKind::LeftParen) {
            self.advance(); // skip '('
            while !matches!(self.current_token().kind, TokenKind::RightParen) {
                if let TokenKind::Identifier(name) = &self.current_token().kind {
                    params.push(name.clone());
                    self.advance();
                }
                if matches!(self.current_token().kind, TokenKind::Comma) {
                    self.advance();
                }
            }
            self.advance(); // skip ')'
        }

        // Emit XDL function
        self.emit_line(&format!("FUNCTION {}", func_name));
        self.indent_level += 1;

        // Skip to end
        let mut depth = 1;
        while depth > 0 && self.position < self.tokens.len() {
            match &self.current_token().kind {
                TokenKind::End => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                TokenKind::Function
                | TokenKind::For
                | TokenKind::While
                | TokenKind::If
                | TokenKind::Switch
                | TokenKind::Try => {
                    depth += 1;
                }
                _ => {}
            }

            if depth > 0 {
                self.transpile_statement()?;
            }
        }

        self.indent_level -= 1;
        self.emit_line("END");

        if matches!(self.current_token().kind, TokenKind::End) {
            self.advance();
        }

        Ok(())
    }

    fn transpile_for_loop(&mut self) -> Result<(), String> {
        self.advance(); // skip 'for'

        // Get loop variable
        let var_name = if let TokenKind::Identifier(name) = &self.current_token().kind {
            name.clone()
        } else {
            return Err("Expected loop variable".to_string());
        };
        self.advance();

        // Expect '='
        if !matches!(self.current_token().kind, TokenKind::Assign) {
            return Err("Expected '=' in for loop".to_string());
        }
        self.advance();

        // Get range (start:end or start:step:end or array)
        let range_expr = self.collect_expression_until_newline();

        // Check if this is a simple range expression with colons
        let xdl_range = if range_expr.contains(':') && !range_expr.contains('(') {
            // Simple range: try to convert
            match self.convert_range(&range_expr) {
                Ok(r) => r,
                Err(_) => {
                    // Complex range expression, use convert_range_to_findgen
                    self.convert_range_to_findgen(&range_expr)
                }
            }
        } else {
            // Not a simple range, output as-is
            range_expr
        };

        self.emit_line(&format!("for {} = {}", var_name, xdl_range));
        self.indent_level += 1;

        // Process body until 'end'
        while !matches!(self.current_token().kind, TokenKind::End | TokenKind::EOF) {
            self.transpile_statement()?;
        }

        self.indent_level -= 1;
        self.emit_line("endfor");

        if matches!(self.current_token().kind, TokenKind::End) {
            self.advance();
        }

        Ok(())
    }

    fn transpile_while_loop(&mut self) -> Result<(), String> {
        self.advance(); // skip 'while'

        let condition = self.collect_expression_until_newline();

        self.emit_line(&format!("while {}", condition));
        self.indent_level += 1;

        while !matches!(self.current_token().kind, TokenKind::End | TokenKind::EOF) {
            self.transpile_statement()?;
        }

        self.indent_level -= 1;
        self.emit_line("endwhile");

        if matches!(self.current_token().kind, TokenKind::End) {
            self.advance();
        }

        Ok(())
    }

    fn transpile_if_statement(&mut self) -> Result<(), String> {
        self.advance(); // skip 'if'

        let condition = self.collect_expression_until_newline();

        self.emit_line(&format!("if {} then", condition));
        self.indent_level += 1;

        while !matches!(
            self.current_token().kind,
            TokenKind::End | TokenKind::Else | TokenKind::Elseif | TokenKind::EOF
        ) {
            self.transpile_statement()?;
        }

        if matches!(self.current_token().kind, TokenKind::Else) {
            self.indent_level -= 1;
            self.emit_line("else");
            self.indent_level += 1;
            self.advance();

            while !matches!(self.current_token().kind, TokenKind::End | TokenKind::EOF) {
                self.transpile_statement()?;
            }
        }

        self.indent_level -= 1;
        self.emit_line("endif");

        if matches!(self.current_token().kind, TokenKind::End) {
            self.advance();
        }

        Ok(())
    }

    fn transpile_switch_statement(&mut self) -> Result<(), String> {
        self.advance(); // skip 'switch'

        // Get switch expression
        let switch_expr = self.collect_expression_until_newline();

        self.emit_line(&format!("CASE {} OF", switch_expr));
        self.indent_level += 1;

        // Process case statements
        while !matches!(self.current_token().kind, TokenKind::End | TokenKind::EOF) {
            match &self.current_token().kind {
                TokenKind::Case => {
                    self.advance(); // skip 'case'

                    // Collect case value(s)
                    let mut case_values = Vec::new();

                    // Check if it's a cell array {val1, val2, ...}
                    if matches!(self.current_token().kind, TokenKind::LeftBrace) {
                        self.advance(); // skip '{'
                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightBrace | TokenKind::EOF
                        ) {
                            let mut value = String::new();
                            while !matches!(
                                self.current_token().kind,
                                TokenKind::Comma
                                    | TokenKind::RightBrace
                                    | TokenKind::Newline
                                    | TokenKind::EOF
                            ) {
                                value.push_str(&self.current_token().lexeme);
                                self.advance();
                            }
                            if !value.trim().is_empty() {
                                case_values.push(value.trim().to_string());
                            }
                            if matches!(self.current_token().kind, TokenKind::Comma) {
                                self.advance();
                            }
                        }
                        if matches!(self.current_token().kind, TokenKind::RightBrace) {
                            self.advance();
                        }
                    } else {
                        // Single case value
                        let mut value = String::new();
                        while !matches!(
                            self.current_token().kind,
                            TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                        ) {
                            value.push_str(&self.current_token().lexeme);
                            self.advance();
                        }
                        case_values.push(value.trim().to_string());
                    }

                    // Skip newline after case
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon
                    ) {
                        self.advance();
                    }

                    // Emit case values (XDL supports multiple values with commas)
                    for val in case_values.iter() {
                        self.emit_line(&format!("{}: BEGIN", val));
                    }
                    self.indent_level += 1;

                    // Process statements until next case/otherwise/end
                    while !matches!(
                        self.current_token().kind,
                        TokenKind::Case | TokenKind::Otherwise | TokenKind::End | TokenKind::EOF
                    ) {
                        self.transpile_statement()?;
                    }

                    self.indent_level -= 1;
                    self.emit_line("END");
                }
                TokenKind::Otherwise => {
                    self.advance(); // skip 'otherwise'

                    // Skip newline
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon
                    ) {
                        self.advance();
                    }

                    self.emit_line("ELSE: BEGIN");
                    self.indent_level += 1;

                    // Process statements until end
                    while !matches!(self.current_token().kind, TokenKind::End | TokenKind::EOF) {
                        self.transpile_statement()?;
                    }

                    self.indent_level -= 1;
                    self.emit_line("END");
                }
                _ => {
                    self.advance();
                }
            }
        }

        self.indent_level -= 1;
        self.emit_line("ENDCASE");

        if matches!(self.current_token().kind, TokenKind::End) {
            self.advance();
        }

        Ok(())
    }

    fn transpile_try_catch(&mut self) -> Result<(), String> {
        self.advance(); // skip 'try'

        // XDL doesn't have direct try/catch, so we'll emit comments and the code
        self.emit_line("; TRY block (error handling not directly supported in XDL)");
        self.emit_line("BEGIN");
        self.indent_level += 1;

        // Process try block
        while !matches!(
            self.current_token().kind,
            TokenKind::Catch | TokenKind::End | TokenKind::EOF
        ) {
            self.transpile_statement()?;
        }

        self.indent_level -= 1;
        self.emit_line("END");

        // Handle catch block if present
        if matches!(self.current_token().kind, TokenKind::Catch) {
            self.advance(); // skip 'catch'

            // Skip optional error variable
            if let TokenKind::Identifier(_err_var) = &self.current_token().kind {
                self.advance();
            }

            // Skip newline
            if matches!(
                self.current_token().kind,
                TokenKind::Newline | TokenKind::Semicolon
            ) {
                self.advance();
            }

            self.emit_line("; CATCH block (error handling not directly supported in XDL)");
            self.emit_line("BEGIN");
            self.indent_level += 1;

            // Process catch block
            while !matches!(self.current_token().kind, TokenKind::End | TokenKind::EOF) {
                self.transpile_statement()?;
            }

            self.indent_level -= 1;
            self.emit_line("END");
        }

        if matches!(self.current_token().kind, TokenKind::End) {
            self.advance();
        }

        Ok(())
    }

    fn transpile_statement(&mut self) -> Result<(), String> {
        // Handle control flow statements that might appear nested
        match &self.current_token().kind {
            TokenKind::For => return self.transpile_for_loop(),
            TokenKind::While => return self.transpile_while_loop(),
            TokenKind::If => return self.transpile_if_statement(),
            TokenKind::Switch => return self.transpile_switch_statement(),
            TokenKind::Try => return self.transpile_try_catch(),
            TokenKind::Break => {
                self.emit_line("BREAK");
                self.advance();
                if matches!(
                    self.current_token().kind,
                    TokenKind::Semicolon | TokenKind::Newline
                ) {
                    self.advance();
                }
                return Ok(());
            }
            TokenKind::Continue => {
                self.emit_line("CONTINUE");
                self.advance();
                if matches!(
                    self.current_token().kind,
                    TokenKind::Semicolon | TokenKind::Newline
                ) {
                    self.advance();
                }
                return Ok(());
            }
            TokenKind::Return => {
                self.emit_line("RETURN");
                self.advance();
                if matches!(
                    self.current_token().kind,
                    TokenKind::Semicolon | TokenKind::Newline
                ) {
                    self.advance();
                }
                return Ok(());
            }
            _ => {}
        }

        // Check if this is a graphics command that should be handled specially
        if let TokenKind::Identifier(name) = &self.current_token().kind {
            match name.as_str() {
                "figure" | "clf" | "close" => {
                    // Ignore figure management commands
                    self.advance();
                    // Skip any arguments
                    while !matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                    ) {
                        self.advance();
                    }
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon
                    ) {
                        self.advance();
                    }
                    self.emit_line("; (figure management command ignored)");
                    return Ok(());
                }
                "hold" => {
                    // Ignore hold on/off commands
                    self.advance();
                    while !matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                    ) {
                        self.advance();
                    }
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon
                    ) {
                        self.advance();
                    }
                    self.emit_line("; (hold command ignored - XDL doesn't support hold on/off)");
                    return Ok(());
                }
                "surf" | "mesh" | "surfc" | "meshc" => {
                    // Convert MATLAB 3D surface plots to XDL SURFACE/CONTOUR
                    let func_name = name.clone();
                    self.advance(); // skip function name

                    if matches!(self.current_token().kind, TokenKind::LeftParen) {
                        self.advance(); // skip '('

                        // Collect arguments: surf(X, Y, Z) or surf(Z)
                        let mut args = Vec::new();
                        let mut current_arg = String::new();
                        let mut paren_depth = 0;

                        while !matches!(self.current_token().kind, TokenKind::EOF) {
                            if matches!(self.current_token().kind, TokenKind::LeftParen) {
                                paren_depth += 1;
                                current_arg.push_str(&self.current_token().lexeme);
                            } else if matches!(self.current_token().kind, TokenKind::RightParen) {
                                if paren_depth > 0 {
                                    paren_depth -= 1;
                                    current_arg.push_str(&self.current_token().lexeme);
                                } else {
                                    // End of function call
                                    if !current_arg.trim().is_empty() {
                                        args.push(current_arg.trim().to_string());
                                    }
                                    break;
                                }
                            } else if matches!(self.current_token().kind, TokenKind::Comma)
                                && paren_depth == 0
                            {
                                if !current_arg.trim().is_empty() {
                                    args.push(current_arg.trim().to_string());
                                }
                                current_arg.clear();
                            } else {
                                current_arg.push_str(&self.current_token().lexeme);
                            }
                            self.advance();
                        }

                        // Convert to XDL SURFACE command
                        // surf(X, Y, Z) -> SURFACE, Z
                        // surf(Z) -> SURFACE, Z
                        let z_data = if args.len() >= 3 {
                            &args[2] // surf(X, Y, Z) - use Z
                        } else if args.len() == 1 {
                            &args[0] // surf(Z) - use Z
                        } else {
                            // Fallback
                            "data"
                        };

                        self.emit_line(&format!("; {} - 3D surface plotting", func_name));
                        self.emit_line(&format!("SURFACE, {}", z_data));

                        // Skip to end of statement
                        while !matches!(
                            self.current_token().kind,
                            TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                        ) {
                            self.advance();
                        }
                        if matches!(
                            self.current_token().kind,
                            TokenKind::Newline | TokenKind::Semicolon
                        ) {
                            self.advance();
                        }

                        return Ok(());
                    }

                    // If we couldn't parse it, emit comment
                    self.emit_line(&format!("; {} - Could not convert to XDL", func_name));
                    return Ok(());
                }
                "tiledlayout" => {
                    // tiledlayout(rows, cols) - set up subplot grid
                    self.advance(); // skip 'tiledlayout'
                    if matches!(self.current_token().kind, TokenKind::LeftParen) {
                        self.advance(); // skip '('

                        // Parse rows and cols
                        if let TokenKind::Number(rows) = &self.current_token().kind {
                            self.subplot_rows = *rows as usize;
                            self.advance();
                        }
                        if matches!(self.current_token().kind, TokenKind::Comma) {
                            self.advance();
                        }
                        if let TokenKind::Number(cols) = &self.current_token().kind {
                            self.subplot_cols = *cols as usize;
                            self.advance();
                        }
                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance();
                        }
                    }

                    while !matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                    ) {
                        self.advance();
                    }
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon
                    ) {
                        self.advance();
                    }

                    self.current_tile = 0; // Reset tile counter
                    self.emit_line(&format!(
                        "; tiledlayout({}, {}) - creating {} subplots",
                        self.subplot_rows,
                        self.subplot_cols,
                        self.subplot_rows * self.subplot_cols
                    ));
                    return Ok(());
                }
                _ => {}
            }
        }

        // Check for "ax = nexttile" pattern before normal statement processing
        if let TokenKind::Identifier(_var_name) = &self.current_token().kind {
            let next_pos = self.position + 1;
            if next_pos < self.tokens.len()
                && matches!(self.tokens[next_pos].kind, TokenKind::Assign)
            {
                let after_assign = self.position + 2;
                if after_assign < self.tokens.len() {
                    if let TokenKind::Identifier(func_name) = &self.tokens[after_assign].kind {
                        if func_name == "nexttile" {
                            // This is "ax = nexttile", handle specially
                            self.current_tile += 1;
                            // Skip past the assignment
                            self.advance(); // skip variable name
                            self.advance(); // skip '='
                            self.advance(); // skip 'nexttile'

                            // Skip any remaining tokens on this line
                            while !matches!(
                                self.current_token().kind,
                                TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                            ) {
                                self.advance();
                            }
                            if matches!(
                                self.current_token().kind,
                                TokenKind::Newline | TokenKind::Semicolon
                            ) {
                                self.advance();
                            }

                            self.emit_line(&format!(
                                "; ax = nexttile - now plotting to tile {}",
                                self.current_tile
                            ));
                            return Ok(());
                        }
                    }
                }
            }
        }

        // Check if statement starts with nexttile
        if let TokenKind::Identifier(name) = &self.current_token().kind {
            if name == "nexttile" {
                // nexttile or ax = nexttile - move to next tile
                self.current_tile += 1;
                self.advance();
                while !matches!(
                    self.current_token().kind,
                    TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                ) {
                    self.advance();
                }
                if matches!(
                    self.current_token().kind,
                    TokenKind::Newline | TokenKind::Semicolon
                ) {
                    self.advance();
                }
                self.emit_line(&format!(
                    "; nexttile - now plotting to tile {}",
                    self.current_tile
                ));
                return Ok(());
            }

            match name.as_str() {
                "comet3" | "comet" | "plot3" => {
                    // Map 3D plot commands to PLOT3D with tile-specific filename
                    self.advance(); // skip command name

                    // Skip axis handle if present: comet3(ax, ...)
                    if matches!(self.current_token().kind, TokenKind::LeftParen) {
                        self.advance(); // skip '('

                        // Check if first arg looks like an axis handle
                        if let TokenKind::Identifier(id) = &self.current_token().kind {
                            if id.starts_with("ax") {
                                self.advance(); // skip axis handle
                                if matches!(self.current_token().kind, TokenKind::Comma) {
                                    self.advance(); // skip comma
                                }
                            }
                        }

                        // Collect remaining arguments (x, y, z or x, y)
                        let mut args = Vec::new();
                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) {
                            if let TokenKind::Identifier(arg) = &self.current_token().kind {
                                args.push(arg.clone());
                            }
                            self.advance();
                            if matches!(self.current_token().kind, TokenKind::Comma) {
                                self.advance();
                            }
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance();
                        }

                        // Generate PLOT3D command with tile-specific filename
                        let filename = if self.current_tile > 0 {
                            format!("'tile{}_plot.png'", self.current_tile)
                        } else {
                            "'xdl_plot.png'".to_string()
                        };

                        if args.len() >= 3 {
                            self.emit_line(&format!(
                                "PLOT3D, {}, {}, {}, filename={}",
                                args[0], args[1], args[2], filename
                            ));
                        } else if args.len() == 2 {
                            self.emit_line(&format!(
                                "PLOT, {}, {}, filename={}",
                                args[0], args[1], filename
                            ));
                        }
                    }

                    while !matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                    ) {
                        self.advance();
                    }
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon
                    ) {
                        self.advance();
                    }
                    return Ok(());
                }
                "xlabel" | "ylabel" | "title" | "legend" | "grid" | "zlabel" => {
                    // These should be converted to PLOT keywords, but for now ignore
                    let cmd_name = name.clone();
                    self.advance();
                    while !matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                    ) {
                        self.advance();
                    }
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon
                    ) {
                        self.advance();
                    }
                    self.emit_line(&format!(
                        "; ({} command - use PLOT keywords: title=, xtitle=, ytitle=)",
                        cmd_name
                    ));
                    return Ok(());
                }
                "axis" => {
                    // axis equal, axis([xmin xmax ymin ymax]), etc. - ignore for now
                    self.advance();
                    while !matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                    ) {
                        self.advance();
                    }
                    if matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon
                    ) {
                        self.advance();
                    }
                    self.emit_line("; (axis command - XDL uses automatic axis scaling)");
                    return Ok(());
                }
                _ => {}
            }
        }

        // Check for meshgrid pattern: [X, Y] = meshgrid(...)
        if matches!(self.current_token().kind, TokenKind::LeftBracket) {
            // Look ahead to see if this is [id, id] = meshgrid(...)
            let saved_pos = self.position;
            let mut is_meshgrid = false;
            let mut output_vars = Vec::new();

            self.advance(); // skip '['
                            // Collect output variable names
            while !matches!(
                self.current_token().kind,
                TokenKind::RightBracket | TokenKind::EOF
            ) {
                if let TokenKind::Identifier(name) = &self.current_token().kind {
                    output_vars.push(name.clone());
                }
                self.advance();
            }
            if matches!(self.current_token().kind, TokenKind::RightBracket) {
                self.advance(); // skip ']'
            }
            if matches!(self.current_token().kind, TokenKind::Assign) {
                self.advance(); // skip '='
                if let TokenKind::Identifier(fname) = &self.current_token().kind {
                    if fname == "meshgrid" {
                        is_meshgrid = true;
                    }
                }
            }

            if is_meshgrid && output_vars.len() == 2 {
                // Generate loop-based meshgrid code
                self.advance(); // skip 'meshgrid'
                if matches!(self.current_token().kind, TokenKind::LeftParen) {
                    self.advance(); // skip '('

                    // Collect the argument
                    let mut arg = String::new();
                    let mut paren_depth = 0;
                    while !matches!(self.current_token().kind, TokenKind::EOF) {
                        if matches!(self.current_token().kind, TokenKind::LeftParen) {
                            paren_depth += 1;
                            arg.push('(');
                        } else if matches!(self.current_token().kind, TokenKind::RightParen) {
                            if paren_depth > 0 {
                                paren_depth -= 1;
                                arg.push(')');
                            } else {
                                break;
                            }
                        } else {
                            arg.push_str(&self.current_token().lexeme);
                        }
                        self.advance();
                    }

                    // Skip to end of statement
                    while !matches!(
                        self.current_token().kind,
                        TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
                    ) {
                        self.advance();
                    }

                    // Generate XDL code
                    let x_var = &output_vars[0];
                    let y_var = &output_vars[1];

                    // Convert range expression to FINDGEN if it contains ':'
                    let converted_arg = if arg.trim().contains(':') {
                        self.convert_range_to_findgen(arg.trim())
                    } else {
                        arg.trim().to_string()
                    };

                    self.emit_line("; meshgrid converted to XDL loops");
                    self.emit_line(&format!("x_vec = {}", converted_arg));
                    self.emit_line(&format!("y_vec = {}", converted_arg));
                    self.emit_line("nx = N_ELEMENTS(x_vec)");
                    self.emit_line("ny = N_ELEMENTS(y_vec)");
                    self.emit_line(&format!("{} = FLTARR(nx, ny)", x_var));
                    self.emit_line(&format!("{} = FLTARR(nx, ny)", y_var));
                    self.emit_line("for i = 0, nx - 1 do begin");
                    self.indent_level += 1;
                    self.emit_line("for j = 0, ny - 1 do begin");
                    self.indent_level += 1;
                    self.emit_line(&format!("{}[i, j] = x_vec[i]", x_var));
                    self.emit_line(&format!("{}[i, j] = y_vec[j]", y_var));
                    self.indent_level -= 1;
                    self.emit_line("endfor");
                    self.indent_level -= 1;
                    self.emit_line("endfor");

                    return Ok(());
                }
            }

            // Not meshgrid, restore position and process normally
            self.position = saved_pos;
        }

        let expr = self.collect_expression_until_newline();
        if !expr.trim().is_empty() {
            self.emit_line(&expr);
        }
        Ok(())
    }

    fn collect_expression_until_newline(&mut self) -> String {
        let mut expr = String::new();

        loop {
            let token = self.current_token();
            if matches!(
                token.kind,
                TokenKind::Newline | TokenKind::Semicolon | TokenKind::EOF
            ) {
                break;
            }

            match &token.kind {
                TokenKind::LeftBracket => {
                    // Check if this is a multiple output assignment: [X, Y] = func(...)
                    // by looking ahead for identifiers followed by ] =
                    let is_multiple_output = if expr.trim().is_empty() {
                        let mut check_pos = self.position + 1;
                        let mut found_ids = false;
                        let mut found_bracket = false;
                        let mut found_assign = false;

                        // Look ahead to check pattern: [ id , id ... ] =
                        while check_pos < self.tokens.len() && check_pos < self.position + 20 {
                            match &self.tokens[check_pos].kind {
                                TokenKind::Identifier(_) => found_ids = true,
                                TokenKind::RightBracket if found_ids => found_bracket = true,
                                TokenKind::Assign if found_bracket => {
                                    found_assign = true;
                                    break;
                                }
                                TokenKind::Comma => {} // Continue checking
                                _ if !found_bracket => {}
                                _ => break, // Stop if unexpected token after ]
                            }
                            check_pos += 1;
                        }
                        eprintln!("DEBUG: LeftBracket at expr.is_empty()={}, found_ids={}, found_bracket={}, found_assign={}",
                            expr.trim().is_empty(), found_ids, found_bracket, found_assign);
                        found_assign
                    } else {
                        eprintln!("DEBUG: LeftBracket but expr not empty: '{}'", expr.trim());
                        false
                    };

                    if is_multiple_output {
                        // Handle multiple output assignment: [X, Y] = func(...)
                        // Just output the bracket and let normal processing continue
                        eprintln!("DEBUG: Adding opening bracket for multiple output");
                        expr.push('[');
                        self.advance();
                        continue;
                    }

                    // Check if this is an array literal or array indexing
                    // Array literal: appears at start of expression or after = or ,
                    // Array indexing: appears after an identifier
                    let is_array_literal = expr.is_empty()
                        || expr.trim().ends_with('=')
                        || expr.trim().ends_with(',')
                        || expr.trim().ends_with('(');

                    if is_array_literal {
                        // Parse as array literal
                        match self.parse_array_literal() {
                            Ok(array_str) => {
                                expr.push_str(&array_str);
                                continue;
                            }
                            Err(e) => {
                                expr.push_str(&format!("/* array parse error: {} */", e));
                                self.advance();
                                continue;
                            }
                        }
                    } else {
                        // Array indexing - adjust for 0-based
                        expr.push('[');
                        self.advance();

                        // Collect index expression
                        let mut index_expr = String::new();
                        let mut paren_depth = 0;
                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightBracket | TokenKind::EOF
                        ) || paren_depth > 0
                        {
                            if matches!(self.current_token().kind, TokenKind::LeftParen) {
                                paren_depth += 1;
                            } else if matches!(self.current_token().kind, TokenKind::RightParen) {
                                paren_depth -= 1;
                            }
                            index_expr.push_str(&self.current_token().lexeme);
                            self.advance();
                        }

                        // Convert 1-based to 0-based if it's a simple number
                        if let Ok(num) = index_expr.trim().parse::<i32>() {
                            expr.push_str(&format!("{}", num - 1));
                        } else {
                            expr.push_str(&format!("({}) - 1", index_expr));
                        }

                        if matches!(self.current_token().kind, TokenKind::RightBracket) {
                            expr.push(']');
                            self.advance();
                        }
                        continue;
                    }
                }
                TokenKind::Colon => {
                    // Colon operator: could be part of a range expression
                    // If we're building a standalone range (not in array indexing context)
                    // we need to convert to FINDGEN
                    expr.push_str(" : ");
                    self.advance();
                    continue;
                }
                TokenKind::Identifier(name) => {
                    // Map MATLAB constants to XDL system variables
                    // BUT: Don't map single-letter identifiers on LHS of assignment
                    let is_lhs_of_assignment =
                        expr.trim().is_empty() || expr.trim().ends_with('\n');
                    let mapped_name = match name.as_str() {
                        "pi" => "!PI",
                        "e" if !is_lhs_of_assignment => "!E", // Only map 'e' if not on LHS
                        _ => name.as_str(),
                    };

                    // Map MATLAB function to XDL
                    let func_name = if let Some(xdl_func) = get_xdl_function(mapped_name) {
                        xdl_func
                    } else {
                        mapped_name
                    };

                    // Check if this is a standalone procedure call (PRINT, PLOT, etc.)
                    // by looking ahead for parenthesis
                    let next_pos = self.position + 1;
                    let is_procedure_call = next_pos < self.tokens.len()
                        && matches!(self.tokens[next_pos].kind, TokenKind::LeftParen)
                        && expr.trim().is_empty(); // Statement starts with function

                    // Special handling for randn(size(x)) or rand(size(x)) -> RANDOMN(seed, N_ELEMENTS(x))
                    if (mapped_name == "randn" || mapped_name == "rand")
                        && next_pos < self.tokens.len()
                        && matches!(self.tokens[next_pos].kind, TokenKind::LeftParen)
                    {
                        // Both rand and randn map to RANDOMU for now (normal distribution not yet implemented)
                        let xdl_func = "RANDOMU";
                        self.advance(); // skip 'randn'/'rand'
                        self.advance(); // skip '('

                        // Check if argument is size(something)
                        if let TokenKind::Identifier(func) = &self.current_token().kind {
                            if func == "size" {
                                self.advance(); // skip 'size'
                                if matches!(self.current_token().kind, TokenKind::LeftParen) {
                                    self.advance(); // skip '('

                                    // Get the variable name
                                    let mut var_name = String::new();
                                    while !matches!(
                                        self.current_token().kind,
                                        TokenKind::RightParen | TokenKind::EOF
                                    ) {
                                        var_name.push_str(&self.current_token().lexeme);
                                        self.advance();
                                    }

                                    if matches!(self.current_token().kind, TokenKind::RightParen) {
                                        self.advance(); // skip ')' for size
                                    }
                                    if matches!(self.current_token().kind, TokenKind::RightParen) {
                                        self.advance(); // skip ')' for randn/rand
                                    }

                                    // Generate: RANDOMN(seed, N_ELEMENTS(var))
                                    // Use a fixed seed for reproducibility (can be made configurable later)
                                    expr.push_str(&format!(
                                        "{}(1, N_ELEMENTS({}))",
                                        xdl_func,
                                        var_name.trim()
                                    ));
                                    continue;
                                }
                            }
                        }

                        // Fall back to collecting regular arguments
                        let mut args = Vec::new();
                        let mut current_arg = String::new();
                        let mut paren_depth = 0;

                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) || paren_depth > 0
                        {
                            if matches!(self.current_token().kind, TokenKind::LeftParen) {
                                paren_depth += 1;
                                current_arg.push('(');
                            } else if matches!(self.current_token().kind, TokenKind::RightParen) {
                                paren_depth -= 1;
                                if paren_depth >= 0 {
                                    current_arg.push(')');
                                }
                            } else if matches!(self.current_token().kind, TokenKind::Comma)
                                && paren_depth == 0
                            {
                                args.push(current_arg.trim().to_string());
                                current_arg = String::new();
                            } else {
                                current_arg.push_str(&self.current_token().lexeme);
                            }
                            self.advance();
                        }

                        if !current_arg.trim().is_empty() {
                            args.push(current_arg.trim().to_string());
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance(); // skip ')'
                        }

                        // Generate: RANDOMN(seed, n) or RANDOMU(seed, n)
                        if !args.is_empty() {
                            expr.push_str(&format!("{}(1, {})", xdl_func, args.join(", ")));
                        } else {
                            expr.push_str(&format!("{}(1, 1)", xdl_func)); // Default to single random value
                        }
                        continue;
                    }

                    // Special handling for complex(real, imag) - XDL doesn't support complex, use real part only
                    if mapped_name == "complex"
                        && next_pos < self.tokens.len()
                        && matches!(self.tokens[next_pos].kind, TokenKind::LeftParen)
                    {
                        self.advance(); // skip 'complex'
                        self.advance(); // skip '('

                        // Collect arguments: real, imag
                        let mut args = Vec::new();
                        let mut current_arg = String::new();
                        let mut paren_depth = 0;

                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) || paren_depth > 0
                        {
                            if matches!(self.current_token().kind, TokenKind::LeftParen) {
                                paren_depth += 1;
                                current_arg.push('(');
                            } else if matches!(self.current_token().kind, TokenKind::RightParen) {
                                paren_depth -= 1;
                                if paren_depth >= 0 {
                                    current_arg.push(')');
                                }
                            } else if matches!(self.current_token().kind, TokenKind::Comma)
                                && paren_depth == 0
                            {
                                args.push(current_arg.trim().to_string());
                                current_arg = String::new();
                            } else {
                                // Map constants
                                let token_str = match &self.current_token().kind {
                                    TokenKind::Identifier(name) => match name.as_str() {
                                        "pi" => "!PI",
                                        "e" => "!E",
                                        _ => &self.current_token().lexeme,
                                    },
                                    _ => &self.current_token().lexeme,
                                };
                                current_arg.push_str(token_str);
                            }
                            self.advance();
                        }

                        if !current_arg.trim().is_empty() {
                            args.push(current_arg.trim().to_string());
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance(); // skip ')'
                        }

                        // XDL doesn't have a complex constructor, so for exp(complex(0, t)):
                        // we'll convert to just the imaginary part for now (exp(i*t) pattern)
                        // In practice, complex(0, t) means 0 + i*t, so exp(complex(0, t)) = exp(i*t)
                        // = cos(t) + i*sin(t). For real plots, we can just use the real part: cos(t)
                        if args.len() >= 2 {
                            let real_part = &args[0];
                            let imag_part = &args[1];
                            // If real part is 0, this is purely imaginary
                            if real_part.trim() == "0" {
                                // For exp(i*t) pattern, just use i*t directly as the argument
                                // But since XDL has no complex type, we use the imaginary part directly
                                expr.push_str(imag_part);
                            } else {
                                // Use real part for now
                                expr.push_str(real_part);
                            }
                        } else if args.len() == 1 {
                            // Just real part
                            expr.push_str(&args[0]);
                        } else {
                            expr.push_str("/* complex() needs 1-2 args */");
                        }
                        continue;
                    }

                    // Special handling for zeros(n) or zeros(m, n) -> FLTARR(m, n)
                    if mapped_name == "zeros"
                        && next_pos < self.tokens.len()
                        && matches!(self.tokens[next_pos].kind, TokenKind::LeftParen)
                    {
                        self.advance(); // skip 'zeros'
                        self.advance(); // skip '('

                        let mut args = Vec::new();
                        let mut current_arg = String::new();

                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) {
                            if matches!(self.current_token().kind, TokenKind::Comma) {
                                args.push(current_arg.trim().to_string());
                                current_arg = String::new();
                            } else {
                                current_arg.push_str(&self.current_token().lexeme);
                            }
                            self.advance();
                        }

                        if !current_arg.trim().is_empty() {
                            args.push(current_arg.trim().to_string());
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance(); // skip ')'
                        }

                        // Generate FLTARR with appropriate dimensions
                        expr.push_str(&format!("FLTARR({})", args.join(", ")));
                        continue;
                    }

                    // Special handling for ones(n) or ones(m, n) -> FLTARR(m, n) + 1
                    if mapped_name == "ones"
                        && next_pos < self.tokens.len()
                        && matches!(self.tokens[next_pos].kind, TokenKind::LeftParen)
                    {
                        self.advance(); // skip 'ones'
                        self.advance(); // skip '('

                        let mut args = Vec::new();
                        let mut current_arg = String::new();

                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) {
                            if matches!(self.current_token().kind, TokenKind::Comma) {
                                args.push(current_arg.trim().to_string());
                                current_arg = String::new();
                            } else {
                                current_arg.push_str(&self.current_token().lexeme);
                            }
                            self.advance();
                        }

                        if !current_arg.trim().is_empty() {
                            args.push(current_arg.trim().to_string());
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance(); // skip ')'
                        }

                        // Generate FLTARR with appropriate dimensions + 1
                        expr.push_str(&format!("FLTARR({}) + 1", args.join(", ")));
                        continue;
                    }

                    // Special handling for eye(n) -> IDENTITY(n)
                    if mapped_name == "eye"
                        && next_pos < self.tokens.len()
                        && matches!(self.tokens[next_pos].kind, TokenKind::LeftParen)
                    {
                        self.advance(); // skip 'eye'
                        self.advance(); // skip '('

                        let mut args = Vec::new();
                        let mut current_arg = String::new();

                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) {
                            if matches!(self.current_token().kind, TokenKind::Comma) {
                                args.push(current_arg.trim().to_string());
                                current_arg = String::new();
                            } else {
                                current_arg.push_str(&self.current_token().lexeme);
                            }
                            self.advance();
                        }

                        if !current_arg.trim().is_empty() {
                            args.push(current_arg.trim().to_string());
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance(); // skip ')'
                        }

                        // Generate IDENTITY
                        // eye(n) -> IDENTITY(n), eye(m,n) -> use IDENTITY(n) for square matrix
                        if args.len() == 1 {
                            expr.push_str(&format!("IDENTITY({})", args[0]));
                        } else if args.len() >= 2 {
                            // For non-square, we need a custom approach but IDENTITY only works for square
                            expr.push_str(&format!("IDENTITY({})", args[0]));
                        }
                        continue;
                    }

                    // Special handling for linspace(start, end, n) -> FINDGEN(n) * (end-start) / (n-1) + start
                    if mapped_name == "linspace"
                        && next_pos < self.tokens.len()
                        && matches!(self.tokens[next_pos].kind, TokenKind::LeftParen)
                    {
                        self.advance(); // skip 'linspace'
                        self.advance(); // skip '('

                        // Collect arguments: start, end, n
                        let mut args = Vec::new();
                        let mut current_arg = String::new();
                        let mut paren_depth = 0;

                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) || paren_depth > 0
                        {
                            if matches!(self.current_token().kind, TokenKind::LeftParen) {
                                paren_depth += 1;
                                current_arg.push('(');
                            } else if matches!(self.current_token().kind, TokenKind::RightParen) {
                                paren_depth -= 1;
                                if paren_depth >= 0 {
                                    current_arg.push(')');
                                }
                            } else if matches!(self.current_token().kind, TokenKind::Comma)
                                && paren_depth == 0
                            {
                                args.push(current_arg.trim().to_string());
                                current_arg = String::new();
                            } else {
                                // Map constants like pi -> !PI
                                let token_str = match &self.current_token().kind {
                                    TokenKind::Identifier(name) => match name.as_str() {
                                        "pi" => "!PI",
                                        "e" => "!E",
                                        _ => &self.current_token().lexeme,
                                    },
                                    _ => &self.current_token().lexeme,
                                };
                                current_arg.push_str(token_str);
                            }
                            self.advance();
                        }

                        if !current_arg.trim().is_empty() {
                            args.push(current_arg.trim().to_string());
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance(); // skip ')'
                        }

                        // Generate XDL equivalent: FINDGEN(n) * (end-start) / (n-1) + start
                        if args.len() == 3 {
                            let start = &args[0];
                            let end = &args[1];
                            let n = &args[2];
                            expr.push_str(&format!(
                                "FINDGEN({}) * (({}) - ({})) / ({} - 1) + ({})",
                                n, end, start, n, start
                            ));
                        } else {
                            // If wrong number of args, just emit a comment
                            expr.push_str(&format!(
                                "/* linspace error: expected 3 args, got {} */",
                                args.len()
                            ));
                        }
                        continue;
                    }

                    // Special handling for meshgrid - DISABLED
                    // XDL doesn't support multiple output assignment [X, Y] = ...
                    // So we handle this at the statement level instead
                    // (see transpile_statement for meshgrid handling)

                    // Special handling for PLOT command with line styles
                    if is_procedure_call && func_name == "PLOT" {
                        // Add tile comment if we're in a subplot
                        if self.current_tile > 0 {
                            self.emit_line(&format!(
                                "  ; Tile {} of {}",
                                self.current_tile,
                                self.subplot_rows * self.subplot_cols
                            ));
                        }
                        expr.push_str("PLOT, ");
                        self.advance(); // skip function name
                        self.advance(); // skip '('

                        let mut arg_count = 0;
                        // Collect arguments until ')'
                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) {
                            match &self.current_token().kind {
                                TokenKind::String(s) => {
                                    // Check if this is a line style string (contains -, :, ., or color letters)
                                    if s.contains('-')
                                        || s.contains(':')
                                        || s.contains('.')
                                        || s.contains('r')
                                        || s.contains('g')
                                        || s.contains('b')
                                        || s.contains('*')
                                        || s.contains('o')
                                        || s.contains('+')
                                    {
                                        // This is likely a line style, skip it
                                        self.advance();
                                        // Skip comma if present
                                        if matches!(self.current_token().kind, TokenKind::Comma) {
                                            self.advance();
                                        }
                                        continue;
                                    } else {
                                        if arg_count > 0 {
                                            expr.push_str(", ");
                                        }
                                        expr.push_str(&format!("'{}'", s));
                                        arg_count += 1;
                                    }
                                }
                                TokenKind::Identifier(n) => {
                                    if arg_count > 0 {
                                        expr.push_str(", ");
                                    }
                                    // Map MATLAB constants
                                    let mapped = match n.as_str() {
                                        "pi" => "!PI",
                                        "e" => "!E",
                                        _ => n.as_str(),
                                    };
                                    expr.push_str(mapped);
                                    arg_count += 1;
                                }
                                TokenKind::Number(n) => {
                                    if arg_count > 0 {
                                        expr.push_str(", ");
                                    }
                                    expr.push_str(&n.to_string());
                                    arg_count += 1;
                                }
                                TokenKind::Comma => {
                                    // Skip commas, we'll add them ourselves
                                }
                                TokenKind::LeftParen => expr.push('('),
                                TokenKind::RightParen => break,
                                _ => expr.push_str(&self.current_token().lexeme),
                            }
                            self.advance();
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance(); // skip ')'
                        }
                        continue;
                    }

                    if is_procedure_call && matches!(func_name, "PRINT" | "PRINTF") {
                        // Convert MATLAB func(arg) to XDL FUNC, arg
                        expr.push_str(func_name);
                        expr.push_str(", ");
                        self.advance(); // skip function name
                        self.advance(); // skip '('

                        // Collect arguments until ')'
                        while !matches!(
                            self.current_token().kind,
                            TokenKind::RightParen | TokenKind::EOF
                        ) {
                            match &self.current_token().kind {
                                TokenKind::Identifier(n) => {
                                    // Map MATLAB function names to XDL
                                    if let Some(xdl_func) = get_xdl_function(n) {
                                        expr.push_str(xdl_func);
                                    } else {
                                        expr.push_str(n);
                                    }
                                }
                                TokenKind::Number(n) => expr.push_str(&n.to_string()),
                                TokenKind::String(s) => expr.push_str(&format!("'{}'", s)),
                                TokenKind::Comma => expr.push_str(", "),
                                TokenKind::LeftParen => expr.push('('),
                                _ => expr.push_str(&self.current_token().lexeme),
                            }
                            self.advance();
                        }

                        if matches!(self.current_token().kind, TokenKind::RightParen) {
                            self.advance(); // skip ')'
                        }
                        continue;
                    } else {
                        expr.push_str(func_name);
                    }
                }
                TokenKind::Number(n) => expr.push_str(&n.to_string()),
                TokenKind::String(s) => expr.push_str(&format!("'{}'", s)),
                TokenKind::LeftParen => {
                    // Check if this is a range expression like (0:L-1) or (1:10)
                    // We need to lookahead to see if there's a colon inside
                    let start_pos = self.position;
                    self.advance(); // skip '('

                    // Collect tokens until ')' to check for colon
                    let mut range_tokens = Vec::new();
                    let mut paren_depth = 1;
                    let mut has_colon = false;

                    while paren_depth > 0 && !matches!(self.current_token().kind, TokenKind::EOF) {
                        match &self.current_token().kind {
                            TokenKind::LeftParen => paren_depth += 1,
                            TokenKind::RightParen => paren_depth -= 1,
                            TokenKind::Colon => has_colon = true,
                            _ => {}
                        }
                        if paren_depth > 0 {
                            range_tokens.push(self.current_token().clone());
                        }
                        self.advance();
                    }

                    if has_colon && paren_depth == 0 {
                        // This is a range expression like (0:L-1) or (1:2:10)
                        // Parse the range and convert to FINDGEN
                        let range_expr = self.parse_range_expression(&range_tokens);
                        expr.push_str(&range_expr);
                    } else {
                        // Not a range, restore position and just add the paren
                        self.position = start_pos;
                        self.advance();
                        expr.push('(');
                    }
                    continue;
                }
                TokenKind::ElementMultiply => expr.push_str(" * "),
                TokenKind::ElementDivide => expr.push_str(" / "),
                TokenKind::ElementPower => expr.push_str(" ^ "),
                TokenKind::Comment(_) => {
                    // Skip comments in expressions
                    self.advance();
                    continue;
                }
                _ => expr.push_str(&token.lexeme),
            }

            expr.push(' ');
            self.advance();
        }

        // Skip newline/semicolon
        if matches!(
            self.current_token().kind,
            TokenKind::Newline | TokenKind::Semicolon
        ) {
            self.advance();
        }

        let expr_trimmed = expr.trim();

        // Post-process: detect standalone range expressions with colons
        // Pattern: "var = start : end" or "var = start : step : end"
        // Only convert if this looks like a simple assignment with a range
        if expr_trimmed.contains(" = ") && expr_trimmed.contains(" : ") {
            // Split by = to get left and right sides
            let parts: Vec<&str> = expr_trimmed.splitn(2, " = ").collect();
            if parts.len() == 2 {
                let lhs = parts[0].trim();
                let rhs = parts[1].trim();

                // Check if RHS contains colon - indicating a range expression
                // The convert_range_to_findgen function handles both simple and complex ranges
                let colon_count = rhs.matches(" : ").count();

                // Don't convert if it looks like array indexing or cell arrays
                let is_array_op = rhs.contains("[") || rhs.contains("{");

                if colon_count > 0 && !is_array_op {
                    // This looks like a range expression: convert it
                    let converted = self.convert_range_to_findgen(rhs);
                    return format!("{} = {}", lhs, converted);
                }
            }
        }

        expr_trimmed.to_string()
    }

    fn convert_range(&self, range: &str) -> Result<String, String> {
        // Convert MATLAB range like 1:10 to XDL 0, 9
        // Or 1:2:10 to 0, 9, 2

        let parts: Vec<&str> = range.split(':').collect();

        match parts.len() {
            2 => {
                // start:end -> (start-1), (end-1)
                let start: i32 = parts[0].trim().parse().map_err(|_| "Invalid range start")?;
                let end: i32 = parts[1].trim().parse().map_err(|_| "Invalid range end")?;
                Ok(format!("{}, {}", start - 1, end - 1))
            }
            3 => {
                // start:step:end -> (start-1), (end-1), step
                let start: i32 = parts[0].trim().parse().map_err(|_| "Invalid range start")?;
                let step: i32 = parts[1].trim().parse().map_err(|_| "Invalid range step")?;
                let end: i32 = parts[2].trim().parse().map_err(|_| "Invalid range end")?;
                Ok(format!("{}, {}, {}", start - 1, end - 1, step))
            }
            _ => Ok(range.to_string()), // Return as-is if not a simple range
        }
    }

    fn parse_range_expression(&self, tokens: &[Token]) -> String {
        // Parse range expressions like 0:L-1 or 1:2:10
        // Split by colons
        let mut parts = Vec::new();
        let mut current_part = Vec::new();

        for token in tokens {
            if matches!(token.kind, TokenKind::Colon) {
                parts.push(current_part.clone());
                current_part.clear();
            } else {
                current_part.push(token.clone());
            }
        }
        if !current_part.is_empty() {
            parts.push(current_part);
        }

        // Convert tokens to string expressions
        let expr_parts: Vec<String> = parts
            .iter()
            .map(|part| {
                part.iter()
                    .map(|t| {
                        match &t.kind {
                            TokenKind::Identifier(name) => {
                                // Map constants
                                match name.as_str() {
                                    "pi" => "!PI",
                                    "e" => "!E",
                                    _ => &t.lexeme,
                                }
                                .to_string()
                            }
                            TokenKind::Number(n) => n.to_string(),
                            _ => t.lexeme.clone(),
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .collect();

        // Handle different range formats
        match expr_parts.len() {
            2 => {
                // start:end -> FINDGEN((end) - (start) + 1) + (start)
                let start = expr_parts[0].trim();
                let end = expr_parts[1].trim();

                // For 0:L-1 specifically, this is just FINDGEN(L)
                if start == "0" {
                    format!("FINDGEN(({})+1)", end)
                } else {
                    format!("FINDGEN(({})-({}) +1) + ({})", end, start, start)
                }
            }
            3 => {
                // start:step:end -> (FINDGEN(((end)-(start))/(step)+1) * (step)) + (start)
                let start = expr_parts[0].trim();
                let step = expr_parts[1].trim();
                let end = expr_parts[2].trim();
                format!(
                    "(FINDGEN((({})-({}))/({}) +1) * ({})) + ({})",
                    end, start, step, step, start
                )
            }
            _ => {
                // Shouldn't happen, but fall back to comment
                "/* unhandled range expression */".to_string()
            }
        }
    }

    /// Parse MATLAB array literal [1, 2, 3] or [1, 2; 3, 4] to XDL array syntax
    fn parse_array_literal(&mut self) -> Result<String, String> {
        // Skip opening bracket
        self.advance();

        let mut rows: Vec<Vec<String>> = Vec::new();
        let mut current_row: Vec<String> = Vec::new();
        let mut current_element = String::new();
        let mut paren_depth = 0;
        let mut bracket_depth = 0;

        while !matches!(self.current_token().kind, TokenKind::EOF) {
            match &self.current_token().kind {
                TokenKind::RightBracket if bracket_depth == 0 && paren_depth == 0 => {
                    // End of array literal
                    if !current_element.trim().is_empty() {
                        current_row.push(current_element.trim().to_string());
                    }
                    if !current_row.is_empty() {
                        rows.push(current_row.clone());
                    }
                    self.advance();
                    break;
                }
                TokenKind::Comma if paren_depth == 0 && bracket_depth == 0 => {
                    // Element separator within a row
                    if !current_element.trim().is_empty() {
                        current_row.push(current_element.trim().to_string());
                        current_element.clear();
                    }
                    self.advance();
                }
                TokenKind::Semicolon if paren_depth == 0 && bracket_depth == 0 => {
                    // Row separator
                    if !current_element.trim().is_empty() {
                        current_row.push(current_element.trim().to_string());
                        current_element.clear();
                    }
                    if !current_row.is_empty() {
                        rows.push(current_row.clone());
                        current_row.clear();
                    }
                    self.advance();
                }
                TokenKind::Colon => {
                    // Handle colon operator for ranges
                    current_element.push(':');
                    self.advance();
                }
                TokenKind::LeftParen => {
                    paren_depth += 1;
                    current_element.push('(');
                    self.advance();
                }
                TokenKind::RightParen => {
                    paren_depth -= 1;
                    current_element.push(')');
                    self.advance();
                }
                TokenKind::LeftBracket => {
                    bracket_depth += 1;
                    current_element.push('[');
                    self.advance();
                }
                TokenKind::RightBracket => {
                    bracket_depth -= 1;
                    current_element.push(']');
                    self.advance();
                }
                TokenKind::Identifier(name) => {
                    // Map constants and check for function calls
                    let mapped = match name.as_str() {
                        "pi" => "!PI".to_string(),
                        "e" => "!E".to_string(),
                        other => {
                            // Check if this is a function call
                            if get_xdl_function(other).is_some() {
                                get_xdl_function(other).unwrap().to_string()
                            } else {
                                other.to_string()
                            }
                        }
                    };
                    current_element.push_str(&mapped);
                    self.advance();
                }
                TokenKind::Number(n) => {
                    // If we have an existing element and it's also a number, treat space as separator
                    if !current_element.trim().is_empty()
                        && current_element
                            .trim()
                            .chars()
                            .all(|c| c.is_ascii_digit() || c == '.' || c == '-')
                    {
                        // Push the previous number as an element
                        current_row.push(current_element.trim().to_string());
                        current_element.clear();
                    }
                    current_element.push_str(&n.to_string());
                    self.advance();
                }
                TokenKind::Newline => {
                    // Skip newlines inside array literals
                    self.advance();
                }
                _ => {
                    current_element.push_str(&self.current_token().lexeme);
                    self.advance();
                }
            }
        }

        // Convert to XDL array syntax
        if rows.is_empty() {
            return Ok("[]".to_string());
        }

        if rows.len() == 1 {
            // Simple vector (1D array)
            let elements = &rows[0];
            if elements.len() == 1 {
                // Check if single element contains colon (range expression)
                let elem = &elements[0];
                if elem.contains(':') {
                    // Parse as range expression
                    Ok(self.convert_range_to_findgen(elem))
                } else {
                    Ok(format!("[{}]", elem))
                }
            } else {
                // Multiple elements: [e1, e2, e3, ...]
                let converted: Vec<String> = elements
                    .iter()
                    .map(|e| {
                        if e.contains(':') {
                            self.convert_range_to_findgen(e)
                        } else {
                            e.clone()
                        }
                    })
                    .collect();
                Ok(format!("[{}]", converted.join(", ")))
            }
        } else {
            // 2D matrix: [[row1], [row2], ...] or use TRANSPOSE if needed
            let row_strs: Vec<String> = rows
                .iter()
                .map(|row| {
                    let elements: Vec<String> = row
                        .iter()
                        .map(|e| {
                            if e.contains(':') {
                                self.convert_range_to_findgen(e)
                            } else {
                                e.clone()
                            }
                        })
                        .collect();
                    format!("[{}]", elements.join(", "))
                })
                .collect();
            Ok(format!("[{}]", row_strs.join(", ")))
        }
    }

    /// Convert MATLAB range expression (e.g., "1:10" or "0:0.1:1") to XDL FINDGEN-based expression
    fn convert_range_to_findgen(&self, range_str: &str) -> String {
        let parts: Vec<&str> = range_str.split(':').collect();

        match parts.len() {
            2 => {
                // start:end
                let start = parts[0].trim();
                let end = parts[1].trim();

                // Try to parse as numbers for special cases
                if let (Ok(s), Ok(e)) = (start.parse::<f64>(), end.parse::<f64>()) {
                    let count = (e - s + 1.0).max(0.0) as i32;
                    if s == 0.0 {
                        format!("FINDGEN({})", count)
                    } else {
                        format!("FINDGEN({}) + {}", count, start)
                    }
                } else {
                    // Complex expression
                    format!("FINDGEN((({}) - ({})) + 1) + ({})", end, start, start)
                }
            }
            3 => {
                // start:step:end
                let start = parts[0].trim();
                let step = parts[1].trim();
                let end = parts[2].trim();

                if let (Ok(s), Ok(st), Ok(e)) = (
                    start.parse::<f64>(),
                    step.parse::<f64>(),
                    end.parse::<f64>(),
                ) {
                    let count = ((e - s) / st + 1.0).max(0.0) as i32;
                    if s == 0.0 {
                        format!("FINDGEN({}) * {}", count, step)
                    } else {
                        format!("FINDGEN({}) * {} + {}", count, step, start)
                    }
                } else {
                    // Complex expression
                    format!(
                        "FINDGEN(((({}) - ({})) / ({})) + 1) * ({}) + ({})",
                        end, start, step, step, start
                    )
                }
            }
            _ => format!("/* invalid range: {} */", range_str),
        }
    }
}

/// Main transpilation function
pub fn transpile_matlab_to_xdl(matlab_code: &str) -> Result<String, String> {
    let mut lexer = Lexer::new(matlab_code);
    let tokens = lexer.tokenize()?;

    let mut transpiler = Transpiler::new(tokens);
    transpiler.transpile()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_assignment() {
        let matlab = "x = 5;";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("x = 5"));
    }

    #[test]
    fn test_function_mapping() {
        let matlab = "y = sin(x);";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("SIN"));
    }

    #[test]
    fn test_simple_array_literal() {
        let matlab = "a = [1, 2, 3, 4, 5];";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("a = [1, 2, 3, 4, 5]"));
    }

    #[test]
    fn test_array_literal_with_spaces() {
        let matlab = "b = [1 2 3];";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("[1") && result.contains("2") && result.contains("3]"));
    }

    #[test]
    fn test_column_vector() {
        let matlab = "c = [1; 2; 3];";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        // Should be represented as nested arrays
        assert!(result.contains("c = [[1], [2], [3]]"));
    }

    #[test]
    fn test_matrix_literal() {
        let matlab = "M = [1, 2, 3; 4, 5, 6];";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        // Should be represented as nested arrays: [[1, 2, 3], [4, 5, 6]]
        assert!(result.contains("M = [[1, 2, 3], [4, 5, 6]]"));
    }

    #[test]
    fn test_colon_range_simple() {
        let matlab = "x = 1:10;";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        // Should convert to FINDGEN
        assert!(result.contains("FINDGEN"));
    }

    #[test]
    fn test_colon_range_with_step() {
        let matlab = "y = 0:0.1:1;";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        // Should convert to FINDGEN with step
        assert!(result.contains("FINDGEN"));
    }

    #[test]
    fn test_zeros_function() {
        let matlab = "z = zeros(5);";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("FLTARR(5)"));
    }

    #[test]
    fn test_zeros_function_2d() {
        let matlab = "z = zeros(3, 4);";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("FLTARR(3, 4)"));
    }

    #[test]
    fn test_ones_function() {
        let matlab = "o = ones(5);";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("FLTARR(5) + 1"));
    }

    #[test]
    fn test_eye_function() {
        let matlab = "I = eye(4);";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("IDENTITY(4)"));
    }

    #[test]
    fn test_linspace_function() {
        let matlab = "x = linspace(0, 10, 100);";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        // Should convert to FINDGEN expression
        assert!(result.contains("FINDGEN"));
    }

    #[test]
    fn test_array_with_range() {
        let matlab = "a = [1:5];";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        // Array containing a range
        assert!(result.contains("FINDGEN"));
    }

    #[test]
    fn test_array_element_operations() {
        let matlab = "result = a .* b;";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        println!("Result: {}", result);
        // Element-wise multiply should convert to *
        // The actual format has spaces around operators
        assert!(result.contains("result = a * b") || result.contains("result = a  *  b"));
    }

    #[test]
    fn test_break_statement() {
        let matlab = "break;";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("BREAK"));
    }

    #[test]
    fn test_continue_statement() {
        let matlab = "continue;";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("CONTINUE"));
    }

    #[test]
    fn test_return_statement() {
        let matlab = "return;";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("RETURN"));
    }

    #[test]
    fn test_simple_switch() {
        let matlab = r#"switch x
            case 1
                y = 'one';
            case 2
                y = 'two';
            otherwise
                y = 'other';
        end"#;
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("CASE x OF"));
        assert!(result.contains("1: BEGIN"));
        assert!(result.contains("2: BEGIN"));
        assert!(result.contains("ELSE: BEGIN"));
        assert!(result.contains("ENDCASE"));
    }

    #[test]
    fn test_switch_with_cell_array() {
        let matlab = r#"switch x
            case {1, 2}
                y = 'one or two';
        end"#;
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("CASE x OF"));
        assert!(result.contains(": BEGIN"));
    }

    #[test]
    fn test_try_catch() {
        let matlab = r#"try
            result = risky_operation();
        catch err
            result = 0;
        end"#;
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("TRY block"));
        assert!(result.contains("CATCH block"));
    }

    #[test]
    fn test_for_loop_with_step() {
        let matlab = "for i = 1:2:10\n  disp(i);\nend";
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("for i ="));
        // Should have converted the range
        assert!(!result.contains("1:2:10"));
    }

    #[test]
    fn test_nested_control_flow() {
        let matlab = r#"for i = 1:5
            if i == 3
                continue;
            end
            disp(i);
        end"#;
        let result = transpile_matlab_to_xdl(matlab).unwrap();
        assert!(result.contains("for i"));
        assert!(result.contains("if"));
        assert!(result.contains("CONTINUE"));
    }
}