mathypad 0.1.17

A smart TUI calculator that understands units and makes complex calculations simple.
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
//! Expression evaluation functions with unit-aware arithmetic

use super::parser::tokenize_with_units;
use super::tokens::Token;
use crate::FLOAT_EPSILON;
use crate::rate_unit;
use crate::units::{Unit, UnitType, UnitValue, parse_unit};
use std::collections::HashMap;

/// Main evaluation function that handles context for line references
pub fn evaluate_expression_with_context(
    text: &str,
    previous_results: &[Option<String>],
    current_line: usize,
) -> Option<String> {
    // New approach: tokenize everything then find mathematical patterns
    if let Some(tokens) = super::parser::tokenize_with_units(text) {
        // Try to find and evaluate mathematical patterns in the token stream
        if let Some(result) =
            evaluate_tokens_stream_with_context(&tokens, previous_results, current_line)
        {
            return Some(result.format());
        }
    }

    None
}

/// Find and evaluate mathematical patterns in a token stream
pub fn evaluate_tokens_stream_with_context(
    tokens: &[Token],
    previous_results: &[Option<String>],
    current_line: usize,
) -> Option<UnitValue> {
    if tokens.is_empty() {
        return None;
    }

    // Look for the longest valid mathematical subsequence
    // Try different starting positions and lengths
    for start in 0..tokens.len() {
        for end in (start + 1..=tokens.len()).rev() {
            // Try longest first
            let subseq = &tokens[start..end];
            if is_valid_mathematical_sequence(subseq) {
                // Try to evaluate this subsequence
                if let Some(result) =
                    evaluate_tokens_with_units_and_context(subseq, previous_results, current_line)
                {
                    return Some(result);
                }
                // If this subsequence failed to evaluate and it spans the entire input,
                // don't try shorter subsequences for certain cases:
                // 1. Pure mathematical expressions (prevents "5 / 0" from evaluating as "5")
                // 2. Pure conversion expressions (prevents "5 MB to QPS" from evaluating as "5 MB")
                // 3. Mixed expressions with conversion at the end (prevents "5 GiB + 10 in seconds" fallback)
                if start == 0 && end == tokens.len() {
                    let has_math = has_mathematical_operators(subseq);
                    let has_conversion = subseq.iter().any(|t| matches!(t, Token::To | Token::In));

                    // Check if this is an expression with conversion at the end (like "A + B in C")
                    // These should fail entirely if conversion is impossible, not fall back
                    let has_conversion_at_end = tokens.len() >= 2
                        && matches!(tokens[tokens.len() - 2], Token::To | Token::In);

                    // Prevent fallback for:
                    // 1. Pure math expressions: has_math && !has_conversion
                    // 2. Pure conversion expressions: has_conversion && !has_math
                    // 3. Mixed expressions with conversion at the end: has_math && has_conversion && has_conversion_at_end
                    #[allow(clippy::nonminimal_bool)]
                    if !has_math && has_conversion
                        || has_math && !has_conversion
                        || has_math && has_conversion_at_end
                    {
                        return None; // Fail entirely for these cases
                    }
                    // For other mixed expressions, allow fallback
                }
            }
        }
    }

    None
}

/// Check if a token sequence contains mathematical operators
fn has_mathematical_operators(tokens: &[Token]) -> bool {
    tokens.iter().any(|t| {
        matches!(
            t,
            Token::Plus | Token::Minus | Token::Multiply | Token::Divide | Token::Power
        )
    })
}

/// Check if a token sequence forms a valid mathematical expression
fn is_valid_mathematical_sequence(tokens: &[Token]) -> bool {
    if tokens.is_empty() {
        return false;
    }

    // Must have at least one number, unit, line reference, variable, or function
    let has_value = tokens.iter().any(|t| {
        matches!(
            t,
            Token::Number(_)
                | Token::NumberWithUnit(_, _)
                | Token::LineReference(_)
                | Token::Variable(_)
                | Token::Function(_)
        )
    });

    if !has_value {
        return false;
    }

    // Simple validation: check for basic mathematical patterns
    // More sophisticated validation can be added as needed

    // Pattern 1: Single value (number, unit, variable, line ref)
    if tokens.len() == 1 {
        return matches!(
            tokens[0],
            Token::Number(_)
                | Token::NumberWithUnit(_, _)
                | Token::LineReference(_)
                | Token::Variable(_)
        );
    }

    // Pattern 2: Value + unit conversion (e.g., "5 GiB to TB", "storage to TB")
    if tokens.len() == 3 {
        let is_value_or_var = |t: &Token| {
            matches!(
                t,
                Token::Number(_)
                    | Token::NumberWithUnit(_, _)
                    | Token::LineReference(_)
                    | Token::Variable(_)
            )
        };
        let is_unit_or_var =
            |t: &Token| matches!(t, Token::NumberWithUnit(_, _) | Token::Variable(_));

        if is_value_or_var(&tokens[0])
            && matches!(tokens[1], Token::To | Token::In)
            && is_unit_or_var(&tokens[2])
        {
            return true;
        }

        // Pattern: Percentage of value (e.g., "10% of 50")
        if matches!(tokens[0], Token::NumberWithUnit(_, Unit::Percent))
            && matches!(tokens[1], Token::Of)
            && is_value_or_var(&tokens[2])
        {
            return true;
        }
    }

    // Pattern 3: Function calls (function ( value ))
    if tokens.len() == 4 {
        if let (Token::Function(_), Token::LeftParen, _, Token::RightParen) =
            (&tokens[0], &tokens[1], &tokens[2], &tokens[3])
        {
            // Check if the middle token is a value
            if matches!(
                tokens[2],
                Token::Number(_)
                    | Token::NumberWithUnit(_, _)
                    | Token::LineReference(_)
                    | Token::Variable(_)
            ) {
                return true;
            }
        }
    }

    // Pattern 4: Binary operations (value op value)
    if tokens.len() == 3 {
        let is_value = |t: &Token| {
            matches!(
                t,
                Token::Number(_)
                    | Token::NumberWithUnit(_, _)
                    | Token::LineReference(_)
                    | Token::Variable(_)
            )
        };
        let is_op = |t: &Token| {
            matches!(
                t,
                Token::Plus | Token::Minus | Token::Multiply | Token::Divide | Token::Power
            )
        };

        if is_value(&tokens[0]) && is_op(&tokens[1]) && is_value(&tokens[2]) {
            return true;
        }
    }

    // Pattern 4: More complex expressions with parentheses, multiple operations
    // For now, if we have values and operators, assume it could be valid
    // The actual evaluation will determine if it's truly valid
    let has_operator = tokens.iter().any(|t| {
        matches!(
            t,
            Token::Plus | Token::Minus | Token::Multiply | Token::Divide | Token::Power
        )
    });

    has_value && (tokens.len() == 1 || has_operator)
}

/// Enhanced evaluation function that handles both expressions and variable assignments
pub fn evaluate_with_variables(
    text: &str,
    variables: &HashMap<String, String>,
    previous_results: &[Option<String>],
    current_line: usize,
) -> (Option<String>, Option<(String, String)>) {
    // Return (result, optional_variable_assignment)

    // New approach: tokenize everything then find patterns
    if let Some(tokens) = super::parser::tokenize_with_units(text) {
        // First check for variable assignments
        if let Some(assignment) =
            find_variable_assignment_in_tokens(&tokens, variables, previous_results, current_line)
        {
            return (Some(assignment.1.clone()), Some(assignment));
        }

        // Then look for mathematical expressions
        if let Some(result) = evaluate_tokens_stream_with_variables(
            &tokens,
            variables,
            previous_results,
            current_line,
        ) {
            return (Some(result.format()), None);
        }
    }

    (None, None)
}

/// Find variable assignment pattern in token stream
fn find_variable_assignment_in_tokens(
    tokens: &[Token],
    variables: &HashMap<String, String>,
    previous_results: &[Option<String>],
    current_line: usize,
) -> Option<(String, String)> {
    // Look for pattern: Variable Assign Expression
    if tokens.len() >= 3 {
        if let (Token::Variable(var_name), Token::Assign) = (&tokens[0], &tokens[1]) {
            // Extract the right-hand side (everything after =)
            let rhs_tokens = &tokens[2..];

            // Evaluate the right-hand side
            if let Some(value) = evaluate_tokens_with_units_and_context_and_variables(
                rhs_tokens,
                variables,
                previous_results,
                current_line,
            ) {
                return Some((var_name.clone(), value.format()));
            }
        }
    }

    None
}

/// Find and evaluate mathematical patterns in a token stream with variable support
fn evaluate_tokens_stream_with_variables(
    tokens: &[Token],
    variables: &HashMap<String, String>,
    previous_results: &[Option<String>],
    current_line: usize,
) -> Option<UnitValue> {
    if tokens.is_empty() {
        return None;
    }

    // First check if we have undefined variables in what looks like a mathematical context
    if has_undefined_variables_in_math_context(tokens, variables) {
        return None; // Fail entirely if undefined variables are in mathematical expressions
    }

    // Look for the longest valid mathematical subsequence
    // Try different starting positions and lengths
    for start in 0..tokens.len() {
        for end in (start + 1..=tokens.len()).rev() {
            // Try longest first
            let subseq = &tokens[start..end];
            if is_valid_mathematical_sequence(subseq) && all_variables_defined(subseq, variables) {
                // Try to evaluate this subsequence
                if let Some(result) = evaluate_tokens_with_units_and_context_and_variables(
                    subseq,
                    variables,
                    previous_results,
                    current_line,
                ) {
                    return Some(result);
                }
                // If this subsequence failed to evaluate and it spans the entire input,
                // don't try shorter subsequences for certain cases:
                // 1. Pure mathematical expressions (prevents "5 / 0" from evaluating as "5")
                // 2. Pure conversion expressions (prevents "5 MB to QPS" from evaluating as "5 MB")
                // Note: Mixed expressions (both math and conversion) allow fallback for partial evaluation
                if start == 0 && end == tokens.len() {
                    let has_math = has_mathematical_operators(subseq);
                    let has_conversion = subseq.iter().any(|t| matches!(t, Token::To | Token::In));

                    // Prevent fallback only for pure expressions that fail
                    if (has_math && !has_conversion) || (has_conversion && !has_math) {
                        return None; // Fail entirely for pure expressions
                    }
                    // For mixed expressions (has_math && has_conversion), allow fallback
                }
            }
        }
    }

    None
}

/// Check if there are undefined variables in what appears to be a mathematical context
fn has_undefined_variables_in_math_context(
    tokens: &[Token],
    variables: &HashMap<String, String>,
) -> bool {
    // Look for undefined variables that are adjacent to mathematical operators or values
    for i in 0..tokens.len() {
        if let Token::Variable(var_name) = &tokens[i] {
            if !variables.contains_key(var_name) {
                // Check if this undefined variable is in a mathematical context
                let has_math_neighbor = (i > 0 && is_math_token(&tokens[i - 1]))
                    || (i + 1 < tokens.len() && is_math_token(&tokens[i + 1]));

                if has_math_neighbor {
                    return true;
                }
            }
        }
    }
    false
}

/// Check if a token is mathematical (operator, number, unit, etc.)
fn is_math_token(token: &Token) -> bool {
    matches!(
        token,
        Token::Number(_)
            | Token::NumberWithUnit(_, _)
            | Token::LineReference(_)
            | Token::Plus
            | Token::Minus
            | Token::Multiply
            | Token::Divide
            | Token::Power
            | Token::LeftParen
            | Token::RightParen
            | Token::To
            | Token::In
            | Token::Function(_)
    )
}

/// Check if all variables in a token sequence are defined
fn all_variables_defined(tokens: &[Token], variables: &HashMap<String, String>) -> bool {
    for token in tokens {
        if let Token::Variable(var_name) = token {
            if !variables.contains_key(var_name) {
                return false;
            }
        }
    }
    true
}

/// Parse and evaluate with context for line references
pub fn parse_and_evaluate_with_context(
    expr: &str,
    previous_results: &[Option<String>],
    current_line: usize,
) -> Option<UnitValue> {
    let tokens = tokenize_with_units(expr)?;
    evaluate_tokens_with_units_and_context(&tokens, previous_results, current_line)
}

/// Evaluate tokens with unit-aware arithmetic and context support
pub fn evaluate_tokens_with_units_and_context(
    tokens: &[Token],
    previous_results: &[Option<String>],
    current_line: usize,
) -> Option<UnitValue> {
    if tokens.is_empty() {
        return None;
    }

    // Handle simple conversion expressions like "1 GiB to KiB" (only if it's the entire expression)
    if tokens.len() == 3 {
        if let (
            Token::NumberWithUnit(value, from_unit),
            Token::To,
            Token::NumberWithUnit(_, to_unit),
        ) = (&tokens[0], &tokens[1], &tokens[2])
        {
            let unit_value = UnitValue::new(*value, Some(from_unit.clone()));
            return unit_value.to_unit(to_unit);
        }
        // Handle percentage of value expressions like "10% of 50"
        if let (Token::NumberWithUnit(percentage, Unit::Percent), Token::Of, value_token) =
            (&tokens[0], &tokens[1], &tokens[2])
        {
            // Resolve the value token (could be number, unit, variable, or line reference)
            let base_value = match value_token {
                Token::Number(n) => UnitValue::new(*n, None),
                Token::NumberWithUnit(n, unit) => UnitValue::new(*n, Some(unit.clone())),
                Token::LineReference(line_index) => {
                    resolve_line_reference(*line_index, previous_results, current_line)?
                }
                _ => return None, // Variables would need additional handling
            };

            // Calculate percentage: convert percentage to decimal first, then multiply
            let percentage_decimal = Unit::Percent.to_base_value(*percentage);
            return Some(UnitValue::new(
                percentage_decimal * base_value.value,
                base_value.unit,
            ));
        }
    }

    // Check if we have an "in" or "to" conversion request at the end
    let mut target_unit_for_conversion = None;
    let mut evaluation_tokens = tokens;

    // Look for "in" or "to" followed by a unit at the end
    for i in 0..tokens.len().saturating_sub(1) {
        if let Token::In | Token::To = &tokens[i] {
            // Look for unit after "in" or "to"
            for j in (i + 1)..tokens.len() {
                if let Token::NumberWithUnit(_, unit) = &tokens[j] {
                    target_unit_for_conversion = Some(unit.clone());
                    evaluation_tokens = &tokens[..i]; // Evaluate everything before "in"/"to"
                    break;
                }
            }
            break;
        }
    }

    // Handle simple arithmetic with units
    let mut operator_stack = Vec::new();
    let mut value_stack = Vec::new();

    for token in evaluation_tokens {
        match token {
            Token::Number(n) => {
                value_stack.push(UnitValue::new(*n, None));
            }
            Token::NumberWithUnit(value, unit) => {
                value_stack.push(UnitValue::new(*value, Some(unit.clone())));
            }
            Token::LineReference(line_index) => {
                // Resolve line reference to its calculated result
                if let Some(line_result) =
                    resolve_line_reference(*line_index, previous_results, current_line)
                {
                    value_stack.push(line_result);
                } else {
                    return None; // Invalid or circular reference
                }
            }
            Token::Plus | Token::Minus | Token::Multiply | Token::Divide | Token::Power => {
                while let Some(top_op) = operator_stack.last() {
                    // Power is right-associative, others are left-associative
                    let should_pop = if matches!(token, Token::Power) {
                        // For right-associative operators, pop only if top has higher precedence
                        precedence_unit(token) < precedence_unit(top_op)
                    } else {
                        // For left-associative operators, pop if top has same or higher precedence
                        precedence_unit(token) <= precedence_unit(top_op)
                    };

                    if should_pop {
                        let op = operator_stack.pop().unwrap();
                        if !apply_operator_with_units(&mut value_stack, &op) {
                            return None;
                        }
                    } else {
                        break;
                    }
                }
                operator_stack.push(token.clone());
            }
            Token::LeftParen => {
                operator_stack.push(token.clone());
            }
            Token::RightParen => {
                // Process operators until we find a left paren or function
                while let Some(op) = operator_stack.pop() {
                    if matches!(op, Token::LeftParen) {
                        // Check if there's a function waiting
                        if let Some(Token::Function(func_name)) = operator_stack.last().cloned() {
                            operator_stack.pop(); // Remove the function
                            if !apply_function(&mut value_stack, &func_name) {
                                return None;
                            }
                        }
                        break;
                    }
                    if !apply_operator_with_units(&mut value_stack, &op) {
                        return None;
                    }
                }
            }
            Token::Function(_) => {
                // Functions are pushed to operator stack
                operator_stack.push(token.clone());
            }
            _ => {}
        }
    }

    while let Some(op) = operator_stack.pop() {
        if !apply_operator_with_units(&mut value_stack, &op) {
            return None;
        }
    }

    if value_stack.len() == 1 {
        let mut result = value_stack.pop().unwrap();

        // If we have a target unit for conversion, convert the result
        if let Some(target_unit) = target_unit_for_conversion {
            if let Some(converted) = result.to_unit(&target_unit) {
                result = converted;
            } else {
                return None; // Explicit conversion failed, fail the entire expression
            }
        }

        Some(result)
    } else {
        None
    }
}

/// Variable-aware version of evaluate_tokens_with_units_and_context
fn evaluate_tokens_with_units_and_context_and_variables(
    tokens: &[Token],
    variables: &HashMap<String, String>,
    previous_results: &[Option<String>],
    current_line: usize,
) -> Option<UnitValue> {
    if tokens.is_empty() {
        return None;
    }

    // Handle simple conversion expressions like "1 GiB to KiB" (only if it's the entire expression)
    if tokens.len() == 3 {
        if let (
            Token::NumberWithUnit(value, from_unit),
            Token::To,
            Token::NumberWithUnit(_, to_unit),
        ) = (&tokens[0], &tokens[1], &tokens[2])
        {
            let unit_value = UnitValue::new(*value, Some(from_unit.clone()));
            return unit_value.to_unit(to_unit);
        }

        // Handle percentage of value expressions like "10% of 50"
        if let (Token::NumberWithUnit(percentage, Unit::Percent), Token::Of, value_token) =
            (&tokens[0], &tokens[1], &tokens[2])
        {
            // Resolve the value token (could be number, unit, variable, or line reference)
            let base_value = match value_token {
                Token::Number(n) => UnitValue::new(*n, None),
                Token::NumberWithUnit(n, unit) => UnitValue::new(*n, Some(unit.clone())),
                Token::LineReference(line_index) => {
                    resolve_line_reference(*line_index, previous_results, current_line)?
                }
                Token::Variable(var_name) => resolve_variable(var_name, variables)?,
                _ => return None,
            };

            // Calculate percentage: convert percentage to decimal first, then multiply
            let percentage_decimal = Unit::Percent.to_base_value(*percentage);
            return Some(UnitValue::new(
                percentage_decimal * base_value.value,
                base_value.unit,
            ));
        }
    }

    // Check if we have an "in" or "to" conversion request at the end
    let mut target_unit_for_conversion = None;
    let mut evaluation_tokens = tokens;

    // Look for "in" or "to" followed by a unit at the end
    for i in 0..tokens.len().saturating_sub(1) {
        if let Token::In | Token::To = &tokens[i] {
            // Look for unit after "in" or "to"
            for j in (i + 1)..tokens.len() {
                if let Token::NumberWithUnit(_, unit) = &tokens[j] {
                    target_unit_for_conversion = Some(unit.clone());
                    evaluation_tokens = &tokens[..i]; // Evaluate everything before "in"/"to"
                    break;
                }
            }
            break;
        }
    }

    // Handle simple arithmetic with units
    let mut operator_stack = Vec::new();
    let mut value_stack = Vec::new();

    for token in evaluation_tokens {
        match token {
            Token::Number(n) => {
                value_stack.push(UnitValue::new(*n, None));
            }
            Token::NumberWithUnit(value, unit) => {
                value_stack.push(UnitValue::new(*value, Some(unit.clone())));
            }
            Token::LineReference(line_index) => {
                // Resolve line reference to its calculated result
                if let Some(line_result) =
                    resolve_line_reference(*line_index, previous_results, current_line)
                {
                    value_stack.push(line_result);
                } else {
                    return None; // Invalid or circular reference
                }
            }
            Token::Variable(var_name) => {
                // Resolve variable to its value
                if let Some(var_result) = resolve_variable(var_name, variables) {
                    value_stack.push(var_result);
                } else {
                    return None; // Undefined variable
                }
            }
            Token::Plus | Token::Minus | Token::Multiply | Token::Divide | Token::Power => {
                while let Some(top_op) = operator_stack.last() {
                    // Power is right-associative, others are left-associative
                    let should_pop = if matches!(token, Token::Power) {
                        // For right-associative operators, pop only if top has higher precedence
                        precedence_unit(token) < precedence_unit(top_op)
                    } else {
                        // For left-associative operators, pop if top has same or higher precedence
                        precedence_unit(token) <= precedence_unit(top_op)
                    };

                    if should_pop {
                        let op = operator_stack.pop().unwrap();
                        if !apply_operator_with_units(&mut value_stack, &op) {
                            return None;
                        }
                    } else {
                        break;
                    }
                }
                operator_stack.push(token.clone());
            }
            Token::LeftParen => {
                operator_stack.push(token.clone());
            }
            Token::RightParen => {
                // Process operators until we find a left paren or function
                while let Some(op) = operator_stack.pop() {
                    if matches!(op, Token::LeftParen) {
                        // Check if there's a function waiting
                        if let Some(Token::Function(func_name)) = operator_stack.last().cloned() {
                            operator_stack.pop(); // Remove the function
                            if !apply_function(&mut value_stack, &func_name) {
                                return None;
                            }
                        }
                        break;
                    }
                    if !apply_operator_with_units(&mut value_stack, &op) {
                        return None;
                    }
                }
            }
            Token::Function(_) => {
                // Functions are pushed to operator stack
                operator_stack.push(token.clone());
            }
            _ => {}
        }
    }

    while let Some(op) = operator_stack.pop() {
        if !apply_operator_with_units(&mut value_stack, &op) {
            return None;
        }
    }

    if value_stack.len() == 1 {
        let mut result = value_stack.pop().unwrap();

        // If we have a target unit for conversion, convert the result
        if let Some(target_unit) = target_unit_for_conversion {
            if let Some(converted) = result.to_unit(&target_unit) {
                result = converted;
            } else {
                return None; // Explicit conversion failed, fail the entire expression
            }
        }

        Some(result)
    } else {
        None
    }
}

/// Resolve a variable to its UnitValue
fn resolve_variable(var_name: &str, variables: &HashMap<String, String>) -> Option<UnitValue> {
    if let Some(var_value_str) = variables.get(var_name) {
        // Parse the variable value back into a UnitValue
        parse_result_string(var_value_str)
    } else {
        None
    }
}

/// Resolve a line reference to its calculated result
pub fn resolve_line_reference(
    line_index: usize,
    previous_results: &[Option<String>],
    current_line: usize,
) -> Option<UnitValue> {
    // Prevent circular references
    if line_index >= current_line {
        return None;
    }

    // Check if the referenced line exists and has a result
    if line_index < previous_results.len() {
        if let Some(result_str) = &previous_results[line_index] {
            // Parse the result string back into a UnitValue
            return parse_result_string(result_str);
        }
    }

    None
}

/// Parse a result string back into a UnitValue
pub fn parse_result_string(result_str: &str) -> Option<UnitValue> {
    // Parse a result string like "14 GiB" or "42" back into a UnitValue
    let parts: Vec<&str> = result_str.split_whitespace().collect();

    if parts.is_empty() {
        return None;
    }

    // Try to parse the first part as a number
    let number_str = parts[0].replace(",", ""); // Remove commas
    if let Ok(value) = number_str.parse::<f64>() {
        if parts.len() == 1 {
            // Just a number
            return Some(UnitValue::new(value, None));
        } else if parts.len() == 2 {
            // Number with unit
            if let Some(unit) = parse_unit(parts[1]) {
                return Some(UnitValue::new(value, Some(unit)));
            }
        }
    }

    None
}

/// Get operator precedence for unit-aware evaluation
fn precedence_unit(token: &Token) -> i32 {
    match token {
        Token::Plus | Token::Minus => 1,
        Token::Multiply | Token::Divide => 2,
        Token::Power => 3, // Highest precedence
        _ => 0,
    }
}

/// Apply an operator to two unit values
fn apply_operator_with_units(stack: &mut Vec<UnitValue>, op: &Token) -> bool {
    if stack.len() < 2 {
        return false;
    }

    let b = stack.pop().unwrap();
    let a = stack.pop().unwrap();

    let result = match op {
        Token::Plus => {
            // Addition: units must be compatible
            match (&a.unit, &b.unit) {
                (Some(unit_a), Some(unit_b)) => {
                    if unit_a.is_compatible_for_addition(unit_b) {
                        let base_a = unit_a.to_base_value(a.value);
                        let base_b = unit_b.to_base_value(b.value);
                        let result_base = base_a + base_b;

                        // Choose the smaller unit (larger value) for the result
                        let result_unit = if unit_a.to_base_value(1.0) < unit_b.to_base_value(1.0) {
                            unit_a
                        } else {
                            unit_b
                        };
                        let result_value = result_unit.clone().from_base_value(result_base);
                        UnitValue::new(result_value, Some(result_unit.clone()))
                    } else {
                        return false;
                    }
                }
                (None, None) => UnitValue::new(a.value + b.value, None),
                _ => return false, // Can't add number with unit and number without unit
            }
        }
        Token::Minus => {
            // Subtraction: units must be compatible
            match (&a.unit, &b.unit) {
                (Some(unit_a), Some(unit_b)) => {
                    if unit_a.is_compatible_for_addition(unit_b) {
                        let base_a = unit_a.to_base_value(a.value);
                        let base_b = unit_b.to_base_value(b.value);
                        let result_base = base_a - base_b;

                        // Choose the smaller unit (larger value) for the result
                        let result_unit = if unit_a.to_base_value(1.0) < unit_b.to_base_value(1.0) {
                            unit_a
                        } else {
                            unit_b
                        };
                        let result_value = result_unit.clone().from_base_value(result_base);
                        UnitValue::new(result_value, Some(result_unit.clone()))
                    } else {
                        return false;
                    }
                }
                (None, None) => UnitValue::new(a.value - b.value, None),
                _ => return false,
            }
        }
        Token::Multiply => {
            // Multiplication: special cases for units
            match (&a.unit, &b.unit) {
                // Time * Rate = Data (convert time to seconds first)
                (Some(time_unit), Some(rate_unit)) | (Some(rate_unit), Some(time_unit))
                    if time_unit.unit_type() == UnitType::Time
                        && (matches!(rate_unit.unit_type(), UnitType::DataRate { .. })) =>
                {
                    // Determine which value is time and which is rate
                    let (time_value, time_u, rate_value, rate_u) =
                        if time_unit.unit_type() == UnitType::Time {
                            (a.value, time_unit, b.value, rate_unit)
                        } else {
                            (b.value, time_unit, a.value, rate_unit)
                        };

                    let time_divider = match rate_unit.unit_type() {
                        UnitType::DataRate { time_multiplier } => time_multiplier,
                        _ => 1.0,
                    };

                    // Convert times to seconds
                    let time_in_seconds = time_u.to_base_value(time_value) / time_divider;

                    // Rate * time = data
                    let data_unit = match rate_u.to_data_unit() {
                        Ok(unit) => unit,
                        Err(_) => return false,
                    };
                    UnitValue::new(rate_value * time_in_seconds, Some(data_unit))
                }
                // Time * BitRate = Bits
                (Some(time_unit), Some(rate_unit)) | (Some(rate_unit), Some(time_unit))
                    if time_unit.unit_type() == UnitType::Time
                        && rate_unit.unit_type() == UnitType::BitRate =>
                {
                    // Check if this is a generic rate unit
                    if let Unit::RateUnit(rate_data, rate_time) = rate_unit {
                        // For generic rates, handle the time conversion properly
                        let (time_value, rate_value) = if time_unit.unit_type() == UnitType::Time {
                            (a.value, b.value)
                        } else {
                            (b.value, a.value)
                        };

                        // Convert time units to match
                        let time_in_rate_units = if time_unit == rate_time.as_ref() {
                            time_value
                        } else {
                            // Convert time to the rate's time unit
                            let time_in_seconds = time_unit.to_base_value(time_value);
                            rate_time.clone().from_base_value(time_in_seconds)
                        };

                        UnitValue::new(
                            rate_value * time_in_rate_units,
                            Some(rate_data.as_ref().clone()),
                        )
                    } else {
                        // Standard bit rate handling (per second)
                        let (time_value, time_u, rate_value, rate_u) =
                            if time_unit.unit_type() == UnitType::Time {
                                (a.value, time_unit, b.value, rate_unit)
                            } else {
                                (b.value, time_unit, a.value, rate_unit)
                            };

                        // Convert time to seconds
                        let time_in_seconds = time_u.to_base_value(time_value);

                        // BitRate * time = bits
                        let bit_unit = match rate_u.to_data_unit() {
                            Ok(unit) => unit,
                            Err(_) => return false,
                        };
                        UnitValue::new(rate_value * time_in_seconds, Some(bit_unit))
                    }
                }
                // Time * RequestRate = Requests (convert time to seconds first)
                (Some(time_unit), Some(rate_unit)) | (Some(rate_unit), Some(time_unit))
                    if time_unit.unit_type() == UnitType::Time
                        && rate_unit.unit_type() == UnitType::RequestRate =>
                {
                    // Determine which value is time and which is rate
                    let (time_value, time_u, rate_value, rate_u) =
                        if time_unit.unit_type() == UnitType::Time {
                            (a.value, time_unit, b.value, rate_unit)
                        } else {
                            (b.value, time_unit, a.value, rate_unit)
                        };

                    // Convert time to seconds
                    let time_in_seconds = time_u.to_base_value(time_value);

                    // RequestRate * time = requests
                    let request_unit = match rate_u.to_request_unit() {
                        Ok(unit) => unit,
                        Err(_) => return false,
                    };
                    UnitValue::new(rate_value * time_in_seconds, Some(request_unit))
                }
                // Data * Currency/Data Rate = Currency (e.g., 1 TiB * $5/GiB = $5120)
                (Some(data_unit), Some(Unit::RateUnit(rate_numerator, rate_denominator)))
                    if data_unit.unit_type() == UnitType::Data
                        && rate_numerator.unit_type() == UnitType::Currency
                        && rate_denominator.unit_type() == UnitType::Data =>
                {
                    // Convert data units to match the rate's denominator
                    let data_in_rate_units = if data_unit == rate_denominator.as_ref() {
                        a.value
                    } else {
                        // Convert data to the rate's data unit
                        let data_in_base = data_unit.to_base_value(a.value);
                        rate_denominator.clone().from_base_value(data_in_base)
                    };

                    UnitValue::new(
                        b.value * data_in_rate_units,
                        Some(rate_numerator.as_ref().clone()),
                    )
                }
                // Currency/Data Rate * Data = Currency (reverse order)
                (Some(Unit::RateUnit(rate_numerator, rate_denominator)), Some(data_unit))
                    if data_unit.unit_type() == UnitType::Data
                        && rate_numerator.unit_type() == UnitType::Currency
                        && rate_denominator.unit_type() == UnitType::Data =>
                {
                    // Convert data units to match the rate's denominator
                    let data_in_rate_units = if data_unit == rate_denominator.as_ref() {
                        b.value
                    } else {
                        // Convert data to the rate's data unit
                        let data_in_base = data_unit.to_base_value(b.value);
                        rate_denominator.clone().from_base_value(data_in_base)
                    };

                    UnitValue::new(
                        a.value * data_in_rate_units,
                        Some(rate_numerator.as_ref().clone()),
                    )
                }
                // Time * Generic Rate = Base Unit (for currency rates, etc.)
                (Some(time_unit), Some(rate_unit)) | (Some(rate_unit), Some(time_unit))
                    if time_unit.unit_type() == UnitType::Time =>
                {
                    // Check if this is a generic rate unit (exclude currency/data rates)
                    if let Unit::RateUnit(rate_data, rate_time) = rate_unit {
                        // Skip currency/data rates (they should be handled above)
                        if rate_data.unit_type() == UnitType::Currency
                            && rate_time.unit_type() == UnitType::Data
                        {
                            return false;
                        }
                        let (time_value, rate_value) = if time_unit.unit_type() == UnitType::Time {
                            (a.value, b.value)
                        } else {
                            (b.value, a.value)
                        };

                        // Convert time units to match
                        let time_in_rate_units = if time_unit == rate_time.as_ref() {
                            time_value
                        } else {
                            // Convert time to the rate's time unit
                            let time_in_seconds = time_unit.to_base_value(time_value);
                            rate_time.clone().from_base_value(time_in_seconds)
                        };

                        UnitValue::new(
                            rate_value * time_in_rate_units,
                            Some(rate_data.as_ref().clone()),
                        )
                    } else {
                        return false; // Not a generic rate
                    }
                }
                // Data * Time = Data (total transferred) - for specific data units
                (Some(data_unit), Some(time_unit)) | (Some(time_unit), Some(data_unit))
                    if data_unit.unit_type() == UnitType::Data
                        && time_unit.unit_type() == UnitType::Time =>
                {
                    UnitValue::new(a.value * b.value, Some(data_unit.clone()))
                }
                (Some(rate_unit), Some(Unit::Second)) | (Some(Unit::Second), Some(rate_unit))
                    if matches!(rate_unit.unit_type(), UnitType::DataRate { .. }) =>
                {
                    let data_unit = match rate_unit.to_data_unit() {
                        Ok(unit) => unit,
                        Err(_) => return false,
                    };
                    UnitValue::new(a.value * b.value, Some(data_unit))
                }
                (Some(unit), None) | (None, Some(unit)) => {
                    // Number * unit = unit
                    UnitValue::new(a.value * b.value, Some(unit.clone()))
                }
                (None, None) => UnitValue::new(a.value * b.value, None),
                _ => return false, // Unsupported unit combination
            }
        }
        Token::Divide => {
            match (&a.unit, &b.unit) {
                (Some(data_unit), Some(time_unit))
                    if data_unit.unit_type() == UnitType::Data
                        && time_unit.unit_type() == UnitType::Time =>
                {
                    // Check if time unit is seconds - if so, create traditional per-second rate
                    if time_unit == &Unit::Second {
                        // Data / seconds = traditional rate (for backwards compatibility)
                        let rate_unit = match data_unit.to_rate_unit() {
                            Ok(unit) => unit,
                            Err(_) => return false,
                        };
                        UnitValue::new(a.value / b.value, Some(rate_unit))
                    } else {
                        // Data / other time unit = generic rate
                        let rate_unit = Unit::RateUnit(
                            Box::new(data_unit.clone()),
                            Box::new(time_unit.clone()),
                        );
                        UnitValue::new(a.value / b.value, Some(rate_unit))
                    }
                }
                (Some(bit_unit), Some(time_unit))
                    if bit_unit.unit_type() == UnitType::Bit
                        && time_unit.unit_type() == UnitType::Time =>
                {
                    // Check if time unit is seconds - if so, create traditional per-second bit rate
                    if time_unit == &Unit::Second {
                        // Bit / seconds = traditional bit rate (for backwards compatibility)
                        let rate_unit = match bit_unit.to_rate_unit() {
                            Ok(unit) => unit,
                            Err(_) => return false,
                        };
                        UnitValue::new(a.value / b.value, Some(rate_unit))
                    } else {
                        // Bit / other time unit = generic bit rate
                        let rate_unit = rate_unit!(bit_unit.clone(), time_unit.clone());
                        UnitValue::new(a.value / b.value, Some(rate_unit))
                    }
                }
                (Some(request_unit), Some(time_unit))
                    if request_unit.unit_type() == UnitType::Request
                        && time_unit.unit_type() == UnitType::Time =>
                {
                    // Requests / time = request rate
                    // Convert time to seconds first
                    let time_in_seconds = time_unit.to_base_value(b.value);
                    let rate_unit = match request_unit.to_rate_unit() {
                        Ok(unit) => unit,
                        Err(_) => return false,
                    };
                    UnitValue::new(a.value / time_in_seconds, Some(rate_unit))
                }
                // Currency / Time = Currency Rate (generic rate)
                (Some(currency_unit), Some(time_unit))
                    if currency_unit.unit_type() == UnitType::Currency
                        && time_unit.unit_type() == UnitType::Time =>
                {
                    // Currency / time = currency rate
                    let rate_unit = Unit::RateUnit(
                        Box::new(currency_unit.clone()),
                        Box::new(time_unit.clone()),
                    );
                    UnitValue::new(a.value / b.value, Some(rate_unit))
                }
                // Currency / Data = Currency Rate (e.g., $/GiB)
                (Some(currency_unit), Some(data_unit))
                    if currency_unit.unit_type() == UnitType::Currency
                        && data_unit.unit_type() == UnitType::Data =>
                {
                    // Currency / data = currency/data rate
                    let rate_unit = Unit::RateUnit(
                        Box::new(currency_unit.clone()),
                        Box::new(data_unit.clone()),
                    );
                    UnitValue::new(a.value / b.value, Some(rate_unit))
                }
                // Data / DataRate = Time
                (Some(data_unit), Some(rate_unit))
                    if data_unit.unit_type() == UnitType::Data
                        && matches!(rate_unit.unit_type(), UnitType::DataRate { .. }) =>
                {
                    // Check if this is a generic rate unit
                    if let Unit::RateUnit(rate_data, rate_time) = rate_unit {
                        // For generic rates, we need to match the data units and return the time unit
                        if data_unit.unit_type() == rate_data.unit_type() {
                            // Convert both to base units
                            let data_base = data_unit.to_base_value(a.value);
                            let rate_data_base = rate_data.to_base_value(b.value);
                            if rate_data_base.abs() < FLOAT_EPSILON {
                                return false;
                            }
                            let time_value = data_base / rate_data_base;
                            UnitValue::new(time_value, Some(rate_time.as_ref().clone()))
                        } else {
                            return false;
                        }
                    } else {
                        // Standard per-second rate handling
                        let data_in_bytes = data_unit.to_base_value(a.value);
                        let rate_in_bytes_per_sec = rate_unit.to_base_value(b.value);
                        if rate_in_bytes_per_sec.abs() < FLOAT_EPSILON {
                            return false;
                        }
                        let time_in_seconds = data_in_bytes / rate_in_bytes_per_sec;
                        UnitValue::new(time_in_seconds, Some(Unit::Second))
                    }
                }
                // Data / BitRate = Time (need to convert between bits and bytes)
                (Some(data_unit), Some(rate_unit))
                    if data_unit.unit_type() == UnitType::Data
                        && rate_unit.unit_type() == UnitType::BitRate =>
                {
                    // Convert data to bytes and rate to bits per second
                    let data_in_bytes = data_unit.to_base_value(a.value);
                    let rate_in_bits_per_sec = rate_unit.to_base_value(b.value);
                    if rate_in_bits_per_sec.abs() < FLOAT_EPSILON {
                        return false;
                    }
                    // Convert bytes to bits (1 byte = 8 bits)
                    let data_in_bits = data_in_bytes * 8.0;
                    let time_in_seconds = data_in_bits / rate_in_bits_per_sec;
                    UnitValue::new(time_in_seconds, Some(Unit::Second))
                }
                // Bit / DataRate = Time (need to convert between bits and bytes)
                (Some(data_unit), Some(rate_unit))
                    if data_unit.unit_type() == UnitType::Bit
                        && matches!(rate_unit.unit_type(), UnitType::DataRate { .. }) =>
                {
                    // Convert data to bits and rate to bytes per second
                    let data_in_bits = data_unit.to_base_value(a.value);
                    let rate_in_bytes_per_sec = rate_unit.to_base_value(b.value);
                    if rate_in_bytes_per_sec.abs() < FLOAT_EPSILON {
                        return false;
                    }
                    // Convert bytes to bits (1 byte = 8 bits)
                    let rate_in_bits_per_sec = rate_in_bytes_per_sec * 8.0;
                    let time_in_seconds = data_in_bits / rate_in_bits_per_sec;
                    UnitValue::new(time_in_seconds, Some(Unit::Second))
                }
                // Bit / BitRate = Time
                (Some(data_unit), Some(rate_unit))
                    if data_unit.unit_type() == UnitType::Bit
                        && rate_unit.unit_type() == UnitType::BitRate =>
                {
                    // Convert data to bits and rate to bits per second
                    let data_in_bits = data_unit.to_base_value(a.value);
                    let rate_in_bits_per_sec = rate_unit.to_base_value(b.value);
                    if rate_in_bits_per_sec.abs() < FLOAT_EPSILON {
                        return false;
                    }
                    let time_in_seconds = data_in_bits / rate_in_bits_per_sec;
                    UnitValue::new(time_in_seconds, Some(Unit::Second))
                }
                (Some(rate_unit), Some(time_unit))
                    if rate_unit.unit_type() == UnitType::RequestRate
                        && time_unit.unit_type() == UnitType::Time =>
                {
                    // RequestRate / time = RequestRate (rate per unit time)
                    // This is a more complex case - dividing a rate by time
                    // For now, we'll treat this as invalid
                    return false;
                }
                // Compatible units divided = dimensionless ratio
                (Some(unit_a), Some(unit_b)) => {
                    // For currencies, only allow division of the exact same currency
                    if unit_a.unit_type() == UnitType::Currency && unit_a != unit_b {
                        return false; // Cannot divide different currencies without exchange rates
                    }

                    // Check if units are compatible (same unit type or bit/data conversion)
                    let compatible = unit_a.unit_type() == unit_b.unit_type()
                        || (unit_a.unit_type() == UnitType::Bit
                            && unit_b.unit_type() == UnitType::Data)
                        || (unit_a.unit_type() == UnitType::Data
                            && unit_b.unit_type() == UnitType::Bit);

                    if compatible {
                        // Convert both to base values and divide to get dimensionless ratio
                        let mut base_a = unit_a.to_base_value(a.value);
                        let mut base_b = unit_b.to_base_value(b.value);

                        // Handle bit/byte conversions: normalize to same base (bits)
                        if unit_a.unit_type() == UnitType::Data
                            && unit_b.unit_type() == UnitType::Bit
                        {
                            base_a *= 8.0; // Convert bytes to bits
                        } else if unit_a.unit_type() == UnitType::Bit
                            && unit_b.unit_type() == UnitType::Data
                        {
                            base_b *= 8.0; // Convert bytes to bits
                        }

                        if base_b.abs() < FLOAT_EPSILON {
                            return false;
                        }
                        let ratio = base_a / base_b;
                        UnitValue::new(ratio, None) // No unit = dimensionless
                    } else {
                        return false; // Incompatible unit types
                    }
                }
                (Some(unit), None) => {
                    // unit / number = unit
                    if b.value.abs() < FLOAT_EPSILON {
                        return false;
                    }
                    UnitValue::new(a.value / b.value, Some(unit.clone()))
                }
                (None, None) => {
                    if b.value.abs() < FLOAT_EPSILON {
                        return false;
                    }
                    UnitValue::new(a.value / b.value, None)
                }
                _ => return false,
            }
        }
        Token::Power => {
            // Exponentiation: only allowed for dimensionless values
            match (&a.unit, &b.unit) {
                (None, None) => {
                    // Both dimensionless - standard exponentiation
                    UnitValue::new(a.value.powf(b.value), None)
                }
                (Some(_unit), None) => {
                    // Base has unit, exponent is dimensionless
                    // Only allowed for certain cases (like square/cube)
                    if b.value == 2.0 || b.value == 3.0 {
                        // For now, disallow units with exponentiation
                        // Future: could support area/volume units
                        return false;
                    } else {
                        return false;
                    }
                }
                _ => return false, // Can't raise units to powers or use units as exponents
            }
        }
        _ => return false,
    };

    stack.push(result);
    true
}

/// Apply a function to the top value on the stack
fn apply_function(stack: &mut Vec<UnitValue>, func_name: &str) -> bool {
    if stack.is_empty() {
        return false;
    }

    let arg = stack.pop().unwrap();

    let result = match func_name {
        "sqrt" => {
            // Only allow sqrt for dimensionless values
            match &arg.unit {
                None => {
                    if arg.value < 0.0 {
                        return false; // Can't take square root of negative number
                    }
                    UnitValue::new(arg.value.sqrt(), None)
                }
                Some(_) => {
                    // For now, don't allow sqrt of values with units
                    // Future: could support area -> length conversions
                    return false;
                }
            }
        }
        _ => return false, // Unknown function
    };

    stack.push(result);
    true
}