# All Examples

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyErrorHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("An error has occurred!");
   Console.WriteLine($"Error #: {(int)uc.Error.Code}");
   Console.WriteLine($"Error Message: {uc.Error.Message}");
   Console.WriteLine($"Error Symbol: {uc.Error.Symbol}");
   Console.WriteLine($"Error Location: {uc.Error.Location}");
   Console.WriteLine($"Error Expression: {uc.Error.Expression}");
}


uc.Error.AddHandler(MyErrorHandler);
Console.WriteLine(uc.EvalStr("123+"));
Console.WriteLine("");

uc.Error.TrapOnDivideByZero = true;
Console.WriteLine(uc.EvalStr("5/0"));
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 2

**Description:** Getting data type object with DataTypeOf

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_8u).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_16u).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.Boolean).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.String).ToString("-1"));

Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_8u).Name);
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_32).ByteSize);
```

**Output:**
```
255
65535
true
-1
int8u
4
```

---

### Example ID: 3

**Description:** Returning the data type of an expression

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.DataTypeOf("10 + 20 - 3").Name);
Console.WriteLine(uc.DataTypeOf(" 'What type ' + 'is this?' ").Name);
Console.WriteLine(uc.DataTypeOf("3 < 10").Name);
Console.WriteLine(uc.DataTypeOf("5 + 7 * #i").Name);
Console.WriteLine("---");

uc.DefineFunction("func(x) as string = 'Hello' * 3");
Console.WriteLine(uc.DataTypeOf("func").Name);
Console.WriteLine(uc.DataTypeOf("Int").Name);
Console.WriteLine(uc.DataTypeOf("NonExistantType").Name); // Empty string
Console.WriteLine(uc.DataTypeOf("&&").Name);


```

**Output:**
```
double
string
bool
complex
---
string
int

bool
```

---

### Example ID: 4

**Description:** Setting/retrieving default data type

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Check default data type
Console.WriteLine(uc.DefaultDataType.Name);

// This examples shows setting the default data type in 3
// different ways: by BuiltInType enum, DataType ojbect,
// or data type by name (string)

// Change default default data type
uc.DefaultDataType = uc.DataTypeOf(BuiltInType.Integer_16);
Console.WriteLine(uc.DefaultDataType.Name);

// Test new default (returns integers instead of double)

uc.DefineFunction("ff(x, y) = (x + y)/3");
// same as ff(x As int16, y As int16) As int16 = ...

uc.DefineFunction("gg(x) = x*100");
// same as gg(x As int16) As int16 = ...

Console.WriteLine(uc.Eval("ff(4, 12)"));
Console.WriteLine(uc.Eval("gg(6.1)"));

uc.SetDefaultDataType("Single");
Console.WriteLine(uc.DefaultDataType.Name);

// Change back to original default (double)
uc.SetDefaultDataType(BuiltInType.Float_Double);

// Verify that default is now double
Console.WriteLine(uc.DefaultDataType.Name);
```

**Output:**
```
double
int16
5
600
single
double
```

---

### Example ID: 5

**Description:** Defining another function using the same callback address of existing one

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineFunction("MyRound(x)", uc.ItemOf("Floor").FunctionAddress);
Console.WriteLine(uc.Eval("MyRound(2.5)"));

uc.ItemOf("MyRound").SetFunctionAddress(uc.ItemOf("Ceil").FunctionAddress);
Console.WriteLine(uc.Eval("MyRound(2.5)"));
```

**Output:**
```
2
3
```

---

### Example ID: 6

**Description:** How to define a constant, variable, operator, function, output format, and token with Define()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine("------ Basic examples -------");
uc.Define("Function: f(x, y) = x + y");
uc.Define("Operator: {x} %% {y} = x * y");
uc.Define("Variable: MyVar = 123");

Console.WriteLine(uc.Eval("f(5, 10)"));
Console.WriteLine(uc.Eval("5 %% 10"));
Console.WriteLine(uc.Eval("MyVar * 100"));

// End users can also call Define()
Console.WriteLine("------ End user definition -------");
uc.Eval("Define('Function: ff(x) = x * 1000')");
Console.WriteLine(uc.Eval("ff(987)"));

Console.WriteLine("------ Boolean format -------");
Console.WriteLine(uc.EvalStr("1 < 2"));
Console.WriteLine(uc.EvalStr("1 > 2"));
Console.WriteLine(uc.EvalStr("Int(1 < 2)"));
Console.WriteLine(uc.EvalStr("(True Or False) And (True And False)"));
uc.Define("Boolean: 55, TotallyTrue, CompletelyFalse");
Console.WriteLine(uc.EvalStr("1 < 2"));
Console.WriteLine(uc.EvalStr("1 > 2"));
Console.WriteLine(uc.EvalStr("Int(1 < 2)"));
Console.WriteLine(uc.EvalStr("(TotallyTrue Or CompletelyFalse) And (TotallyTrue And CompletelyFalse)"));

// Format - configures the formatting for the output given by EvalStr
Console.WriteLine("------ Format -------");
uc.Define("Format: Result = 'Answer: <' + Result + '>'");
uc.Define("Format: String, val = 'String Value --> ' + val");
Console.WriteLine(uc.EvalStr("1+2"));
Console.WriteLine(uc.EvalStr("'Hello ' + 'world!'"));
var Additional = uc.Define("Format: ret = 'Additional format: ' + ret");
Console.WriteLine(uc.EvalStr("1+2"));
uc.Define("Format: InsertAt: 0, result = 'The ' + result");
Console.WriteLine(uc.EvalStr("1+2"));
Additional.Release();
Console.WriteLine(uc.EvalStr("1+2"));
uc.FormatRemove();

// Bootstrap - builds new def on top of existing one
Console.WriteLine("------ Bootstrap -------");
Console.WriteLine(uc.EvalStr("Hex(123)")); // uses "built-in" version of Hex()
var MyHex = uc.Define("Bootstrap ~~ Function: Hex(number As Int) As String = '0x' + UCase(Hex(number))");
Console.WriteLine(uc.EvalStr("Hex(123)"));
MyHex.Release();
Console.WriteLine(uc.EvalStr("Hex(123)"));

// Overwrite - useful for spreadsheet-like functionality
Console.WriteLine("------ Overwrite -------");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_A1() = 5");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()");
Console.WriteLine(uc.Eval("SpreadsheetCell_A1()"));
Console.WriteLine(uc.Eval("SpreadsheetCell_B2()"));
Console.WriteLine(uc.Eval("SpreadsheetCell_C3()"));
// SpreadsheetCell_C3() will be affected by the definition changes of SpreadsheetCell_A1() and  SpreadsheetCell_B3()
uc.Define("Overwrite ~~ Func: SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_A1() = 25");
Console.WriteLine("-------");
// Note: Empty parenthesis are optional for functions with no parameters
Console.WriteLine(uc.Eval("SpreadsheetCell_A1"));
Console.WriteLine(uc.Eval("SpreadsheetCell_B2"));
Console.WriteLine(uc.Eval("SpreadsheetCell_C3"));

// Lock
Console.WriteLine("------ Lock -------");
uc.Define("Variable: xy = 555");
uc.Define("Lock ~~ Variable: pi = 3.14"); // like using DefineConstant()
Console.WriteLine(uc.EvalStr("xy"));
Console.WriteLine(uc.EvalStr("pi"));
Console.WriteLine(uc.EvalStr("xy = 222")); // This variable is being changed
Console.WriteLine(uc.EvalStr("pi = 3.14159")); // This one is locked and cannot be changed
Console.WriteLine(uc.EvalStr("xy")); // Returns the new value of xy
Console.WriteLine(uc.EvalStr("pi")); // pi did not change; returns original value
Console.WriteLine("-------");
uc.Define("Function: f1(x) = x + 100");
uc.Define("Lock ~~ Function: f2(x) = x + 200"); // End-user can't change f2
Console.WriteLine(uc.Eval("f1(5)"));
Console.WriteLine(uc.Eval("f2(5)"));
uc.Eval("Define('Function: f1(x) = x + 300')");
uc.Eval("Define('Function: f2(x) = x + 400')"); // This re-definition is ignored
Console.WriteLine(uc.Eval("f1(5)"));
Console.WriteLine(uc.Eval("f2(5)"));

// Tokens
Console.WriteLine("------ Tokens -------");
Console.WriteLine(uc.EvalStr("5 + 4 // This comment causes an error"));
Console.WriteLine(uc.EvalStr("5 + /* comment not recognized yet */ 10"));
uc.Define("TokenType: Whitespace ~~ Token: //.*"); // // C-style to end-of-line comment
uc.Define("TokenType: Whitespace ~~ Token: /[*].*?[*]/"); // /* C-style enclosed comment */
Console.WriteLine(uc.EvalStr("5 + 4 // This comment will be ignored"));
Console.WriteLine(uc.EvalStr("5 + /* comment ignored */ 10"));

// Precedence
Console.WriteLine("------ Precedence -------");
uc.Define("Precedence: 1    ~~ Operator: {a As Int32} OpA {b As Int32} = a + b");
uc.Define("Precedence: 1000 ~~ Operator: {a As Int32} OpB {b As Int32} = a + b");
Console.WriteLine(uc.Eval("5 OpA 4 * 10"));
Console.WriteLine(uc.Eval("5 OpB 4 * 10"));

// Associativity
Console.WriteLine("------ Associativity -------");
uc.Define("Associativity: LeftToRight ~~ Operator: {x} OpX {y} = x / y");
uc.Define("Associativity: RightToLeft ~~ Operator: {x} OpY {y} = x / y");
Console.WriteLine(uc.Eval("3 OpX 4 OpX 5"));
Console.WriteLine(uc.Eval("3 OpY 4 OpY 5"));
```

**Output:**
```
------ Basic examples -------
15
50
12300
------ End user definition -------
987000
------ Boolean format -------
true
false
1
false
TotallyTrue
CompletelyFalse
55
CompletelyFalse
------ Format -------
Answer: <3>
Answer: <String Value --> Hello world!>
Answer: <Additional format: 3>
The Answer: <Additional format: 3>
The Answer: <3>
------ Bootstrap -------
7b
0x7B
7b
------ Overwrite -------
5
50
55
-------
25
2500
2525
------ Lock -------
555
3.14
222
Value cannot be assigned here
222
3.14
-------
105
205
305
205
------ Tokens -------
Undefined identifier
Undefined identifier
9
15
------ Precedence -------
45
90
------ Associativity -------
0.15
3.75
```

---

### Example ID: 8

**Description:** Defining a constant

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("MyVar = 10");
uc.DefineConstant("MyPi = 3.14");

Console.WriteLine(uc.Eval("MyVar"));
Console.WriteLine(uc.Eval("MyPi"));

uc.EvalStr("MyVar = 20"); // Attempt to change MyVar
Console.WriteLine(uc.Error.Message);

uc.EvalStr("MyPi = 25"); // Attempt to change MyPi
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.EvalStr("MyVar"));
Console.WriteLine(uc.EvalStr("MyPi"));
```

**Output:**
```
10
3.14
No error
Value cannot be assigned here
20
3.14
```

---

### Example ID: 10

**Description:** Miscellaneous end-user functions defined with DefineFunction()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine("---- Simple function def ----");
uc.DefineFunction("f(x) = x ^ 2 + 5");
Console.WriteLine(uc.Eval("f(10)"));

Console.WriteLine("---- Function overloading ----");
// Overloading based on parameter type or number of parameters
uc.DefineFunction("MyOverload(x As Double) = x + x");
uc.DefineFunction("MyOverload(x As String) As String = x + x");
uc.DefineFunction("MyOverload(x As String, y As String) As String = x + y");
uc.DefineFunction("MyOverload(x, y) = x + y");
Console.WriteLine(uc.EvalStr("MyOverload(5)"));
Console.WriteLine(uc.EvalStr("MyOverload('Ha')"));
Console.WriteLine(uc.EvalStr("MyOverload('Hello ', 'world!')"));
Console.WriteLine(uc.EvalStr("MyOverload(5, 10)"));

Console.WriteLine("---- Definition hiding/un-hiding ----");
// Shadowing (hiding) definitions
uc.DefineFunction("h(x) = x * 10");
Console.WriteLine(uc.Eval("h(3)"));
var hFunc = uc.DefineFunction("h(x) = x * 100"); // hides previous def
Console.WriteLine(uc.Eval("h(3)"));
hFunc.Release(); // Releasing this restores previous def
Console.WriteLine(uc.Eval("h(3)"));

Console.WriteLine("---- Optional parameters ----");
uc.DefineFunction("Opt(x, y = 5, z As String = 'Hello') = x + y + Length(z)");
Console.WriteLine(uc.Eval("Opt(10)"));
Console.WriteLine(uc.Eval("Opt(10, 20)"));
Console.WriteLine(uc.Eval("Opt(10, 20, 'Just a test 123')"));

Console.WriteLine("---- Recursion ----");
uc.DefineFunction("Factorial(x) = iif(x > 1, x * Factorial(x - 1), 1)");
uc.DefineFunction("Fib(n) = IIf(n < 2, n, Fib(n - 1) + Fib(n - 2))");
Console.WriteLine(uc.Eval("Factorial(5)"));
Console.WriteLine(uc.Eval("Fib(10)"));

// Bootstrap - builds new def on top of existing one
Console.WriteLine("------ Bootstrapping -------");
Console.WriteLine(uc.EvalStr("Hex(123)")); // uses "built-in" version of Hex()

var MyHex = uc.DefineFunction("Hex(number As Int) As String = '0x' + UCase(Hex(number))", bootstrap: true);

Console.WriteLine(uc.EvalStr("Hex(123)"));
MyHex.Release();
Console.WriteLine(uc.EvalStr("Hex(123)"));

// Overwrite - useful for spreadsheet-like functionality
Console.WriteLine("------ Overwrite -------");

uc.DefineFunction("SpreadsheetCell_A1() = 5", overwrite: true);
uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10", overwrite: true);
uc.DefineFunction("SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()", overwrite: true);

Console.WriteLine(uc.Eval("SpreadsheetCell_A1()"));
Console.WriteLine(uc.Eval("SpreadsheetCell_B2()"));
Console.WriteLine(uc.Eval("SpreadsheetCell_C3()"));
// SpreadsheetCell_C3() will be affected by the definition changes of SpreadsheetCell_A1() and  SpreadsheetCell_B3()

uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100", overwrite: true);
uc.DefineFunction("SpreadsheetCell_A1() = 25", overwrite: true);

Console.WriteLine("-------");
// Note: Empty parenthesis are optional for functions with no parameters
Console.WriteLine(uc.Eval("SpreadsheetCell_A1"));
Console.WriteLine(uc.Eval("SpreadsheetCell_B2"));
Console.WriteLine(uc.Eval("SpreadsheetCell_C3"));

// See Define() topic for more





```

**Output:**
```
---- Simple function def ----
105
---- Function overloading ----
10
HaHa
Hello world!
15
---- Definition hiding/un-hiding ----
30
300
30
---- Optional parameters ----
20
35
45
---- Recursion ----
120
55
------ Bootstrapping -------
7b
0x7B
7b
------ Overwrite -------
5
50
55
-------
25
2500
2525
```

---

### Example ID: 11

**Description:** How to define a custom function using a native callback.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyArea(uCalc.Callback cb) {
   // Retrieve the 1st and 2nd arguments passed to the function
   var Length = cb.Arg(1);
   var Width = cb.Arg(2);

   // Calculate the area and return the result to the uCalc engine.
   // This logic pattern translates seamlessly across languages.
   cb.Return(Length * Width); // Same as cb.ReturnDbl
}

uc.DefineFunction("Area(x, y)", MyArea);
Console.WriteLine(uc.Eval("Area(3, 4)"));
```

**Output:**
```
12
```

---

### Example ID: 12

**Description:** Defining a callback function with a variable number of arguments

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyAverage(uCalc.Callback cb) {
   double Total = 0;
   for (int x = 1; x <= cb.ArgCount(); x++) {
      Total = Total + cb.Arg(x);
   }
   cb.Return(Total / cb.ArgCount());
}

uc.DefineFunction("Average(x ...)", MyAverage);
Console.WriteLine(uc.Eval("Average(10, 3, 7, 4)"));
```

**Output:**
```
6
```

---

### Example ID: 13

**Description:** Passing arg ByHandle to retrieve meta data such as arg data type; and AnyType

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void DisplayArgs(uCalc.Callback cb) {
   for (int x = 1; x <= cb.ArgCount(); x++) {
      Console.WriteLine(cb.ArgItem(x).ValueStr() + "  Type: " + cb.ArgItem(x).DataType.Name);
   }
}

uc.DefineFunction("DisplayArgs(ByHandle Arg As AnyType ...)", DisplayArgs);
uc.Eval("DisplayArgs(5, 3+2*#i, 'Hello', True, False, Int16(5+4.1))");
```

**Output:**
```
5  Type: double
3+2i  Type: complex
Hello  Type: string
true  Type: bool
false  Type: bool
9  Type: int16
```

---

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MySum(uCalc.Callback cb) {
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for (double x = Start; x <= Finish; x++) {
      Variable.Value(x);
      Total += Expr.Evaluate();
   }
   cb.Return(Total);
}

uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
Console.WriteLine(uc.Eval("Sum(x ^ 2, 1, 10, x)"));

```

**Output:**
```
385
```

---

### Example ID: 15

**Description:** Returning a string (from a callback)

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void TwiceStr(uCalc.Callback cb) {
   cb.ReturnStr(cb.ArgStr(1) + cb.ArgStr(1));
}

uc.DefineFunction("Twice(Txt As String) As String", TwiceStr);
Console.WriteLine(uc.EvalStr("Twice('Bye')"));
```

**Output:**
```
ByeBye
```

---

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyFunction(uCalc.Callback cb) {
   var uc = cb.uCalc;
   Console.WriteLine("------ MyFunc ------");

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   Console.WriteLine(cb.ArgInt32(1));
   Console.WriteLine(cb.ArgInt64(2));

   // Retrieve the value of a pointer argument by referencing its exact data type.
   Console.WriteLine(uc.ItemOf("Int8").DataType.ToString(cb.ArgAddr(3)));

   // The Item object correctly identifies the type before conversion
   Console.WriteLine(uc.ItemOf("Int").DataType.ToString(cb.ArgPtr(4)));
}

static void MyFunction2(uCalc.Callback cb) {
   var uc = cb.uCalc;
   Console.WriteLine("------ MyFunc2 ------");
   Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_8).ToString(cb.ArgPtr(1)));
}

static void MyFunction3(uCalc.Callback cb) {
   var uc = cb.uCalc;
   Console.WriteLine("------ MyFunc3 ------");
   Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_16).ToString(cb.ArgPtr(1)));
}

uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

Console.WriteLine("MyVar = " + uc.EvalStr("MyVar"));
Console.WriteLine("MyInt = " + uc.EvalStr("MyInt"));
Console.WriteLine("MyStr = " + uc.EvalStr("MyStr"));
Console.WriteLine("OtherStr = " + uc.EvalStr("OtherStr"));
Console.WriteLine("MyInt16 = " + uc.EvalStr("MyInt16"));
Console.WriteLine("MyBool = " + uc.EvalStr("MyBool"));
Console.WriteLine("MyComplex = " + uc.EvalStr("MyComplex"));
Console.WriteLine("---");
Console.WriteLine(MyVar.Value());
Console.WriteLine(MyInt.ValueInt32());
Console.WriteLine(MyStr.ValueStr());
Console.WriteLine("---");
Console.WriteLine(uc.ItemOf("MyVar").DataType.Name);
Console.WriteLine(uc.ItemOf("MyInt").DataType.Name);
Console.WriteLine(uc.ItemOf("MyStr").DataType.Name);
Console.WriteLine(uc.ItemOf("OtherStr").DataType.Name);
Console.WriteLine(uc.ItemOf("MyInt16").DataType.Name);
Console.WriteLine(uc.ItemOf("MyBool").DataType.Name);
Console.WriteLine("---");

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

Console.Write("Expression = ");
Console.WriteLine(Expression);
for (int x = 1; x <= 10; x++) {
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   Console.WriteLine("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr());
}

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 18

**Description:** DefineVariable; using pointers

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var Int8Var = uc.DefineVariable("x As Int8 = -1");
var Int16Var = uc.DefineVariable("y As Int16 = -1");
var StrVar = uc.DefineVariable("MyStr = 'Hello there'");
Console.WriteLine(uc.EvalStr("x"));
Console.WriteLine(uc.EvalStr("y"));
Console.WriteLine(uc.EvalStr("MyStr"));

var xPtr = uc.DefineVariable("xPtr As Pointer"); // General pointer
var yPtr = uc.DefineVariable("yPtr As Int16u Ptr"); // pointer specific to unsigned Int16
var yPtrB = uc.DefineVariable("yPtrB As Int16 Ptr = AddressOf(y)"); // Using AddressOf
var StrPtr = uc.DefineVariable("StrPtr As String Ptr");
xPtr.ValuePtr(Int8Var.ValueAddr()); // Sets the pointer address
yPtr.ValuePtr(Int16Var.ValueAddr()); // Note: address of signed Int16 going to an unsigned Ptr
StrPtr.ValuePtr(StrVar.ValueAddr());

// Note: for the ints we are now returning unsigned values; so -1 turns into positive numbers
Console.WriteLine(uc.EvalStr("ValueAt(Int8u, xPtr)")); // Type required because it's defined as generar pointer
Console.WriteLine(uc.EvalStr("ValueAt(yPtr)")); // Type name not needed because it's defined as Int16u Ptr
Console.WriteLine(uc.EvalStr("ValueAt(yPtrB)"));
Console.WriteLine(uc.EvalStr("ValueAt(StrPtr)"));

// Iterate through uc.ItemOf(ItemIs.DataType, n).Name()
// to see data type names you can use with ValueAt

var OtherInt = uc.DefineVariable("OtherInt As Int16 = 1234");
uc.DataTypeOf(BuiltInType.Integer_16).SetScalar(Int16Var.ValueAddr(), OtherInt.ValueAddr());

Console.WriteLine(uc.EvalStr("OtherInt"));
Console.WriteLine(uc.EvalStr("ValueAt(yPtrB)"));





```

**Output:**
```
-1
-1
Hello there
255
65535
-1
Hello there
1234
1234
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng((float)1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

Console.WriteLine(MyVar.Value());
Console.WriteLine((int)ByteVar.ValueByte());
Console.WriteLine(Int16uVar.ValueInt16());
Console.WriteLine(Int32uVar.ValueInt32());
Console.WriteLine(Int64uVar.ValueInt64());
Console.WriteLine(SingleVar.ValueSng());
Console.WriteLine(DoubleVar.ValueDbl());
Console.WriteLine(StringVar.ValueStr());
Console.WriteLine("---");
Console.WriteLine("MyVar value: " + uc.EvalStr("MyVar"));
Console.WriteLine("ByteVar value: " + uc.EvalStr("ByteVar"));
Console.WriteLine("Int16uVar value: " + uc.EvalStr("Int16uVar"));
Console.WriteLine("Int32uVar value: " + uc.EvalStr("Int32uVar"));
Console.WriteLine("Int64uVar value: " + uc.EvalStr("Int64uVar"));
Console.WriteLine("SingleVar value: " + uc.EvalStr("SingleVar"));
Console.WriteLine("DoubleVar value: " + uc.EvalStr("DoubleVar"));
Console.WriteLine("StringVar value: " + uc.EvalStr("StringVar"));
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

### Example ID: 21

**Description:** Evaluating expressions

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// See EvalStr for more examples.

Console.WriteLine(uc.Eval("1+1"));
Console.WriteLine(uc.Eval("5*(3+9)^2"));
Console.WriteLine(uc.Eval("Length('This is a test')"));
```

**Output:**
```
2
720
14
```

---

### Example ID: 22

**Description:** How to perform a summation in a loop efficiently using Execute() instead of Evaluate().

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var VariableX = uc.DefineVariable("x = 0");
var Total = uc.DefineVariable("Total");
string Expression = "x++; Total = Total + x^2 + 5";

var ParsedExpr = uc.Parse(Expression);

for (double x = 1; x <= 10; x++) {
   // Execute() runs the parsed expression without the overhead of returning a value.
   // This provides near-native performance for loops across C#, VB, and C++.
   ParsedExpr.Execute();

   // Evaluate string interpolation to output the final calculated total
   Console.WriteLine(uc.EvalStr("$'{x}   Sub total = {Total}'"));
}

Console.WriteLine(uc.EvalStr("$'Total = {Total}'"));

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
1   Sub total = 6
2   Sub total = 15
3   Sub total = 29
4   Sub total = 50
5   Sub total = 80
6   Sub total = 121
7   Sub total = 175
8   Sub total = 244
9   Sub total = 330
10   Sub total = 435
Total = 435
```

---

### Example ID: 23

**Description:** Evaluating expressions returned as string

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 123");
uc.DefineVariable("y");

Console.WriteLine(uc.EvalStr("1 + 1"));
Console.WriteLine(uc.EvalStr("UCase('Hello ' + 'world!')"));
Console.WriteLine(uc.EvalStr("$'Interpolation: {2+3}'"));
Console.WriteLine(uc.EvalStr("#b101 + #hAE"));
Console.WriteLine(uc.EvalStr("Hex(1234)"));
Console.WriteLine(uc.EvalStr("(3+5*#i)^2"));
Console.WriteLine(uc.EvalStr("3 > 4"));
Console.WriteLine(uc.EvalStr("Max(5, 10, 3, -5)"));
Console.WriteLine(uc.EvalStr("x * 10"));
uc.EvalStr("x = 456");
Console.WriteLine(uc.EvalStr("x"));
Console.WriteLine(uc.EvalStr("2+4, 5+4, 10+20"));
Console.WriteLine(uc.EvalStr("y=100; ForLoop(x, 1, 10, 1, y = y + x); y"));
Console.WriteLine(uc.EvalStr("10 / "));
```

**Output:**
```
2
HELLO WORLD!
Interpolation: 5
179
4d2
-16+30i
false
10
1230
456
30
155
Syntax error
```

---

### Example ID: 24

**Description:** Finding the precedence level of an operator

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineOperator("{a As Bool} ## {b As Bool} As Bool = a And b", uc.ItemOf("And").Precedence);
Console.WriteLine(uc.EvalStr("true Or false ## 2 > 5"));

uc.ItemOf("##").SetPrecedence(uc.ItemOf("Or").Precedence);
Console.WriteLine(uc.EvalStr("true Or false ## 2 > 5"));
```

**Output:**
```
true
false
```

---

### Example ID: 25

**Description:** Setting variables of any data type

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var Int32Var = uc.DefineVariable("Int32Var As Int32");
var ByteVar = uc.DefineVariable("ByteVar As Byte");
var StrVar = uc.DefineVariable("StrVar As String");
var SngVar = uc.DefineVariable("SngVar As Single");

Int32Var.Value("4.25"); // Will be converted to integer
ByteVar.Value("-1");    // Will be converted to unsigned byte
StrVar.Value("'Test'");
SngVar.Value("1 + 0.25");

Console.WriteLine(uc.Eval("Int32Var"));
Console.WriteLine(uc.Eval("ByteVar"));
Console.WriteLine(uc.EvalStr("StrVar"));
Console.WriteLine(uc.EvalStr("SngVar"));

```

**Output:**
```
4
255
Test
1.25
```

---

### Example ID: 26

**Description:** Format using callback functions

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void OutputAnswerCB(uCalc.Callback cb) {
   cb.ReturnStr("Answer: " + cb.ArgStr(1));
}
static void OutputSymbolCB(uCalc.Callback cb) {
   cb.ReturnStr("==> " + cb.ArgStr(1));
}
static void OutputBoolCB(uCalc.Callback cb) {
   if (cb.ArgStr(1) == "false") {
      cb.ReturnStr("No");
   } else if (cb.ArgStr(1) == "true") {
      cb.ReturnStr("Yes");
   }
}


// This format inserts "Answer: " in front of every result
var OutputAnswer = uc.Format( OutputAnswerCB);
Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine("---");

// This one inserts ==> in front of the result
// The previously defined "Answer: " output is still prepended as well
var OutputSymbol = uc.Format( OutputSymbolCB);
Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine("---");

// Causes Boolean values to return Yes or No (instead of true or false)
var OutputBool = uc.Format( OutputBoolCB, "Bool");
Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine(uc.EvalStr("5 < 10"));
Console.WriteLine("---");

// The previously defined "==>" output is removed
OutputSymbol.Release();
Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine(uc.EvalStr("5 < 10"));
```

**Output:**
```
Answer: 30
Answer: Hello world
Answer: false
---
Answer: ==> 30
Answer: ==> Hello world
Answer: ==> false
---
Answer: ==> 30
Answer: ==> Hello world
Answer: ==> No
Answer: ==> Yes
---
Answer: 30
Answer: Hello world
Answer: No
Answer: Yes
```

---

### Example ID: 27

**Description:** Output formatting without using a callback

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// The output is surrounded by < and >, and prepended with Answer:
uc.Format("Result = 'Answer: <' + Result + '>'");

Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));

uc.FormatRemove();
```

**Output:**
```
Answer: <30>
Answer: <Hello world>
Answer: <false>
```

---

### Example ID: 28

**Description:** Different output formats for different data types

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// String results will be surrounded by << and >>, while Boolean will be surrounded by [[ and ]]
uc.Format("DataType: String, Def: val = '<<' + val + '>>' ");
uc.Format("Bool, val = '[[' + val + ']]'"); // Shortcut notation without "DataType" or "Def"

Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine(uc.EvalStr("5 < 10"));

uc.FormatRemove();
Console.WriteLine("---");
Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine(uc.EvalStr("5 < 10"));
```

**Output:**
```
30
<<Hello world>>
[[false]]
[[true]]
---
30
Hello world
false
true
```

---

### Example ID: 29

**Description:** Inserts formatting in specified sequence

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.Format("Result = 'Answer: ' + Result");
uc.Format("DataType: String, Def: val = '<<' + val + '>>' ");
uc.Format("DataType: Bool, Def: val = '[[' + val + ']]'");

// Note the difference between where "Bool: " and "String: " are displayed in the result
uc.Format("InsertAt: 0, DataType: Bool, Def: val = 'Bool: ' + val");  // Inserts at 0th position of Bool
uc.Format("InsertAt: 1, DataType: String, Def: val = 'String: ' + val"); // Inserts at 1st position of String
Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine("---");

// This fomratting will be the last one to take effect
uc.Format("InsertAt: 0, Def: val = 'Outer: ' + val");
Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine("---");

// This formatting will be the first one to take effect
uc.Format("val = 'Inner: ' + val"); // Optionally InsertAt: -1 could have been used
Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
Console.WriteLine("---");

uc.FormatRemove();

Console.WriteLine(uc.EvalStr("10+20"));
Console.WriteLine(uc.EvalStr("'Hello '+'world'"));
Console.WriteLine(uc.EvalStr("5 > 10"));
```

**Output:**
```
Answer: 30
Answer: String: <<Hello world>>
Bool: Answer: [[false]]
---
Outer: Answer: 30
Outer: Answer: String: <<Hello world>>
Outer: Bool: Answer: [[false]]
---
Outer: Answer: Inner: 30
Outer: Answer: String: <<Inner: Hello world>>
Outer: Bool: Answer: [[Inner: false]]
---
30
Hello world
false
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

Console.WriteLine("--- Efficient: Parse() once, then Evaluate() in a loop ---");
var ParsedExpr = uc.Parse(Expression);
for (double x = 1; x <= 10; x++) {
   VariableX.Value(x);
   Console.WriteLine(ParsedExpr.Evaluate());
}

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

### Example ID: 32

**Description:** Displaying Integer (Int32) results with Evaluate32

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var VariableX = uc.DefineVariable("x");

var ParsedExpr = uc.Parse("x / 2", "Integer"); // Causes output of "x / 2" to convert to an integer

// NOTE: EvaluateInt32 should only be used when Parse() explicitly specifies Integer
// (Or Int, or Int32) as the second argument, or if the expression evaluates to an integer
// (such as evaluating a variable that was explicitly defined as integer;
// other arithmetic operators typically evaluate to Double floating point).

for (double x = 1; x <= 10; x++) {
   VariableX.Value(x);
   Console.WriteLine("x = " + VariableX.ValueStr() + "  Result = " + (ParsedExpr.EvaluateInt32()).ToString());
}

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 0
x = 2  Result = 1
x = 3  Result = 1
x = 4  Result = 2
x = 5  Result = 2
x = 6  Result = 3
x = 7  Result = 3
x = 8  Result = 4
x = 9  Result = 4
x = 10  Result = 5
```

---

### Example ID: 33

**Description:** Doing an Eval in the same uCalc instance a variable belongs to

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var uc1 = new uCalc();
var uc2 = new uCalc();

var x1 = uc1.DefineVariable("x = 5");
var x2 = uc2.DefineVariable("x = 6");

Console.WriteLine(x1.uCalc.Eval("x*10")); // Same as uc1.Eval("x*10")
Console.WriteLine(x2.uCalc.Eval("x*10")); // Same as uc2.Eval("x*10")

uc1.Release();  // Since x1 is part of uc1, x1 is automatically released as well
uc2.Release();  // Since x2 is part of uc2, x2 is automatically released as well

// You should no longer use x1 or x2 because they were part of uc1 & uc2
// Don not try x1.uCalc().Eval("x*10"); or x2.uCalc().Eval("x*10");
```

**Output:**
```
50
60
```

---

### Example ID: 37

**Description:** Raising an error in a callback with ErrorRaise

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void RaiseErrorCallback(uCalc.Callback cb) {
   if (cb.Arg(1) == 123) {
      cb.Error.Raise(ErrorCode.Unrecognized_Command);
   }
   cb.Return(cb.Arg(1));
}


uc.DefineFunction("ErrRaiseTest(Value)", RaiseErrorCallback);
Console.WriteLine(uc.EvalStr("ErrRaiseTest(111)"));
Console.WriteLine(uc.EvalStr("ErrRaiseTest(123)")); // The callback arbitrarily raises an error for 123
```

**Output:**
```
111
Unrecognized command
```

---

### Example ID: 39

**Description:** Raises an error in a callback using a customized message with ErrorRaiseMessage

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void RaiseErrorMessageCallback(uCalc.Callback cb) {
   if (cb.Arg(1) == 123) {
      cb.Error.Raise("I do not like this value!");
      cb.Return(cb.Arg(1));
   }
}


uc.DefineFunction("ErrRaiseMsgTest(Value)", RaiseErrorMessageCallback);
Console.WriteLine(uc.EvalStr("ErrRaiseMsgTest(111)"));
Console.WriteLine(uc.EvalStr("ErrRaiseMsgTest(123)"));
```

**Output:**
```
111
I do not like this value!
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void ItemCallback(uCalc.Callback cb) {
   Console.WriteLine($"Name: {cb.Item.Name}");
   Console.WriteLine($"Data type: {cb.Item.DataType.Name}");
   Console.WriteLine($"Param count: {cb.Item.Count}");
   Console.Write("Procedure type: ");
   if (cb.Item.IsProperty(ItemIs.Operator)) {
      Console.WriteLine("Operator");
   } else if (cb.Item.IsProperty(ItemIs.Function)) {
      Console.WriteLine("Function");
   }
   Console.WriteLine(cb.Item.Text);
   Console.WriteLine(cb.Item.Description);
   Console.WriteLine("---");
}


uc.DefineFunction("AAA() As Double", ItemCallback).Description = "Does this and that";
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).Description = "Does something else";
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity.LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 41

**Description:** Displaying the data type of a parsed expression

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.Parse(" 3 + 6 * 10 ").DataType.Name);
Console.WriteLine(uc.Parse(" 'This ' + 'is a string' ").DataType.Name);
Console.WriteLine(uc.Parse(" 2 + 8 * #i / 2").DataType.Name);
Console.WriteLine(uc.Parse(" 10 + 2 > 3").DataType.Name);
```

**Output:**
```
double
string
complex
bool
```

---

### Example ID: 42

**Description:** Displaying strings with EvaluateStr()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var VariableX = uc.DefineVariable("x As Int32");
var MyStringVar = uc.DefineVariable("MyString = 'Hello world'");
var ParsedExpr = uc.Parse("SubStr(MyString, x, 1)");
var StrLength = uc.Eval("Length(MyString)");

for (int x = 0; x <= uc.Eval("Length(MyString) - 1"); x++) {
   VariableX.ValueInt32(x);
   Console.Write(ParsedExpr.EvaluateStr() + ".");
}
```

**Output:**
```
H.e.l.l.o. .w.o.r.l.d.
```

---

### Example ID: 43

**Description:** Displaying complex number outputs with EvaluateStr()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var VariableX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse("x * #i + 5", "Complex");

for (double x = 1; x <= 10; x++) {
   VariableX.Value(x);
   // Note: EvaluateStr works with any data type;
   Console.WriteLine(uc.EvalStr("$'x = {x}  Result = '") + ParsedExpr.EvaluateStr());
}

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 5+1i
x = 2  Result = 5+2i
x = 3  Result = 5+3i
x = 4  Result = 5+4i
x = 5  Result = 5+5i
x = 6  Result = 5+6i
x = 7  Result = 5+7i
x = 8  Result = 5+8i
x = 9  Result = 5+9i
x = 10  Result = 5+10i
```

---

### Example ID: 44

**Description:** Displaying an expression of unsigned byte as a signed byte by using a Pointer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var VariableX = uc.DefineVariable("x As Int");
var ParsedExpr = uc.Parse("x + 125", "Int8u");

for (int x = 1; x <= 10; x++) {
   VariableX.ValueInt32(x);
   Console.WriteLine($"x = {x}  Int8 result = {uc.ValueAt(ParsedExpr.EvaluateVoid(), "Int8")}");
}

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Int8 result = 126
x = 2  Int8 result = 127
x = 3  Int8 result = -128
x = 4  Int8 result = -127
x = 5  Int8 result = -126
x = 6  Int8 result = -125
x = 7  Int8 result = -124
x = 8  Int8 result = -123
x = 9  Int8 result = -122
x = 10  Int8 result = -121
```

---

### Example ID: 45

**Description:** ItemOf selection between infix version of - (minus) operator and unary prefix version with Properties

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// Returns number of operands for the given operators
Console.WriteLine(uc.ItemOf("-", uCalc.Properties(ItemIs.Infix)).Count);
Console.WriteLine(uc.ItemOf("-", uCalc.Properties(ItemIs.Prefix)).Count);

// You can pass one property directly in C++ and C#, but not VB
Console.WriteLine(uc.ItemOf("-", ItemIs.Infix).Count);
Console.WriteLine(uc.ItemOf("-", ItemIs.Prefix).Count);

```

**Output:**
```
2
1
2
1
```

---

### Example ID: 46

**Description:** Dispaying the number of elements in an array

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyAverage(uCalc.Callback cb) {
   double Total = 0;
   for (int x = 1; x <= cb.ArgCount(); x++) {
      Total = Total + cb.Arg(x);
   }
   cb.Return(Total / cb.ArgCount());
}

var MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}");
var MyArrayB = uc.DefineVariable("MyArrayB[15]");
var FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z");
var FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b");
var FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage);
var FunctionD = uc.DefineFunction("FuncD() = 1+1");

Console.WriteLine($"Elements in MyArrayA: {MyArrayA.Count}");
Console.WriteLine($"Elements in MyArrayB: {MyArrayB.Count}");
Console.WriteLine($"Params in FuncA(): {FunctionA.Count}");
Console.WriteLine($"Params in FuncB(): {FunctionB.Count}");
Console.WriteLine($"Params in FuncC(): {FunctionC.Count}"); // -1 or 2^n-1 (n=32 or 64)
Console.WriteLine($"Params in FuncD(): {FunctionD.Count}");
Console.WriteLine($"Operands in ! operator: {uc.ItemOf("!").Count}");
Console.WriteLine($"Operands in > operator: {uc.ItemOf(">").Count}");
```

**Output:**
```
Elements in MyArrayA: 5
Elements in MyArrayB: 15
Params in FuncA(): 3
Params in FuncB(): 4
Params in FuncC(): -1
Params in FuncD(): 0
Operands in ! operator: 1
Operands in > operator: 2
```

---

### Example ID: 47

**Description:** Determining whether items are functions, or arrays, etc.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("MyVar");

Console.WriteLine($"{uc.EvalStr("'Cos is a function? '")}{uc.ItemOf("Cos").IsProperty(ItemIs.Function)}");
Console.WriteLine($"{uc.EvalStr("'Cos is a variable? '")}{uc.ItemOf("Cos").IsProperty(ItemIs.Variable)}");
Console.WriteLine($"{uc.EvalStr("'Cos is an operator? '")}{uc.ItemOf("Cos").IsProperty(ItemIs.Operator)}");
Console.WriteLine($"{uc.EvalStr("'MyVar is a function? '")}{uc.ItemOf("MyVar").IsProperty(ItemIs.Function)}");
Console.WriteLine($"{uc.EvalStr("'MyVar is a variable? '")}{uc.ItemOf("MyVar").IsProperty(ItemIs.Variable)}");
Console.WriteLine($"{uc.EvalStr("'MyVar is an operator? '")}{uc.ItemOf("MyVar").IsProperty(ItemIs.Operator)}");
Console.WriteLine($"{uc.EvalStr("'+ is a function? '")}{uc.ItemOf("+").IsProperty(ItemIs.Function)}");
Console.WriteLine($"{uc.EvalStr("'+ is a variable? '")}{uc.ItemOf("+").IsProperty(ItemIs.Variable)}");
Console.WriteLine($"{uc.EvalStr("'+ is an operator? '")}{uc.ItemOf("+").IsProperty(ItemIs.Operator)}");
Console.WriteLine($"{uc.EvalStr("'Cos not found? '")}{uc.ItemOf("Cos").IsProperty(ItemIs.NotFound)}");
Console.WriteLine($"{uc.EvalStr("'XYZABC not found? '")}{uc.ItemOf("XYZABC").IsProperty(ItemIs.NotFound)}");
```

**Output:**
```
Cos is a function? True
Cos is a variable? False
Cos is an operator? False
MyVar is a function? False
MyVar is a variable? True
MyVar is an operator? False
+ is a function? False
+ is a variable? False
+ is an operator? True
Cos not found? False
XYZABC not found? True
```

---

### Example ID: 48

**Description:** Renames the Cos function (which is in Radian) to CosR and defines Cos in Degrees

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineConstant("pi = Atan(1) * 4");

// Original Cosine behavior with Radian
Console.WriteLine(uc.EvalStr("Cos(pi)"));
Console.WriteLine(uc.EvalStr("Cos(180)"));

// Cos is renamed to CosR so that Cos can now be defined in Degree
uc.ItemOf("Cos").Rename("CosR");
uc.DefineFunction("Cos(x) = CosR(x*pi/180)");

// Now Cos is in Degree
Console.WriteLine(uc.EvalStr("Cos(pi)"));
Console.WriteLine(uc.EvalStr("Cos(180)"));

// This is the original function now named CosR
Console.WriteLine(uc.EvalStr("CosR(pi)"));
Console.WriteLine(uc.EvalStr("CosR(180)"));
// Note: Some functions may be overloaded, such as the Cos function in
// this example, which has a definition for Double and another for Complex.
// This example renames only the Double precision version.
// You can use NextOverload() and DataType() to pinpoint the one you want
```

**Output:**
```
-1
-0.59846006905785
0.99849714986386
-1
-1
-0.59846006905785
```

---

### Example ID: 49

**Description:** Setting a variable value by pointer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var x = uc.DefineVariable("x = 123");
var y = uc.DefineVariable("y");

y.ValueByPtr(x.ValueAddr());

Console.WriteLine(uc.Eval("x"));
Console.WriteLine(uc.Eval("y"));
```

**Output:**
```
123
123
```

---

### Example ID: 50

**Description:** Displaying the data type name and size of a variable

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyVariable = uc.DefineVariable("MyVariable");
Console.WriteLine("MyVariable type: " + MyVariable.DataType.Name);
Console.WriteLine($"MyVariable size: {MyVariable.DataType.ByteSize}");
```

**Output:**
```
MyVariable type: double
MyVariable size: 8
```

---

### Example ID: 51

**Description:** Returning data type names for the different definitions of the "+" operator

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var PlusOperator = uc.ItemOf("+");

while (PlusOperator.NotEmpty()) {
   Console.WriteLine("Def: " + PlusOperator.Text + "  Type: " + PlusOperator.DataType.Name);
   PlusOperator = PlusOperator.NextOverload();
}
```

**Output:**
```
Def: Operator: 70 +{x}  Type: double
Def: Operator: 50 {x} + {y}  Type: double
Def: Operator: 50 {x As Int} + {y As Int} As Int  Type: int
Def: Operator: 50 {x As String} + {y As String} As String  Type: string
Def: Operator: 50 {x As Complex} + {y As Complex} As Complex  Type: complex
Def: Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr  Type: sametypeas:ptr
Def: Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String  Type: string
Def: Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String  Type: string
```

---

### Example ID: 52

**Description:** Inspecting the parts of a syntax construct

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineFunction("MyFunction(x) = x * 2");
Console.WriteLine(uc.ItemOf("MyFunction").Text);
```

**Output:**
```
Function: MyFunction(x) = x * 2
```

---

### Example ID: 54

**Description:** Error handler to auto-define variables

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// This error handler allows you to use variables that were not
// explicitly defined previously, by defining the unrecognized identifiers
// as variables instead of returning an error
static void AutoVariableDef(Handle_uCalc h) {
   var uc = new uCalc(h);
   if (uc.Error.Code == ErrorCode.Undefined_Identifier) {
      uc.DefineVariable(uc.Error.Symbol);
      uc.Error.Response = ErrorHandlerResponse.Resume;
   }
}


uc.Error.AddHandler(AutoVariableDef);
Console.WriteLine(uc.Eval("AutoTest = 123"));
Console.WriteLine(uc.Eval("AutoTest * 1000"));
```

**Output:**
```
123
123000
```

---

### Example ID: 55

**Description:** Error handler order

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void ErrorHandlerA(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("Handler A called");
}

static void ErrorHandlerB(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("Handler B called");
}

static void ErrorHandlerC(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("Handler C called");
}

static void ErrorHandlerD(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("Handler D called");
}

static void ErrorHandlerE(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("Handler E called");
}


uc.Error.AddHandler(ErrorHandlerA);
uc.Error.AddHandler(ErrorHandlerB);
uc.Error.AddHandler(ErrorHandlerC);
uc.Error.AddHandler(ErrorHandlerD, -1);
uc.Error.AddHandler(ErrorHandlerE, 3);

Console.WriteLine(uc.EvalStr("10 / "));
```

**Output:**
```
Handler C called
Handler B called
Handler A called
Handler E called
Handler D called
Syntax error
```

---

### Example ID: 56

**Description:** Alias using symbol object

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyVar = uc.DefineVariable("MyVar = 123");
var MyAlias = uc.CreateAlias("MyAlias", MyVar);

Console.WriteLine(uc.Eval("MyAlias")); // Contains same value as MyVar
uc.Eval("MyAlias = 456"); // Same as changing MyVar
Console.WriteLine(uc.EvalStr("MyVar")); // MyVar reflects change made in MyAlias
Console.WriteLine("");


// This section below shows how you can have Alias distinguish
// between different variables with the same name

uc.DefineFunction("MyFunc() = MyVar + 1");

// MyVar defined below is a new variable sharing the same name
// MyFunc() will still use the value of the original MyVar
var MyVarAlt = uc.DefineVariable("MyVar = 100");

// The function below uses the new MyVar variable
uc.DefineFunction("MyFunc2() = MyVar + 1");

Console.WriteLine(uc.Eval("MyFunc()"));
Console.WriteLine(uc.Eval("MyFunc2()"));
Console.WriteLine("");

uc.CreateAlias("MyAliasAlt", MyVarAlt);
uc.Eval("MyAlias = 200"); // Changes MyVar used in MyFunc()
uc.Eval("MyAliasAlt = 300"); // Changes MyVar used in MyFunc2()

Console.WriteLine(uc.Eval("MyFunc()"));
Console.WriteLine(uc.Eval("MyFunc2()"));
```

**Output:**
```
123
456

457
101

201
301
```

---

### Example ID: 57

**Description:** Simple alias

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 10");

// Create alias: y behaves exactly like x
uc.CreateAlias("y", "x");

Console.WriteLine(uc.Eval("y + 5"));
```

**Output:**
```
15
```

---

### Example ID: 58

**Description:** Creating alternative names for Define commands

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.CreateAlias("VariableDefinition", "Variable", true);
uc.CreateAlias("Method", "Function", true);

uc.Define("VariableDefinition: MyVar = 123");
uc.Define("Method: MyFunc(x) = x * 10");

Console.WriteLine(uc.Eval("MyVar"));
Console.WriteLine(uc.Eval("MyFunc(5)"));
```

**Output:**
```
123
50
```

---

### Example ID: 59

**Description:** Creating a clone of a uCalc object

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

uc.DefineVariable("MyVar = 100");
uc.DefineFunction("MyFunc(x) = x + 1");

var Cloned_uc = uc.Clone();

Console.WriteLine(uc.EvalStr("MyVar"));
Console.WriteLine(uc.EvalStr("MyFunc(10)"));

Console.WriteLine(Cloned_uc.EvalStr("MyVar"));
Console.WriteLine(Cloned_uc.EvalStr("MyFunc(10)"));

Cloned_uc.Eval("MyVar = 200");
Cloned_uc.DefineFunction("OtherFunc(x) = x * 10");

Console.WriteLine(uc.EvalStr("MyVar"));
Console.WriteLine(uc.EvalStr("OtherFunc(5)"));

Console.WriteLine(Cloned_uc.EvalStr("MyVar"));
Console.WriteLine(Cloned_uc.EvalStr("OtherFunc(5)"));
```

**Output:**
```
100
11
100
11
100
Undefined identifier
200
50
```

---

### Example ID: 60

**Description:** Using the default uCalc.GetDefaultInstance() instance

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uCalc.DefaultInstance.DefineVariable("instance = 'original default'");

var ucB = new uCalc();
var ucC = new uCalc();
var ucD = new uCalc();

ucB.Eval("instance = 'B derived from -> ' + instance");
ucC.Eval("instance = 'C derived from -> ' + instance");
ucD.Eval("instance = 'D derived from -> ' + instance");

ucC.IsDefault = true;

var ucE = new uCalc();
ucE.Eval("instance = 'E derived from -> ' + instance");

Console.WriteLine(uCalc.DefaultInstance.EvalStr("'Default: ' + instance"));

Console.WriteLine(uc.EvalStr("instance")); // Note: this is not, nor was the default
Console.WriteLine(ucB.EvalStr("instance"));
Console.WriteLine(ucC.EvalStr("instance"));
Console.WriteLine(ucD.EvalStr("instance"));
Console.WriteLine(ucE.EvalStr("instance"));

// Note: Unlike this example, it is generally best to always
// create a new instance first and then set it as default
```

**Output:**
```
Default: C derived from -> original default
Undefined identifier
B derived from -> original default
C derived from -> original default
D derived from -> original default
E derived from -> C derived from -> original default
```

---

### Example ID: 61

**Description:** Setting default uCalc instance with uCalc.IsDefault(); also clearing all uCalc instances from default list

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uCalc.DefaultInstance.DefineVariable("val = 'original default'");
Console.WriteLine(uCalc.DefaultInstance.EvalStr("val"));

uc.DefineVariable("val = 'uc'");
uc.IsDefault = true;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("val"));

var ucB = new uCalc();
ucB.DefineVariable("val = 'ucB'");
ucB.IsDefault = true;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("val"));

var ucC = new uCalc();
ucC.DefineVariable("val = 'ucC'");
ucC.IsDefault = true;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("val"));

uCalc.DefaultClear();

// The original unnamed default instance is reset so user variable val no longer exists
Console.WriteLine(uCalc.DefaultInstance.EvalStr("val"));

// The other instances are removed from Default list but remain active
Console.WriteLine(uc.EvalStr("val"));
Console.WriteLine(ucB.EvalStr("val"));
Console.WriteLine(ucC.EvalStr("val"));
```

**Output:**
```
original default
uc
ucB
ucC
Undefined identifier
uc
ucB
ucC
```

---

### Example ID: 62

**Description:** Number of uCalc instances on the default uCalc instance list

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uCalc.DefaultCount);

uc.IsDefault = true;
Console.WriteLine(uCalc.DefaultCount);

var ucB = new uCalc();
ucB.IsDefault = true;
Console.WriteLine(uCalc.DefaultCount);

var ucC = new uCalc();
ucC.IsDefault = true;
Console.WriteLine(uCalc.DefaultCount);

uCalc.DefaultClear();
Console.WriteLine(uCalc.DefaultCount);
```

**Output:**
```
1
2
3
4
1
```

---

### Example ID: 64

**Description:** Operator definitions; infix, prefix, postfix, data types, precedence

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineOperator("{x} MyOp {y} = x + y", 0); // Infix operator with alphanumeric name
uc.DefineOperator("@@ {number} = number * 2", 0); // Prefix operator with symbolic name
uc.DefineOperator("{val} % = val / 100", 0); // Postfix operator with symbolic name
uc.DefineOperator("{a} times {b} = a * b", uc.ItemOf("*").Precedence); // Specifying precedence
uc.DefineOperator("{TextA As String} concat {TextB As String} As String = TextA + TextB", 0); // Specifying types

Console.WriteLine(uc.Eval("5 MyOp 4"));
Console.WriteLine(uc.Eval("@@5"));
Console.WriteLine(uc.Eval("5 %"));
Console.WriteLine(uc.Eval("3 times 5"));
Console.WriteLine(uc.EvalStr("'Hello' concat ' world!'"));
```

**Output:**
```
9
10
0.05
15
Hello world!
```

---

### Example ID: 66

**Description:** Operator ByRef, AnyType, SameTypeAs, Precedence, RightToLeft, callback

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void AssignValueA(uCalc.Callback cb) {
   cb.uCalc.DataTypeOf(BuiltInType.Integer_64).SetScalar(cb.ArgPtr(1), cb.ArgAddr(2));
   // C++ can do it with pointers instead like the commented line below:
   // *(int64_t *)cb.ArgInt64(1) = cb.ArgInt64(2);
}
static void AssignValueB(uCalc.Callback cb) {
   if (cb.ArgItem(1).DataType.BuiltInTypeEnum == BuiltInType.String) {
      cb.ArgItem(1).ValueStr(cb.ArgItem(2).ValueStr());
   } else {
      cb.ArgItem(1).DataType.SetScalar(cb.ArgItem(1).ValueAddr(), cb.ArgItem(2).ValueAddr());
   }
}


// ByRef approach (only for primitive types only, like double, int, etc., not composite types like strings)
Console.WriteLine("-- ByRef approach --");
uc.DefineOperator("{ByRef variable As AnyType} SetValA {value As SameTypeAs:0} As SameTypeAs:0", uc.ItemOf("=").Precedence, Associativity.RightToLeft, AssignValueA);
uc.DefineVariable("MyDbl As Double");
uc.DefineVariable("MyInt As Int");
uc.DefineVariable("MyStr As String");

uc.Eval("MyDbl SetValA 3.14");
uc.Eval("MyInt SetValA Int(3.14 * 10)");

Console.WriteLine("MyDbl: " + uc.EvalStr("MyDbl"));
Console.WriteLine("MyInt: " + uc.EvalStr("MyInt"));

// ByHandle approach
Console.WriteLine("-- ByHandle approach --");
uc.DefineOperator("{ByHandle variable As AnyType} SetValB {ByHandle val As SameTypeAs:0}", uc.ItemOf("=").Precedence, Associativity.RightToLeft, AssignValueB);
uc.Eval("MyDbl SetValB 123.456");
uc.Eval("MyInt SetValB Int(555.123)");
uc.Eval("MyStr SetValB 'Hello World'");

Console.WriteLine("MyDbl: " + uc.EvalStr("MyDbl"));
Console.WriteLine("MyInt: " + uc.EvalStr("MyInt"));
Console.WriteLine("MyStr: " + uc.EvalStr("MyStr"));

```

**Output:**
```
-- ByRef approach --
MyDbl: 3.14
MyInt: 31
-- ByHandle approach --
MyDbl: 123.456
MyInt: 555
MyStr: Hello World
```

---

### Example ID: 67

**Description:** Arrays with DefineVariable

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyArray = uc.DefineVariable("MyArray[3]");
uc.DefineVariable("MyArrayStr[] = {'aa', 'bb', 'cc'}");

uc.Eval("MyArray[0] = 111; MyArray[1] = 222; MyArray[2] = 333");

Console.WriteLine(uc.EvalStr("MyArray[0]"));
Console.WriteLine(uc.EvalStr("MyArray[1]"));
Console.WriteLine(uc.EvalStr("MyArray[2]"));
Console.WriteLine(uc.EvalStr("MyArrayStr[0]"));
Console.WriteLine(uc.EvalStr("MyArrayStr[1]"));
Console.WriteLine(uc.EvalStr("MyArrayStr[2]"));
Console.WriteLine(MyArray.Count);
Console.WriteLine(uc.ItemOf("MyArrayStr").Count);
```

**Output:**
```
111
222
333
aa
bb
cc
3
3
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Lists all tokens currently defined for the expression evaluator.

Console.WriteLine($"Token Count: {uc.ExpressionTokens.Count}");
Console.WriteLine("");
Console.WriteLine("Index  Type  Name: regex");
Console.WriteLine("========================");
var Tokens = uc.ExpressionTokens;
foreach(var token in Tokens) {
   Console.Write(Tokens.IndexOf(token));
   Console.WriteLine($"  {token.Description}  {token.Name}: {token.Regex}");
}

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

### Example ID: 71

**Description:** Change characters accepted as alphanumeric in expressions using ExpressionTokens() & Token()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// (See alternate version of this example using ItemOf instead of ExpressionTokens)

// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("Variable123 = 222");
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.ExpressionTokens[TokenType.AlphaNumeric].Regex);
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");

// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z]+";

uc.DefineVariable("Other_Variable = 333");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("OtherVariable123 = 444");
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.EvalStr("Other_Variable"));
Console.WriteLine(uc.EvalStr("OtherVariable123 "));
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");

// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z_][a-zA-Z0-9_]*";
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
```

**Output:**
```
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
```

---

### Example ID: 72

**Description:** Changing accepted tokens with ItemOf().Regex or ExpressionTokens().Token

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// (See alternate version of this example using ExpressionTokens instead of ItemOf)

// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("Variable123 = 222");
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.ItemOf("_Token_Alphanumeric").Regex);
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");

// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ItemOf("_Token_Alphanumeric").Regex = "[a-zA-Z]+";

uc.DefineVariable("Other_Variable = 333");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("OtherVariable123 = 444");
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.EvalStr("Other_Variable"));
Console.WriteLine(uc.EvalStr("OtherVariable123 "));
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");

//
// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
// Also: We can't use the commented line below because it has the underscore, _,
// character that we had removed.
// uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*");
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z_][a-zA-Z0-9_]*";
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
```

**Output:**
```
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
```

---

### Example ID: 73

**Description:** Using ExpressionTransformer to transform expressions before they are parsed

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var ExprT = uc.ExpressionTransformer;  // Transformer used for Eval() and Evaluate()

var p1 = ExprT.FromTo("AddUp({x})", "{x}"); // RewindOnChange False by default
var p2 = ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").SetRewindOnChange(true);

Console.WriteLine($"p1 RewindOnChange: {p1.RewindOnChange}");
Console.WriteLine($"p2 RewindOnChange: {p2.RewindOnChange}");

Console.WriteLine("");

Console.WriteLine($"Input: AddUp(1,2,3,4)");
Console.WriteLine($"Transform: {ExprT.Transform("AddUp(1,2,3,4)")}");
Console.WriteLine($"Eval: {uc.Eval("AddUp(1,2,3,4)")}");
```

**Output:**
```
p1 RewindOnChange: False
p2 RewindOnChange: True

Input: AddUp(1,2,3,4)
Transform: (1 + (2 + (3 + 4)))
Eval: 10
```

---

### Example ID: 74

**Description:** Raising floating point errors with FloatingPointErrorsToTrap

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.Error.FloatingPointErrorsToTrap);
Console.WriteLine(uc.EvalStr("1/0"));
Console.WriteLine(uc.EvalStr("0/0"));
Console.WriteLine(uc.EvalStr("5*10^308"));
Console.WriteLine(uc.EvalStr("10^-308/10000"));

Console.WriteLine("--- Raise Div-by-0 ---");
uc.Error.FloatingPointErrorsToTrap = (int)ErrorCode.FloatDivisionByZero;
Console.WriteLine(uc.Error.FloatingPointErrorsToTrap);
Console.WriteLine(uc.EvalStr("1/0"));
Console.WriteLine(uc.EvalStr("0/0"));
Console.WriteLine(uc.EvalStr("5*10^308"));
Console.WriteLine(uc.EvalStr("10^-308/10000"));

Console.WriteLine("--- Raise overflow ---");
uc.Error.FloatingPointErrorsToTrap = (int)ErrorCode.FloatOverflow;
Console.WriteLine(uc.Error.FloatingPointErrorsToTrap);
Console.WriteLine(uc.EvalStr("1/0"));
Console.WriteLine(uc.EvalStr("0/0"));
Console.WriteLine(uc.EvalStr("5*10^308"));
Console.WriteLine(uc.EvalStr("10^-308/10000"));

Console.WriteLine("--- Raise invalid & underflow ---");
uc.Error.SetFloatingPointErrorsToTrap(ErrorCode.FloatInvalid, ErrorCode.FloatUnderflow);
Console.WriteLine(uc.Error.FloatingPointErrorsToTrap); // ErrorCode::FloatInvalid + ErrorCode::FloatUnderflow
Console.WriteLine(uc.EvalStr("1/0"));
Console.WriteLine(uc.EvalStr("0/0"));
Console.WriteLine(uc.EvalStr("5*10^308"));
Console.WriteLine(uc.EvalStr("10^-308/10000"));
```

**Output:**
```
0
inf
nan
inf
0
--- Raise Div-by-0 ---
8
Division by 0
nan
inf
0
--- Raise overflow ---
4
Floating point overflow
nan
Floating point overflow
0
--- Raise invalid & underflow ---
18
inf
Invalid floating point operation
inf
Floating point underflow
```

---

### Example ID: 75

**Description:** Checking if a uCalc object is the default with IsDefault

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var Status = uc.DefineVariable("Status As Bool");
Console.WriteLine(Status.ValueBool());

var MyuCalc = new uCalc();

Status.ValueBool(MyuCalc.IsDefault);
Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"));

MyuCalc.IsDefault = true;
Status.ValueBool(MyuCalc.IsDefault);

Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"));
```

**Output:**
```
False
MyuCalc is the current default? false
MyuCalc is the current default? true
```

---

### Example ID: 76

**Description:** Setting uCalc default with uCalc.IsDefault()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var uCalcA = new uCalc();
var uCalcB = new uCalc();
var uCalcC = new uCalc();

uCalcA.DefineVariable("MyVar = 'I was cloned from uCalcA'");
uCalcB.DefineVariable("MyVar = 'I was cloned from uCalcB'");
uCalcC.DefineVariable("MyVar = 'I was cloned from uCalcC'");

uCalcA.IsDefault = true;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("MyVar"));

uCalcB.IsDefault = true;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("MyVar"));

uCalcC.IsDefault = true;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("MyVar"));

Console.WriteLine("---");

// Now unsetting uCalc objects as default
uCalcC.IsDefault = false;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("MyVar"));

uCalcB.IsDefault = false;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("MyVar"));

uCalcA.IsDefault = false;
Console.WriteLine(uCalc.DefaultInstance.EvalStr("MyVar"));


```

**Output:**
```
I was cloned from uCalcA
I was cloned from uCalcB
I was cloned from uCalcC
---
I was cloned from uCalcB
I was cloned from uCalcA
Undefined identifier
```

---

### Example ID: 77

**Description:** ItemOf based on properties

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var Item = new uCalc.Item();
var x = 0;

// Lists the first few funcions defined in uCalc
// For the full list, loop until Item.IsEmpty() or while Item.NotEmpty()
for ( x = 0; x <= 15; x++) {
   Item = uc.ItemOf(ItemIs.Function, x);
   Console.WriteLine(Item.Name);
}
Console.WriteLine("---");

// List only Prefix and Postfix (operators)
x = 0;
do {
   Item = uc.ItemOf(uCalc.Properties(ItemIs.Prefix, ItemIs.Postfix), x);
   x = x + 1;
   Console.WriteLine(Item.Name);
} while (Item.NotEmpty());
```

**Output:**
```
abs
acos
acosh
addptr
addressof
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
---
!
+
-
not
~
```

---

### Example ID: 78

**Description:** Creating uCalc instances

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 123");

var uc1 = new uCalc(); // Creates a new instance
Console.WriteLine(uc1.EvalStr("x")); // uc1 does not have a variable named x
uc1.Release(); // Releases uc1 if it is no longer needed

var uc2 = uc.Clone(); // Creates new instance that is a clone of uc
Console.WriteLine(uc2.EvalStr("x")); // starts with the value of x obtained from uc
uc2.Eval("x = 456"); // Changes the value of x in uc1 but not uc
Console.WriteLine(uc2.EvalStr("x"));
Console.WriteLine(uc.EvalStr("x")); // The original x in uc remains unchanged
uc2.Release();

// Language specific - auto-releasing uCalc object

{ // Instances pointed to by neither uCalc1 nor uCalc2 will be released when they go out of scope
   var uCalc1 = new uCalc();
   var uCalc2 = uc.Clone();
   // Call uCalc1.Release() and uCalc2.Release() explicitly if want to release them
}

{ // The instances that both uCalc1 and uCalc2 point to will be released when uCalc1 and uCalc2 go out of scope
   using var uCalc1 = new uCalc();
   using var uCalc2 = uc.Clone();

   // No need for uCalc1.Release() or uCalc2.Release(), they will automatically be released
}

```

**Output:**
```
Undefined identifier
123
456
123
```

---

### Example ID: 79

**Description:** Defining uCalc Strings and  Expressions in the default uCalc object space

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var ucB = new uCalc();

uc.DefineVariable("x = 111");
ucB.DefineVariable("x = 222");

Console.WriteLine("--- using 'uc' as default ---");
uc.IsDefault = true;

uCalc.String MyString = "The variable value is: x";
Console.WriteLine(MyString.Replace("x", "{@Eval: x}"));

uCalc.Expression MyExpression = "x * 1000";
Console.WriteLine(MyExpression.Evaluate());

var MyTransformer = new uCalc.Transformer();
MyTransformer.Text = "Value is: x";
MyTransformer.FromTo("x", "{@Eval: x}");
Console.WriteLine(MyTransformer.Transform());


Console.WriteLine("--- using 'ucB' as default ---");
ucB.IsDefault = true;

uCalc.String MyStringB = "The variable value is: x";
Console.WriteLine(MyStringB.Replace("x", "{@Eval: x}"));

uCalc.Expression MyExpressionB = "x * 1000";
Console.WriteLine(MyExpressionB.Evaluate());

var MyTransformerB = new uCalc.Transformer();
MyTransformerB.Str("Value is: x");
MyTransformerB.FromTo("x", "{@Eval: x}");
Console.WriteLine(MyTransformerB.Transform());

```

**Output:**
```
--- using 'uc' as default ---
The variable value is: 111
111000
Value is: 111
--- using 'ucB' as default ---
The variable value is: 222
222000
Value is: 222
```

---

### Example ID: 80

**Description:** RaiseErrorOnDivideByZero

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.EvalStr("1/0"));
uc.Error.TrapOnDivideByZero = true;
Console.WriteLine(uc.EvalStr("1/0"));

Console.WriteLine(uc.EvalStr("Sqrt(-1)"));
uc.Error.TrapOnInvalid = true;
Console.WriteLine(uc.EvalStr("Sqrt(-1)"));

Console.WriteLine(uc.EvalStr("5*10^308"));
uc.Error.TrapOnOverflow = true;
Console.WriteLine(uc.EvalStr("5*10^308"));

Console.WriteLine(uc.EvalStr("10^-308/10000"));
uc.Error.TrapOnUnderflow = true;
Console.WriteLine(uc.EvalStr("10^-308/10000"));
```

**Output:**
```
inf
Division by 0
nan
Invalid floating point operation
inf
Floating point overflow
0
Floating point underflow
```

---

### Example ID: 82

**Description:** Pointer value with ValueAt

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.Format("Result = 'Answer: <' + Result + '>'");

var Dbl = uc.DefineVariable("MyDouble = 123.456");

Console.WriteLine(uc.ValueAt(Dbl.ValueAddr(), "Double"));
Console.WriteLine(uc.ValueAt(Dbl.ValueAddr(), BuiltInType.Float_Double));
Console.WriteLine(uc.ValueAt(Dbl.ValueAddr(), BuiltInType.Float_Double, true));


```

**Output:**
```
123.456
123.456
Answer: <123.456>
```

---

### Example ID: 84

**Description:** ArgDbl (same as Arg)

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyArea(uCalc.Callback cb) {
   var Length = cb.ArgDbl(1); // Same as cb.Arg(1);
   var Width = cb.ArgDbl(2); // Same as cb.Arg(2);
   cb.Return(Length * Width);
}

uc.DefineFunction("Area(x, y)", MyArea);
Console.WriteLine(uc.Eval("Area(3, 4)"));
```

**Output:**
```
12
```

---

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void BooleanAnd(uCalc.Callback cb) {
   cb.ReturnBool(cb.ArgBool(1) && cb.ArgBool(2));
}
static void AddInt16(uCalc.Callback cb) {
   //C# promots Int16 to int for arithmetic hence (Int16) to convert it back
   cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));

}
static void AddInt32(uCalc.Callback cb) {
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
}
static void AddInt64(uCalc.Callback cb) {
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
}


uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

Console.WriteLine(uc.EvalStr("BooleanAnd(true, false)"));
Console.WriteLine(uc.EvalStr("AddInt16(5.2, 4.1)"));
Console.WriteLine(uc.EvalStr("AddInt32(2, 3)"));
Console.WriteLine(uc.EvalStr("AddInt64(10, 20)"));
```

**Output:**
```
false
9
5
30
```

---

### Example ID: 86

**Description:** Returning a pointer with ReturnPtr

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void GetAddressOf(uCalc.Callback cb) {
   cb.ReturnPtr(cb.ArgItem(1).ValueAddr());
}


// This example is for sake of illustration
// There is already a built-in AddressOf() function

uc.DefineFunction("GetAddressOf(ByHandle Variable As AnyType) As SameTypeAs:0 Ptr", GetAddressOf);

uc.DefineVariable("MyVariable = 123.456");
uc.DefineVariable("MyStr = 'Hello world!'");

Console.WriteLine(uc.EvalStr("ValueAt(GetAddressOf(MyVariable))"));
Console.WriteLine(uc.EvalStr("ValueAt(GetAddressOf(MyStr))"));
```

**Output:**
```
123.456
Hello world!
```

---

### Example ID: 87

**Description:** Determining if a data type is compound or not with IsCompound

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.DataTypeOf("2 * (3 + 4)").IsCompound);
Console.WriteLine(uc.DataTypeOf(" 'Hello ' + 'world!' ").IsCompound);
Console.WriteLine(uc.DataTypeOf("3 + 4 * #i").IsCompound);
Console.WriteLine(uc.DataTypeOf(BuiltInType.String).IsCompound);
Console.WriteLine(uc.DataTypeOf("Bool").IsCompound);
```

**Output:**
```
False
True
True
True
False
```

---

### Example ID: 88

**Description:** Data type Reset

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyDbl = uc.DefineVariable("MyDbl = 123.456");
var MyStr = uc.DefineVariable("MyStr = 'Hello world!'");
var MyCplx = uc.DefineVariable("MyCplx = 3 + 4 * #i");

Console.WriteLine(uc.EvalStr("MyDbl"));
Console.WriteLine(uc.EvalStr("MyStr"));
Console.WriteLine(uc.EvalStr("MyCplx"));

uc.DataTypeOf("double").Reset(MyDbl.ValueAddr());
uc.DataTypeOf("string").Reset(MyStr.ValueAddr()); // empty string ""
uc.DataTypeOf("complex").Reset(MyCplx.ValueAddr());

Console.WriteLine(uc.EvalStr("MyDbl"));
Console.WriteLine(uc.EvalStr("MyStr"));
Console.WriteLine(uc.EvalStr("MyCplx"));


```

**Output:**
```
123.456
Hello world!
3+4i
0

0+0i
```

---

### Example ID: 89

**Description:** Sets a data type as the default

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.DataTypeOf("double").IsDefault);
Console.WriteLine(uc.DataTypeOf("int64").IsDefault);
Console.WriteLine(uc.DefaultDataType.Name);
Console.WriteLine("---");

uc.DataTypeOf("int64").IsDefault = true;

Console.WriteLine(uc.DataTypeOf("double").IsDefault);
Console.WriteLine(uc.DataTypeOf("int64").IsDefault);
Console.WriteLine(uc.DefaultDataType.Name);
Console.WriteLine("---");

uc.DataTypeOf("int64").IsDefault = false;

Console.WriteLine(uc.DataTypeOf("double").IsDefault);
Console.WriteLine(uc.DataTypeOf("int64").IsDefault);
Console.WriteLine(uc.DefaultDataType.Name);
```

**Output:**
```
True
False
double
---
False
True
int64
---
True
False
double
```

---

### Example ID: 90

**Description:** SetScalar

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyVar1 = uc.DefineVariable("MyVar1 = 123.456");
var MyVar2 = uc.DefineVariable("MyVar2 = 654.321");
var MyStr1 = uc.DefineVariable("MyStr1 = 'First string'");
var MyStr2 = uc.DefineVariable("MyStr2 = 'Second string'");

uc.DataTypeOf("double").SetScalar(MyVar1.ValueAddr(), MyVar2.ValueAddr());
uc.DataTypeOf("string").SetScalar(MyStr1.ValueAddr(), MyStr2.ValueAddr());

Console.WriteLine(uc.EvalStr("MyVar1")); // Now contains value copied from MyVar2
Console.WriteLine(uc.EvalStr("MyStr1")); // Now contains value copied from MyStr2
```

**Output:**
```
654.321
Second string
```

---

### Example ID: 91

**Description:** SwapScalarValues

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyVar1 = uc.DefineVariable("MyVar1 = 123.456");
var MyVar2 = uc.DefineVariable("MyVar2 = 654.321");
var MyStr1 = uc.DefineVariable("MyStr1 = 'First string'");
var MyStr2 = uc.DefineVariable("MyStr2 = 'Second string'");

Console.WriteLine(uc.EvalStr("MyVar1"));
Console.WriteLine(uc.EvalStr("MyVar2"));
Console.WriteLine(uc.EvalStr("MyStr1"));
Console.WriteLine(uc.EvalStr("MyStr2"));
Console.WriteLine("---");

uc.DataTypeOf("double").SwapScalarValues(MyVar1.ValueAddr(), MyVar2.ValueAddr());
uc.DataTypeOf("string").SwapScalarValues(MyStr1.ValueAddr(), MyStr2.ValueAddr());

Console.WriteLine(uc.EvalStr("MyVar1")); // Values of MyVar1 and MyVar2 are now swapped
Console.WriteLine(uc.EvalStr("MyVar2"));
Console.WriteLine(uc.EvalStr("MyStr1")); // Values of MyStr1 and MyStr2 are now swapped
Console.WriteLine(uc.EvalStr("MyStr2"));
```

**Output:**
```
123.456
654.321
First string
Second string
---
654.321
123.456
Second string
First string
```

---

### Example ID: 92

**Description:** Using ToString to convert a value to a string

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_8).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_8u).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_16u).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.Boolean).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.String).ToString("-1"));
```

**Output:**
```
-1
255
65535
true
-1
```

---

### Example ID: 93

**Description:** EvaluateBool, also ValueStr which converts numeric value to string

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

var VariableX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse("x > 3"); // The > operation returns a Boolean instead of the default floating point

for (double x = 1; x <= 5; x++) {
   VariableX.Value(x);
   Console.WriteLine($"x = {VariableX.ValueStr()}  x > 3 is {ParsedExpr.EvaluateBool()}");
}

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  x > 3 is False
x = 2  x > 3 is False
x = 3  x > 3 is False
x = 4  x > 3 is True
x = 5  x > 3 is True
```

---

### Example ID: 94

**Description:** Expression constructor

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uCalc.DefaultInstance.DefineVariable("x = 1.2");
uc.DefineVariable("x = 3.2");

var MyExprA = new uCalc.Expression();
var MyExprB = new uCalc.Expression("x+4.25");
var MyExprC = new uCalc.Expression("x+4.25", uCalc.DefaultInstance.DataTypeOf("int"));
var MyExprD = new uCalc.Expression(uc, "x+4.25");

MyExprA.Parse("x*100");

Console.WriteLine(MyExprA.Evaluate());
Console.WriteLine(MyExprB.Evaluate());
Console.WriteLine(MyExprC.Evaluate());
Console.WriteLine(MyExprD.Evaluate());

// Release expressions when no longer needed (see other example for auto-release)
MyExprA.Release();
MyExprB.Release();
MyExprC.Release();
MyExprD.Release();
```

**Output:**
```
120
5.45
5
7.45
```

---

### Example ID: 96

**Description:** Evaluate() auto-conversion

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// The int return value type in MyExprB is converted to
// Double with .Evaluate(), but not with .EvaluateDbl()
var MyExprA = uc.Parse("3.2 + 5.2");
var MyExprB = uc.Parse("int(3.2 + 5.2)");

Console.WriteLine(MyExprA.Evaluate());
Console.WriteLine(MyExprA.EvaluateDbl() == 8.4);
Console.WriteLine(MyExprB.Evaluate());
Console.WriteLine(MyExprB.EvaluateDbl() == 8);
```

**Output:**
```
8.4
True
8
False
```

---

### Example ID: 97

**Description:** Gets uCalc object associated with an expression

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyExpr = uc.Parse("5+4");

Console.WriteLine(MyExpr.Evaluate());

MyExpr.uCalc.Format("Result = 'Answer = ' + Result");

Console.WriteLine(MyExpr.EvaluateStr());
```

**Output:**
```
9
Answer = 9
```

---

### Example ID: 98

**Description:** uCalc.Item constructor

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// Note that x is defined in the default instance
// while f(x) is defined in the uc instance.
var MyVar = new uCalc.Item("Variable: x = 123");
var MyFunc = new uCalc.Item(uc, "Function: f(x) = x^2");

Console.WriteLine(uCalc.DefaultInstance.Eval("x"));
Console.WriteLine(uc.Eval("f(5)"));

MyVar.Release();
MyFunc.Release();

```

**Output:**
```
123
25
```

---

### Example ID: 99

**Description:** Language-specific auto-releasing of Item object

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Language specific - auto-releasing Item object
Console.WriteLine("auto-releasing Item (language-specific)");

{ // MyVar resources will NOT be released when MyVar goes out of scope
   var MyVar = new uCalc.Item("Variable: x = 123");
   // Call MyVar.Release() explicitly if want to release it here
}

{ // MyVar resouces will be released automatically when MyVar goes of scope
   using var MyVar = new uCalc.Item("Variable: x = 123");

   // No need for MyVar.Release(), it will automatically be released
}

```

**Output:**
```
auto-releasing Item (language-specific)
```

---

### Example ID: 100

**Description:** Setting a token data type

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// This example makes the # character behave the same way as quotes
uc.ExpressionTokens.Add("#([^#]*)#", TokenType.Literal, "", 1).DataType = uc.DataTypeOf("String");
Console.WriteLine(uc.EvalStr("#Hello # + #World#"));
```

**Output:**
```
Hello World
```

---

### Example ID: 101

**Description:** Changing an item's property

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyVar = uc.DefineVariable("x = 100");
Console.WriteLine(uc.EvalStr("x"));

uc.EvalStr("x = 200");
Console.WriteLine(uc.EvalStr("x")); // x can change here

// Locking an item prevents it from being changed
MyVar.IsProperty(ItemIs.Locked, true);

uc.EvalStr("x = 300"); // x cannot change here
Console.WriteLine(uc.EvalStr("x")); // x retains the previous value




```

**Output:**
```
100
200
200
```

---

### Example ID: 102

**Description:** Using ValuePtr

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var xVar = uc.DefineVariable("x = 123");
var xVarPtr = uc.DefineVariable("xPtr As Double Ptr = AddressOf(x)");

Console.WriteLine((xVarPtr.ValuePtr() == xVar.ValueAddr()));
```

**Output:**
```
True
```

---

### Example ID: 103

**Description:** Using ValueStr()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyStr = uc.DefineVariable("MyStr As String");
var MyDbl = uc.DefineVariable("MyDbl As Double");
var MyCplx = uc.DefineVariable("MyCplx As Complex");
var MyBool = uc.DefineVariable("MyBool As Boolean");

MyStr.ValueStr("Hello world!");
MyDbl.ValueStr("123.456");
MyCplx.ValueStr("3+4*#i");
MyBool.ValueStr("True");

Console.WriteLine(uc.EvalStr("$'MyStr = {MyStr}'"));
Console.WriteLine(uc.EvalStr("$'MyDbl = {MyDbl}'"));
Console.WriteLine(uc.EvalStr("$'MyCplx = {MyCplx}'"));
Console.WriteLine(uc.EvalStr("$'MyBool = {MyBool}'"));
Console.WriteLine("---");
Console.WriteLine(MyStr.ValueStr());
Console.WriteLine(MyDbl.ValueStr());
Console.WriteLine(MyCplx.ValueStr());
Console.WriteLine(MyBool.ValueStr());
```

**Output:**
```
MyStr = Hello world!
MyDbl = 123.456
MyCplx = 3+4i
MyBool = true
---
Hello world!
123.456
3+4i
true
```

---

### Example ID: 105

**Description:** How to extract text that appears after a specific pattern using the String.After() method.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uCalc.String s = "This is just a test";
Console.WriteLine(s.After("is"));

s = "/* if else */ if (x > 100) y = x * 2; else if(x == 5) y = x - 1;";
Console.WriteLine(s.After("if ({cond})"));
Console.WriteLine(s.After("if ({cond})").After("if ({cond})"));
Console.WriteLine(s.After("if ({cond})", 2)); // Finds text after 2nd match (same as above)
Console.WriteLine(s.After("NonExistingPattern")); // Nothing to display on this line
Console.WriteLine("----");

```

**Output:**
```
 just a test
 y = x * 2; else if(x == 5) y = x - 1;
 y = x - 1;
 y = x - 1;

----
```

---

### Example ID: 107

**Description:** uCalc.Items

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
foreach(var item in uc.Items) {
   Console.WriteLine(item.Name);
}
```

**Output:**
```
!
%
&
&&
*
+
,
-
/
<
<<
<=
<>
=
==
>
>=
>>
\
^
_enduserformattedoutput
_newline
_token_alphanumeric
_token_argseparator
_token_binaryhexoctalnotation
_token_catchall
_token_catchall_utf8_other
_token_curlybrace
_token_curlybrace_close
_token_floatnumber
_token_imaginaryunit
_token_line
_token_memberaccess
_token_newline
_token_parenthesis
_token_parenthesis_close
_token_punctuation
_token_quotechar
_token_quotechar_double
_token_quotechar_single
_token_quotechar_tripledouble
_token_reducible
_token_reducible2
_token_semicolon
_token_squarebracket
_token_squarebracket_close
_token_string_doublequoted
_token_string_singlequoted
_token_string_tripledoublequoted
_token_stringinterpolationquote
_token_variableargs
_token_whitespace
_ucalc_lib_is32
_ucalc_lib_is64
_ucalc_lib_os
_ucalc_lib_release_date
_ucalc_lib_release_datetime
_ucalc_lib_version
abs
acos
acosh
addptr
addressof
and
andalso
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
back
baseconvert
bin
bitand
bitor
bool
bool
int8u
c_str
cbrt
ceil
chr
clear
compare
complex
conj
contains
copysign
cos
cosh
define
doloop
double
endswith
erase
erase_copy
erf
erfc
error
eval
evalstr
evaluate
evaluateint
evaluatestr
exp
exp2
expm1
exprptr
fabs
false
fdim
file
filesize
fill
find_first_not_of
find_first_of
find_last_not_of
find_last_of
single
floor
fmax
fmin
fmod
forloop
format
fpclassify
frac
frexp
fromto
gcd
goto
hex
hypot
iif
ilogb
imag
indexof
inf
insert
insert_copy
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
isfinite
isinf
isnan
isnormal
lastindexof
lastrandomnumber
lcase
lcm
ldexp
length
lgamma
llrint
llround
log
log10
log1p
log2
logb
lrint
lround
ltrim
max
min
mod
modf
nan
nearbyint
nextafter
nexttoward
norm
not
oct
omnitype
or
orelse
padleft
padright
parse
pointer
polar
pop
pow
precedence
proj
push
rand
randfromsameseed
randomnumber
randomseed
real
remainder
remquo
repeat
replace
replace_copy
reset
rint
round
rtrim
sametypeas
scalbln
scalbn
setvar
sgn
signbit
sin
single
sinh
size_t
sizeof
sort
sqr
sqrt
startswith
str
string
substr
subtractptr
swap
tan
tanh
tgamma
trim
true
trunc
ucalcinstance
ucase
valueat
valueattype
void
xor
|
||
~
```

---

### Example ID: 108

**Description:** ListOfItem with name / property

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine("Items with the Prefix property");
Console.WriteLine("------------------------------");
foreach(var item in uc.GetItems(ItemIs.Prefix)) {
   Console.WriteLine(item.Name);
}

Console.WriteLine("");
Console.WriteLine("Different versions of the + operator");
Console.WriteLine("------------------------------------");
foreach(var item in uc.GetItems("+")) {
   Console.WriteLine(item.Text);
}
```

**Output:**
```
Items with the Prefix property
------------------------------
!
+
-
not
~

Different versions of the + operator
------------------------------------
Operator: 70 +{x}
Operator: 50 {x} + {y}
Operator: 50 {x As Int} + {y As Int} As Int
Operator: 50 {x As String} + {y As String} As String
Operator: 50 {x As Complex} + {y As Complex} As Complex
Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr
Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String
Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String
```

---

### Example ID: 109

**Description:** ListOfDataTypes

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
foreach(var Item in uc.ListOfDataTypes()) {
   Console.WriteLine(Item.Name);
}

```

**Output:**
```
anytype
bool
bool
int8u
complex
double
single
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
omnitype
pointer
sametypeas
single
size_t
string
void
```

---

### Example ID: 110

**Description:** How to find matched patterns while skipping commented text using SkipOver().

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("int result = (x + 3) * 2 - (y - 7 / z) * (5 ^ a + 10); /* (x + y) */");

// Capture standard blocks surrounded by parentheses
t.Pattern("({expr})");

// Instruct the transformer to ignore any text inside C-style block comments.
// This prevents the commented "(x + y)" from being falsely counted as a match.
t.SkipOver("/* {etc} */"); // commented text between /* */ is skipped

t.Find();
Console.WriteLine(t.Matches.Count());
```

**Output:**
```
3
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>";
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

Console.WriteLine(t.Text);
Console.WriteLine("");

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.Matches;

Console.WriteLine(Matches[0].Text);
Console.WriteLine($"Start pos: {Matches[0].StartPosition}");
Console.WriteLine($"End pos: {Matches[0].EndPosition}");
Console.WriteLine($"Length: {Matches[0].Length}");
Console.WriteLine("");

Console.WriteLine(Matches[1].Text);
Console.WriteLine($"Start pos: {Matches[1].StartPosition}");
Console.WriteLine($"End pos: {Matches[1].EndPosition}");
Console.WriteLine($"Length: {Matches[1].Length}");
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 112

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

Console.WriteLine($"All matches -- count = {t.Matches.Count()}");
Console.WriteLine("----------------------");
Console.WriteLine(t.Matches);
Console.WriteLine("");

Console.WriteLine($"Only BoldTag matches -- count = {BoldTag.Matches.Count()}");
Console.WriteLine("-------------------------------");
Console.WriteLine(BoldTag.Matches);
Console.WriteLine("");

Console.WriteLine($"Only H3Tag matches -- count = {H3Tag.Matches.Count()}");
Console.WriteLine("-----------------------------");
Console.WriteLine(H3Tag.Matches);
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

### Example ID: 113

**Description:** Using IndexOf() in Matches

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");
//     ^             ^                    ^               ^                ^
//     012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50        60        70        80
// Carrets (^) point to Start locations of the matches

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

Console.WriteLine("IndexOf   StartPos   Match");
Console.WriteLine("");

Console.WriteLine("All Matches");
Console.WriteLine("-----------");
foreach(var match in t.Matches) {
   Console.WriteLine($"{t.Matches.IndexOf(match.StartPosition)}         {match.StartPosition}          {match.Text}");
}
Console.WriteLine("");

Console.WriteLine("Bold Matches");
Console.WriteLine("------------");
foreach(var BoldMatch in BoldTag.Matches) {
   Console.WriteLine($"{t.Matches.IndexOf(BoldMatch.StartPosition)}         {BoldMatch.StartPosition}          {BoldMatch.Text}");
}
Console.WriteLine("");

Console.WriteLine("H3 Matches");
Console.WriteLine("----------");
foreach(var H3Match in H3Tag.Matches) {
   Console.WriteLine($"{t.Matches.IndexOf(H3Match.StartPosition)}         {H3Match.StartPosition}          {H3Match.Text}");
}
Console.WriteLine("");

Console.WriteLine("Other Matches");
Console.WriteLine("-------------");
foreach(var AnyOtherMatch in AnyOtherTag.Matches) {
   Console.WriteLine($"{t.Matches.IndexOf(AnyOtherMatch.StartPosition)}         {AnyOtherMatch.StartPosition}          {AnyOtherMatch.Text}");
}
```

**Output:**
```
IndexOf   StartPos   Match

All Matches
-----------
0         0          <h3>Title</h3>
1         14          <b>Bold statement</b>
2         35          <h3>Title B</h3>
3         51          <b>Other text</b>
4         68          <p>My paragraph</p>

Bold Matches
------------
1         14          <b>Bold statement</b>
3         51          <b>Other text</b>

H3 Matches
----------
0         0          <h3>Title</h3>
2         35          <h3>Title B</h3>

Other Matches
-------------
4         68          <p>My paragraph</p>
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>";
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.Matches) {
   Console.WriteLine(match.Text);
   Console.WriteLine($"Start pos: {match.StartPosition}");
   Console.WriteLine($"End pos: {match.EndPosition}");
   Console.WriteLine($"Length: {match.Length}");
   Console.WriteLine("");
}
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

### Example ID: 118

**Description:** How to assign and retrieve descriptions for specific transformation patterns using SetDescription().

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>").SetDescription("other kind of tag");
var BoldTag = t.Pattern("<b>{text}</b>").SetDescription("bold tag");
var H3Tag = t.Pattern("<h3>{text}</h3>").SetDescription("h3 tag");
t.Find();

foreach(var match in t.Matches) {
   Console.WriteLine(match.Text + "   Description: " + match.Rule.Description);
}
```

**Output:**
```
<h3>Title</h3>   Description: h3 tag
<b>Bold statement</b>   Description: bold tag
<h3>Title B</h3>   Description: h3 tag
<b>Other text</b>   Description: bold tag
<p>My paragraph</p>   Description: other kind of tag
```

---

### Example ID: 120

**Description:** How to dynamically enable or disable transformation rules using the Active property.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b>");

var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();


Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

BoldTag.Active = false;
Console.WriteLine($"BoldTag.Active(): {BoldTag.Active}");
Console.WriteLine("-----------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

BoldTag.Active = true;
Console.WriteLine($"BoldTag.Active(): {BoldTag.Active}");
Console.WriteLine("----------------------");

t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

```

**Output:**
```
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>

BoldTag.Active(): False
-----------------------
<h3>Title</h3>
<h3>Title B</h3>

BoldTag.Active(): True
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
```

---

### Example ID: 121

**Description:** BracketSensitive

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var Pattern = t.Pattern("< {etc} >");
t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >");

// Note the difference in the final match

Pattern.BracketSensitive = true; // true is the default
Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}");
Console.WriteLine("----------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

Pattern.BracketSensitive = false;
Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}");
Console.WriteLine("-----------------------");

t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

t.Str("( a b ( c ) d e )");
// Here parentheses are captured as regular tokens, not bracket pairs
var Pattern2a = t.Pattern("( {etc} (");
var Pattern2b = t.Pattern(") {etc} )");

Console.WriteLine("Brackets used as part of pattern");
Console.WriteLine("--------------------------------");
Pattern2a.BracketSensitive = true;
Pattern2b.BracketSensitive = true;
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");
Pattern2a.BracketSensitive = false;
Pattern2b.BracketSensitive = false;
t.Find();
Console.WriteLine(t.Matches.Text);


```

**Output:**
```
BracketSensitive: True
----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( > p) q >

BracketSensitive: False
-----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( >

Brackets used as part of pattern
--------------------------------
( a b (
) d e )

( a b (
) d e )
```

---

### Example ID: 122

**Description:** CaseSensitive

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH");
var Pattern = t.Pattern("StArT {etc} FinISH");

Pattern.CaseSensitive = true;
Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}");
Console.WriteLine("-------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

Pattern.CaseSensitive = false;
Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}");
Console.WriteLine("--------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
CaseSensitive: True
-------------------
StArT a b c FinISH

CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH
```

---

### Example ID: 123

**Description:** Focusable to toggle pattern matches

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b>");

var BoldTag = t.Pattern("<b>{text}</b>").SetFocusable(true);
var H3Tag = t.Pattern("<h3>{text}</h3>").SetFocusable(true);
t.Find();

Console.WriteLine(t.GetMatches(MatchesOption.FocusableOnly).Text);
Console.WriteLine("");

BoldTag.Focusable = false;
Console.WriteLine($"BoldTag.Focusable(): {BoldTag.Focusable}");
Console.WriteLine("--------------------------");
// t.Find(); // A Find operation does not have to be executed again
Console.WriteLine(t.GetMatches(MatchesOption.FocusableOnly).Text);
Console.WriteLine("");

BoldTag.Focusable = true;
Console.WriteLine($"BoldTag.Focusable(): {BoldTag.Focusable}");
Console.WriteLine("--------------------------");

//t.Find(); // A Find operation does not have to be executed again
Console.WriteLine(t.GetMatches(MatchesOption.FocusableOnly).Text);
Console.WriteLine("");
```

**Output:**
```
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>

BoldTag.Focusable(): False
--------------------------
<h3>Title</h3>
<h3>Title B</h3>

BoldTag.Focusable(): True
--------------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
```

---

### Example ID: 125

**Description:** Using SkipOver() to ignore XML-style comments

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// StatementSensitive() is set to false so that ";" and newline are not treated as special

var t = uc.NewTransformer();
Console.WriteLine($"StatementSensitive: {t.DefaultRuleSet.StatementSensitive}");
Console.WriteLine("Setting StatementSensitive to False");

t.DefaultRuleSet.StatementSensitive = false; // so that newline does not behave as a statement separator

Console.WriteLine($"StatementSensitive: {t.DefaultRuleSet.StatementSensitive}");
Console.WriteLine("");

var Content =
"""

<nav aria-label="Main navigation">
  <ul>
    <li><a href="#intro">Intro</a></li>
    <li><a href="#examples">Examples</a></li>
    <!-- <li><a href="#contact">Contact</a></li> -->
  </ul>
</nav>

<!-- 
<h2>Ingredients</h2>
<ul>
  <li>3 cups flour</li>
  <li>1.5 cups water</li>
  <li>1 tsp salt</li>
</ul>
-->

<nav aria-label="Chapter navigation">
    <ul>
      <li><a href="#one">One</a></li>
      <li><a href="#two">Two</a></li>
      <li><a href="#three">Three</a></li>
    </ul>
</nav>

""";

t.Str(Content);
var Pattern = t.Pattern("<li>{item}</li>");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

Console.WriteLine("<!-- Skip over commented lines -->");
Console.WriteLine("----------------------------------");
t.SkipOver("<!-- {comment} -->");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

```

**Output:**
```
StatementSensitive: True
Setting StatementSensitive to False
StatementSensitive: False

<li><a href="#intro">Intro</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#contact">Contact</a></li>
<li>3 cups flour</li>
<li>1.5 cups water</li>
<li>1 tsp salt</li>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>

<!-- Skip over commented lines -->
----------------------------------
<li><a href="#intro">Intro</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
```

---

### Example ID: 126

**Description:** LocalTransformer, HasLocalTransformer, IsChildRule

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Note the change in section/div/h2
var t = uc.NewTransformer();

var rule = t.Pattern("<section>{body}</section>").SetStatementSensitive(false);
var section = rule.LocalTransformer;
section.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>");
section.SkipOver("&{entity};");
var ch = section.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>");

Console.WriteLine($"Has a local transformer: {rule.HasLocalTransformer}");
Console.WriteLine($"rule is a child rule: {rule.IsChildRule}");
Console.WriteLine($"ch is a child rule: {ch.IsChildRule}");

var HtmlText =
"""

<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h2>Article Three</h2>
    <p>This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>

""";

t.Text = HtmlText;
t.Transform();
Console.WriteLine(t.Text);


```

**Output:**
```
Has a local transformer: True
rule is a child rule: False
ch is a child rule: True

<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h1>====> ARTICLE THREE <====</h1>
    <p>SELECTED: This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
```

---

### Example ID: 127

**Description:** Maximum, GlobalMaximum

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var FruitsXML =
"""

<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>

""";

uc.DefineVariable("x");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

uc.Eval("x = 1");
Fruit.Maximum = 10;
t.Filter(FruitsXML);
Console.WriteLine($"Maximum = {Fruit.Maximum}");
Console.WriteLine($"Matches count: {t.Matches.Count()}"); // 1 for FruitsTag occurrence
Console.WriteLine("");
Console.WriteLine(t.Matches);
Console.WriteLine("");
Console.WriteLine("===============");

uc.Eval("x = 1");
Fruit.Maximum = 20;
t.Filter(FruitsXML);
Console.WriteLine($"Maximum = {Fruit.Maximum}");
Console.WriteLine($"Matches count: {t.Matches.Count()}"); // 1 for FruitsTag plus 12 fruits
Console.WriteLine("");
Console.WriteLine(t.Matches);
Console.WriteLine("");
Console.WriteLine("===============");

uc.Eval("x = 1");
Fruit.GlobalMaximum = 10; // Notice "List of fruits" will not show
t.Filter(FruitsXML);
Console.WriteLine($"MaximumAND = {Fruit.GlobalMaximum}");
Console.WriteLine($"Matches count: {t.Matches.Count()}"); // Even FruitsTage won't be counted
Console.WriteLine("");
Console.WriteLine(t.Matches);
Console.WriteLine("===============");

uc.Eval("x = 1");
Fruit.GlobalMaximum = 20;
t.Filter(FruitsXML);
Console.WriteLine($"MaximumAND = {Fruit.GlobalMaximum}");
Console.WriteLine($"Matches count: {t.Matches.Count()}");
Console.WriteLine("");
Console.WriteLine(t.Matches);

```

**Output:**
```
Maximum = 10
Matches count: 1

List of fruits

===============
Maximum = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MaximumAND = 10
Matches count: 0


===============
MaximumAND = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

### Example ID: 130

**Description:** Rule Name

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<b>(5+4)</b> this and that etc";
var a = t.Pattern("<{tg}>");
var b = t.Pattern("This {body} That");
var c = t.Pattern("etc");
var d = t.Pattern("({expr})");

t.Filter();
Console.WriteLine("--- Matches ---");
Console.WriteLine(t.Matches.Text);
Console.WriteLine("--- Pattern names ---");
Console.WriteLine(a.Name);
Console.WriteLine(b.Name);
Console.WriteLine(c.Name);
Console.WriteLine(d.Name);
Console.WriteLine("--- Pattern defs ---");
Console.WriteLine(a.Pattern);
Console.WriteLine(b.Pattern);
Console.WriteLine(c.Pattern);
Console.WriteLine(d.Pattern);
```

**Output:**
```
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})
```

---

### Example ID: 131

**Description:** Rule NextOverload and Tag

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "Testing (a b c) Testing x y z! Testing 1 2 3.";

var Pattern1 = t.Pattern("Testing {etc}.").SetTag(111);
var Pattern2 = t.Pattern("Testing {etc}!").SetTag(222);
var Pattern3 = t.Pattern("Testing ({etc})").SetTag(333);

t.Find();
Console.WriteLine("--- Matches ---");
Console.WriteLine(t.Matches.Text);
Console.WriteLine("--- Patterns ---");
Console.WriteLine(Pattern1.Pattern);
Console.WriteLine(Pattern2.Pattern);
Console.WriteLine(Pattern3.Pattern);
Console.WriteLine("---- Tags ----");
Console.WriteLine(Pattern1.Tag);
Console.WriteLine(Pattern2.Tag);
Console.WriteLine(Pattern3.Tag);
Console.WriteLine("-- Overload Tags --");
// Note that most recently defined patterns come first
Console.WriteLine(Pattern3.NextOverload().Tag);
Console.WriteLine(Pattern2.NextOverload().Tag);
Console.WriteLine(Pattern1.NextOverload().Tag);


```

**Output:**
```
--- Matches ---
Testing (a b c)
Testing x y z!
Testing 1 2 3.
--- Patterns ---
Testing {etc}.
Testing {etc}!
Testing ({etc})
---- Tags ----
111
222
333
-- Overload Tags --
222
111
0
```

---

### Example ID: 132

**Description:** ParentTransformer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var Txt = "Test a b c. x y z";

var FirstTransform = uc.NewTransformer().SetText(Txt).SetDescription("First Transformer");
var aaa = FirstTransform.FromTo("Test {etc}.", "[{etc}]");

var SecondTransform = uc.NewTransformer().SetDescription("Second Transformer");
var bbb = SecondTransform.FromTo("Test {etc}.", "({etc})");

Console.WriteLine(aaa.ParentTransformer.Description);
Console.WriteLine(FirstTransform.Transform().Text);
Console.WriteLine("");

Console.WriteLine(SecondTransform.Description);
Console.WriteLine(bbb.ParentTransformer.Transform(Txt).Text);
```

**Output:**
```
First Transformer
[a b c] x y z

Second Transformer
(a b c) x y z
```

---

### Example ID: 134

**Description:** Replacement()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "aaa bbb xyz 123";
var aaa = t.FromTo("aaa", "111");
var xyz = t.Pattern("xyz");
t.Filter();
Console.WriteLine(t.Matches.Text);

Console.WriteLine("-----");
Console.WriteLine(aaa.Replacement);
Console.WriteLine(xyz.Replacement);

```

**Output:**
```
111
xyz
-----
111
{@Self}
```

---

### Example ID: 137

**Description:** SkipOver(),  Str(), Implicit Str()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var txt = "a b c (a b c a b c) a b c";
t.FromTo("a", "AA");

// You can either set the string before or pass it to Transform()
t.Str(txt);
Console.WriteLine(t.Transform().Text);

t.SkipOver("({text})");
Console.WriteLine(t.Transform(txt)); // Implicit Text property
```

**Output:**
```
AA b c (AA b c AA b c) AA b c
AA b c (a b c a b c) AA b c
```

---

### Example ID: 138

**Description:** Rule StartAfter()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var FruitsXML =
"""

<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>

""";

var Fruit = t.FromTo("CommonName={@string:name}", "{name}");

// StopAfter()
Fruit.StopAfter = 4;
t.Filter(FruitsXML);
Console.WriteLine($"*** Stop after: {Fruit.StopAfter} ***");
Console.WriteLine(t.Matches.Text);
Fruit.StopAfter = -1; // Resets back to infinity (default) for next example
Console.WriteLine("");

// StartAfter()
Fruit.StartAfter = 6;
t.Filter(FruitsXML);
Console.WriteLine($"*** Start after: {Fruit.StartAfter} ***");
Console.WriteLine(t.Matches.Text);
Fruit.StartAfter = 0; // Resets back to 0 (default) for next example
Console.WriteLine("");


// Both StartAfter() and StopAfter()
Fruit.SetStartAfter(2).SetStopAfter(5);
t.Filter(FruitsXML);
Console.WriteLine($"*** Between {Fruit.StartAfter + 1} and {Fruit.StopAfter} ***");
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

// All
uc.DefineVariable("x = 1");
Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");
t.Filter(FruitsXML);
Console.WriteLine("*** All ***");
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
*** Stop after: 4 ***
Apple
Banana
Orange
Grapes

*** Start after: 6 ***
Mango
Blueberry
Rambutan
Salak (Snake Fruit)
Jabuticaba
Watermelon

*** Between 3 and 5 ***
Orange
Grapes
Strawberry

*** All ***
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

### Example ID: 139

**Description:** Focusable to select only patterns from local transformer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var FruitsXML =
"""

<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <!-- <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' /> -->
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <!-- <Fruit CommonName='Mango' ScientificName='Mangifera indica' /> -->
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <!-- <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' /> -->
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <!-- <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' /> -->
</Fruits>

""";

// List names of fruit within comment, not the whole comment as well
t.Text = FruitsXML;
var CommentedFruits = t.Pattern("<!-- {comment} -->").SetFocusable(false);
var CommentedFruitsTr = CommentedFruits.LocalTransformer;
CommentedFruitsTr.FromTo("CommonName={@string:text}", "{text}").Focusable = true;

t.Filter();
Console.WriteLine("With Focusable()");
Console.WriteLine("----------------");
Console.WriteLine(t.GetMatches(MatchesOption.FocusableOnly).Text);
Console.WriteLine("");

// Note: The displayed Fruit element is modified by CommentedFruitsTr.FromTo()
Console.WriteLine("Without Focusable()");
Console.WriteLine("-------------------");
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
With Focusable()
----------------
Grapes
Mango
Rambutan
Watermelon

Without Focusable()
-------------------
<!-- <Fruit Grapes ScientificName='Vitis vinifera' /> -->
Grapes
<!-- <Fruit Mango ScientificName='Mangifera indica' /> -->
Mango
<!-- <Fruit Rambutan ScientificName='Nephelium lappaceum' /> -->
Rambutan
<!-- <Fruit Watermelon ScientificName='Citrullus lanatus' /> -->
Watermelon
```

---

### Example ID: 140

**Description:** StatementSensitive()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "x = 1; if (true) func1(3+4); else func2(x*y); y = x + 2";
var p = t.Pattern("if {etc}");

Console.WriteLine($"Input: {t.Text}");
Console.WriteLine($"Pattern: {p.Pattern}");
Console.WriteLine("");

t.Find();
Console.WriteLine($"StatementSensitive: {t.DefaultRuleSet.StatementSensitive}");
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

t.DefaultRuleSet.StatementSensitive = false;
t.Find();
Console.WriteLine($"StatementSensitive: {t.DefaultRuleSet.StatementSensitive}");
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
Input: x = 1; if (true) func1(3+4); else func2(x*y); y = x + 2
Pattern: if {etc}

StatementSensitive: True
if (true) func1(3+4)

StatementSensitive: False
if (true) func1(3+4); else func2(x*y); y = x + 2
```

---

### Example ID: 141

**Description:** Rule uCalc

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "The value is: x";

uc.DefineVariable("VarX");
t.FromTo("x", "{@Eval: VarX}").uCalc.Eval("VarX = 123");

t.Transform();
Console.WriteLine(t.Text);
```

**Output:**
```
The value is: 123
```

---

### Example ID: 142

**Description:** WhitespaceSensitive()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var Text = "This is a test.";
var p = t.FromTo("This {words:3}", "[{words}]");

Console.WriteLine($"Input: {Text}");
Console.WriteLine($"Pattern: {p.Pattern}");
Console.WriteLine("");

Console.WriteLine("3 captured tokens are in brackets");
Console.WriteLine("");

Console.WriteLine($"WhitespaceSensitive = {t.DefaultRuleSet.WhitespaceSensitive}");
Console.WriteLine(t.Transform(Text));
Console.WriteLine("");

t.DefaultRuleSet.WhitespaceSensitive = true;
Console.WriteLine($"WhitespaceSensitive = {t.DefaultRuleSet.WhitespaceSensitive}");
Console.WriteLine(t.Transform(Text));

```

**Output:**
```
Input: This is a test.
Pattern: This {words:3}

3 captured tokens are in brackets

WhitespaceSensitive = False
[is a test].

WhitespaceSensitive = True
[ is ]a test.
```

---

### Example ID: 143

**Description:** Minimum, GlobalMinimum

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var FruitsXML =
"""

<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>

""";

uc.DefineVariable("x = 1");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

Fruit.Minimum = 20;
t.Filter(FruitsXML);
Console.WriteLine($"Minimum = {Fruit.Minimum}");
Console.WriteLine($"Matches count: {t.Matches.Count()}"); // 1 for FruitsTag occurrence
Console.WriteLine("");
Console.WriteLine(t.Matches);
Console.WriteLine("");
Console.WriteLine("===============");

uc.Eval("x = 1");
Fruit.Minimum = 10;
t.Filter(FruitsXML);
Console.WriteLine($"Minimum = {Fruit.Minimum}");
Console.WriteLine($"Matches count: {t.Matches.Count()}"); // 1 for FruitsTag plus 12 fruits
Console.WriteLine("");
Console.WriteLine(t.Matches);
Console.WriteLine("");
Console.WriteLine("===============");

uc.Eval("x = 1");
Fruit.GlobalMinimum = 20; // Notice "List of fruits" will not show
t.Filter(FruitsXML);
Console.WriteLine($"MinimumAND = {Fruit.GlobalMinimum}");
Console.WriteLine($"Matches count: {t.Matches.Count()}"); // Even FruitsTage won't be counted
Console.WriteLine("");
Console.WriteLine(t.Matches);
Console.WriteLine("===============");

uc.Eval("x = 1");
Fruit.GlobalMinimum = 10;
t.Filter(FruitsXML);
Console.WriteLine($"MinimumAND = {Fruit.GlobalMinimum}");
Console.WriteLine($"Matches count: {t.Matches.Count()}");
Console.WriteLine("");
Console.WriteLine(t.Matches);

```

**Output:**
```
Minimum = 20
Matches count: 1

List of fruits

===============
Minimum = 10
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MinimumAND = 20
Matches count: 0


===============
MinimumAND = 10
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

### Example ID: 144

**Description:** QuoteSensitive

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer().SetText("Test1 'a b c' a b c Test2 'a b c' a b c");

var Test1 = t.FromTo("Test1 {txt} b", "[{txt}]"); // defaults to QuoteSensitive = true
var Test2 = t.FromTo("Test2 {txt} b", "({txt})").SetQuoteSensitive(false);
t.Transform();

Console.WriteLine($"Test1 QuoteSensitive = {Test1.QuoteSensitive}");
Console.WriteLine($"Test2 QuoteSensitive = {Test2.QuoteSensitive}");

Console.WriteLine(t);
```

**Output:**
```
Test1 QuoteSensitive = True
Test2 QuoteSensitive = False
['a b c' a] c ('a) c' a b c
```

---

### Example ID: 145

**Description:** How to define and then permanently remove a rule.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
string text = "(this and that) <this or that>";
t.Text = text;

// Define two rules
var rule1 = t.FromTo("({txt})", "#{txt}#");
var rule2 = t.FromTo("<{txt}>", "${txt}$");

// Transform with both rules active
Console.WriteLine(t.Transform());

// Release the first rule
rule1.Release();

// Re-run the transformation; only the second rule applies
t.Text = text;
Console.WriteLine(t.Transform());
```

**Output:**
```
#this and that# $this or that$
(this and that) $this or that$
```

---

### Example ID: 147

**Description:** Demonstration of TraceTrancform, ListFunction, and IndexBase

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.DefaultRuleSet.RewindOnChange = true;
t.FromTo("AddUp({x})", "{x}");
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

Console.WriteLine(t.TraceTransform("AddUp(1, 2, 3, 4)").ListFunction("$'Step {Index}: {x}\n'"));

// 0 is the default IndexBase.  Here we will use 1 instead.
// So it will now start with "Step: 1" instead of "Step: 0"
Console.WriteLine("--- Now with IndexBase = 1 ---");
Console.WriteLine(t.TraceTransform("AddUp(1, 2, 3, 4)").ListFunction("$'Step {Index} of {Count}: {x}\n'").IndexBase(1));
```

**Output:**
```
Step 0: AddUp(1, 2, 3, 4)
Step 1: (1 + AddUp(2, 3, 4))
Step 2: (1 + (2 + AddUp(3, 4)))
Step 3: (1 + (2 + (3 + AddUp(4))))
Step 4: (1 + (2 + (3 + 4)))

--- Now with IndexBase = 1 ---
Step 1 of 5: AddUp(1, 2, 3, 4)
Step 2 of 5: (1 + AddUp(2, 3, 4))
Step 3 of 5: (1 + (2 + AddUp(3, 4)))
Step 4 of 5: (1 + (2 + (3 + AddUp(4))))
Step 5 of 5: (1 + (2 + (3 + 4)))
```

---

### Example ID: 148

**Description:** MatchesOption: RootLevelOnly and InnermostOnly

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.Str(txt);

t.Pattern("<p {etc}>").LocalTransformer.FromTo("id={@string:id}", "{id}");
t.Filter();


Console.WriteLine("All matches");
Console.WriteLine("-----------");
Console.WriteLine(t.GetMatches(MatchesOption.All).Text); // All is the default
Console.WriteLine("");

Console.WriteLine("RootLevelOnly");
Console.WriteLine("-------------");
Console.WriteLine(t.GetMatches(MatchesOption.RootLevelOnly).Text);
Console.WriteLine("");

Console.WriteLine("InnermostOnly");
Console.WriteLine("-------------");
Console.WriteLine(t.GetMatches(MatchesOption.InnermostOnly).Text);
Console.WriteLine("");
```

**Output:**
```
All matches
-----------
<p aa>
aa
<p bb>
bb
<p cc>
cc

RootLevelOnly
-------------
<p aa>
<p bb>
<p cc>

InnermostOnly
-------------
aa
bb
cc
```

---

### Example ID: 149

**Description:** Pass()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var FruitsXML =
"""

<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>

""";

var t = uc.NewTransformer();
t.Text = FruitsXML;

var Pass1 = t.Pass();
var Pass2 = t.Pass();

Pass1.Description = "Pass A";
Pass1.FromTo("Fruits", "ListOfFruits");
Pass1.FromTo("<Fruit CommonName={@str:name} ScientificName={@str:sci_name} />", "<Fruit>{name}</Fruit>");

Pass2.Description = "Pass B";
Pass2.FromTo("{Fruit: Apple | Orange | Mango }", "{Fruit} *");
Pass2.FromTo("{Fruit: Banana | Grapes | Watermelon }", "{Fruit} **");

t.Transform();
Console.WriteLine("All passes");
Console.WriteLine("----------");
Console.WriteLine(t.Text);

Console.WriteLine(t.Pass(0).Description);
Console.WriteLine(t.Pass(1).Description);
Console.WriteLine($"Pass count: {t.PassCount()}");
Console.WriteLine("");

t.Str(FruitsXML);
Pass2.Release();
t.Transform();
Console.WriteLine("Pass1 only (Pass2 released)");
Console.WriteLine("---------------------------");
Console.WriteLine(t.Text);

```

**Output:**
```
All passes
----------

<ListOfFruits>
  <Fruit>Apple *</Fruit>
  <Fruit>Banana **</Fruit>
  <Fruit>Orange *</Fruit>
  <Fruit>Grapes **</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango *</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon **</Fruit>
</ListOfFruits>

Pass A
Pass B
Pass count: 2

Pass1 only (Pass2 released)
---------------------------

<ListOfFruits>
  <Fruit>Apple</Fruit>
  <Fruit>Banana</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon</Fruit>
</ListOfFruits>
```

---

### Example ID: 151

**Description:** Transformer Reset()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var txt = "a b c d e";

t.Text = txt;
t.FromTo("a", "aaa");
t.FromTo("c", "xyz");

Console.WriteLine($"Input: {t}");
Console.WriteLine($"Transformed: {t.Transform()}");

Console.WriteLine("Reset");
t.Reset();

Console.WriteLine($"Input: {t}(empty)");
t.Text = "a b c d e";
Console.WriteLine($"New input: {t.Text}");
Console.WriteLine($"Transformed: {t.Transform().Text} (no transform)");
Console.WriteLine("New rules");

t.FromTo("b", "ABC");
t.FromTo("d", "DDD");
Console.WriteLine($"Transformed: {t.Transform().Text}");

```

**Output:**
```
Input: a b c d e
Transformed: aaa b xyz d e
Reset
Input: (empty)
New input: a b c d e
Transformed: a b c d e (no transform)
New rules
Transformed: a ABC c DDD e
```

---

### Example ID: 152

**Description:** RewindOnChange

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var ExprT = uc.ExpressionTransformer;  // Transformer used for Eval() and Evaluate()

ExprT.DefaultRuleSet.RewindOnChange = true;

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
Console.WriteLine($"Input: {Expression}");
Console.WriteLine($"Transform: {ExprT.Transform(Expression)}");
Console.WriteLine($"Eval: {uc.Eval(Expression)}");
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

### Example ID: 154

**Description:** To_uCalcString

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "if (x > 3) y = x * 2; else if(x == 5) y = x - 1;";
t.FromTo("1", "100");
t.Transform();

var Pattern = "if ({cond})";
Console.WriteLine(new uCalc.String(t).After(Pattern).Text);
Console.WriteLine(new uCalc.String(t).After(Pattern).After(Pattern));

var s = new uCalc.String();
s = "This is a test";
Console.WriteLine(new uCalc.Transformer(s).Text);
```

**Output:**
```
y = x * 2; else if(x == 5) y = x - 100;
 y = x - 100;
This is a test
```

---

### Example ID: 155

**Description:** Transformer: Matching by tokens vs match by character; also whitespace sensitivity

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// This examples shows the default match by
// token mode, as well as how to reconfigure
// it in order to do match by character
// along with a whitespace variation

var t = uc.NewTransformer();
var txt = "This is an island test, I said.";
t.FromTo("is", "<is>");

Console.WriteLine(t.Transform(txt));
Console.WriteLine("");

t.Tokens.Description = "Match by character";
t.Tokens.Add("."); // This overrides existing tokens
t.FromTo("is", "<is>");
Console.WriteLine(t.Tokens.Description);
Console.WriteLine(t.Transform(txt));
Console.WriteLine("");

// Note: whitespace sensitivity is off by default
// Whitespace token is re-introduced
// (after being overridden in the previous Token Add())
t.Tokens.Description = "By char + whitespace ignored";
t.Tokens.Add("[\\t\\v ]+", TokenType.Whitespace);
t.FromTo("is", "<{@Self}>");
Console.WriteLine(t.Tokens.Description);
Console.WriteLine(t.Transform(txt));
```

**Output:**
```
This <is> an island test, I said.

Match by character
Th<is> <is> an <is>land test, I said.

By char + whitespace ignored
Th<is> <is> an <is>land test, <I s>aid.
```

---

### Example ID: 156

**Description:** Implicit Str(), Transform()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("a", "XY");

t.Text = "a b c a b c";
Console.WriteLine(t.Transform().Text); // Text that was set before trasnform
Console.WriteLine(t.Transform("c b a c b a").Text); // text passed to Transform()
Console.WriteLine(t.Transform("a, b, a, b")); // Implicit; Text property can be omitted
```

**Output:**
```
XY b c XY b c
c b XY c b XY
XY, b, XY, b
```

---

### Example ID: 157

**Description:** StrLength()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("a b c d e f");
t.FromTo("{ a | d }", "xy");

Console.WriteLine(t);
Console.WriteLine($"Length: {t.StrLength()}");
Console.WriteLine("");
Console.WriteLine(t.Transform());
Console.WriteLine($"Length: {t.StrLength()}");
```

**Output:**
```
a b c d e f
Length: 11

xy b c xy e f
Length: 13
```

---

### Example ID: 158

**Description:** Transformer.uCalc

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.uCalc.DefineVariable("xyz = 123");

t.FromTo("xyz", "{@Eval: xyz * 10}");
Console.WriteLine(t.Transform("The answer is: xyz"));
```

**Output:**
```
The answer is: 1230
```

---

### Example ID: 159

**Description:** WasModified

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("a", "*a good*");

t.Text = "This is a test";
Console.WriteLine(t.Transform());
Console.WriteLine($"Modified: {t.WasModified}");
Console.WriteLine("");

t.Text = "This is another test";
Console.WriteLine(t.Transform());
Console.WriteLine($"Modified: {t.WasModified}");
```

**Output:**
```
This is *a good* test
Modified: True

This is another test
Modified: False
```

---

### Example ID: 160

**Description:** Changing the parent uCalc object for a Transformer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 1");
uc.DefineVariable("y = 2");
uc.DefineFunction("f(x) = x * 10");

var t = uc.NewTransformer();
var text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}";

var uNew = new uCalc();
uNew.DefineVariable("x = 111");
uNew.DefineVariable("y = 222");
uNew.DefineFunction("f(x) = x * 1000");

// Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)}
// which is what's needed for to evaluate the expression
// resulting from the match that is not known ahead of time
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
Console.WriteLine(t.Transform(text));

t.uCalc = uNew;
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
Console.WriteLine(t.Transform(text));

```

**Output:**
```
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000
```

---

### Example ID: 161

**Description:** "using" (C#) and Owned (C++) for auto-releasing uCalc object

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

uc.IsDefault = true; // Set uc as the default uCalc object
uCalc.DefaultInstance.DefineVariable("Value = 'Original uc object'");
Console.WriteLine(uCalc.DefaultInstance.EvalStr("Value")); // Outputs: Original uc object

// Use "using" so that the object is auto-released when it it goes out of scope
using (var uCalcTemp = new uCalc()) {
   uCalcTemp.IsDefault = true; // Set uCalcTemp as the default uCalc object
   uCalc.DefaultInstance.DefineVariable("Value = 'uCalcTemp object'");
   Console.WriteLine(uCalc.DefaultInstance.EvalStr("Value")); // uCalcTemp object
}
// uCalcTemp goes out of scope here, and the default uCalc object reverts back to uc

Console.WriteLine(uCalc.DefaultInstance.EvalStr("Value")); // Original uc object

{
   /*using*/ var uCalcSticky = new uCalc(); // remains the default even after going out of scope
   uCalcSticky.IsDefault = true; // Set uCalcSticky as the default uCalc object
   uCalc.DefaultInstance.DefineVariable("Value = 'uCalcSticky object'");
   Console.WriteLine(uCalc.DefaultInstance.EvalStr("Value")); // Outputs: uCalcSticky object
}    // The uCalcSticky object itself goes out of scope here, but internally it remains the default uCalc object

Console.WriteLine(uCalc.DefaultInstance.EvalStr("Value"));
```

**Output:**
```
Original uc object
uCalcTemp object
Original uc object
uCalcSticky object
uCalcSticky object
```

---

### Example ID: 162

**Description:** "using" (C#) and Owned (C++) for auto-releasing Transformer object

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

var t = new uCalc.Transformer(uc);
var MemIndex = t.MemoryIndex;
t.Release(); // MemIndex will be recycled and assigned to the next def

// Use "using" so that the object is auto-released when it it goes out of scope
using (var TempTransform = new uCalc.Transformer(uc)) {
   Console.WriteLine(TempTransform.MemoryIndex == MemIndex); // MemoryIndex() will be the recycled value of the released t object
}
// TempTransform goes out of scope here

var t3 = new uCalc.Transformer(uc);
Console.WriteLine(t3.MemoryIndex == MemIndex); // MemoryIndex() will be the recycled value of the released TempTransform object
t3.Release();

{
   // Use "using" so that the object is auto-released when it it goes out of scope
   var StickyTransformer = new uCalc.Transformer(uc);
   Console.WriteLine(StickyTransformer.MemoryIndex == MemIndex);
} // StickyTransformer remains in memery

var t4 = new uCalc.Transformer(uc);
Console.WriteLine(t4.MemoryIndex == MemIndex); // False since StickyTransformer was not released; MemoryIndex() has a new value
```

**Output:**
```
True
True
True
False
```

---

### Example ID: 163

**Description:** Token Add(ExistingToken)

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

var t1 = uc.NewTransformer();
var CommentRegex = """
/\*([\s\S]*?)\*/
""";
var WhitespaceToken = t1.Tokens.Add(CommentRegex, TokenType.Whitespace);
WhitespaceToken.Description = "Treats text between /* and */ as whitespace";

var txt = "a b, a /* comment a b */ b, a x b, ab, a   b, a, b";

var t2 = uc.NewTransformer();
t2.FromTo("a b", "<{@Self}>");
t2.Transform(txt);
Console.WriteLine(t2);

// The token defined in the other transformer (WhitespaceToken) is imported into this one.
// Now, everything between /* and */ will be treated as whitespace
t2.Tokens.Add(WhitespaceToken);
Console.WriteLine(t2.Transform(txt));
```

**Output:**
```
<a b>, a /* comment <a b> */ b, a x b, ab, <a   b>, a, b
<a b>, <a /* comment a b */ b>, a x b, ab, <a   b>, a, b
```

---

### Example ID: 165

**Description:** Defining a token bracket pair

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// Here we define < and > as a bracket pair.
// Such pairs can be part of a pattern match
// and a match can be found within a bracket pair
// but a match will not cross boundaries with one
// part of the match out and another part inside

var t = uc.NewTransformer();
var txt = "a < b c > c, < a > b c, < a b c >";

t.Tokens.Add("<", TokenType.Generic, ">");
t.FromTo("a {etc} c", "((a {etc} c))");

Console.WriteLine(txt);
Console.WriteLine(t.Transform(txt));
```

**Output:**
```
a < b c > c, < a > b c, < a b c >
((a < b c > c)), < a > b c, < ((a b c)) >
```

---

### Example ID: 166

**Description:** Defining quoted text 

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// In example we'll define quoted text using < and > as
// surrounding quotes.  Singe and double quotes ' and "
// are already defined by default.  This is just an example.

// Quoted text must be defined as TokenType.Literal
// The last argument, 1, means that the literal part of the match will
// be the part of the regex found int the first parenthesis (here's
// there's only one set of parenthesis).

var t = uc.NewTransformer();
var SpecialQuotes = t.Tokens.Add("<([^>]*)>", TokenType.Literal, "", 1);
SpecialQuotes.SetDataType(BuiltInType.String);
SpecialQuotes.IsProperty(ItemIs.QuotedText, true);

t.Pattern("{token:1}");
Console.WriteLine(t.Filter("abc <some quoted text> xyz 123.456 + 25e2").Matches.Text);
Console.WriteLine("");

// Based on the definition, the part within < and > is the literal part
// passed to the string + operator used by EvalStr

uc.ExpressionTokens.Add(SpecialQuotes);
Console.WriteLine(uc.EvalStr("<some quoted text> + < plus more>"));
```

**Output:**
```
abc
<some quoted text>
xyz
123.456
+
25e2

some quoted text plus more
```

---

### Example ID: 167

**Description:** Importing a list of tokens from one transformer to another

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// This creates a simpler (not very useful) set of tokens for sake of example
var MyTokens = t.Tokens;
MyTokens.Clear(); // removes the default list of tokens
MyTokens.Add("."); // Should always have a fallback token like this one
MyTokens.Add(";", TokenType.StatementSep);
MyTokens.Add("<", TokenType.Generic, ">");
MyTokens.Add("[0-9]+", TokenType.Literal);
MyTokens.Add(" +", TokenType.Whitespace);
MyTokens.Add("[a-z]+", TokenType.AlphaNumeric);

t.FromTo("{ This | That} {etc}", "[{@Self}]"); // {etc} stops at the semicolon ";" TokenType.StatementSep

Console.WriteLine(t.Transform("This is a test; That < 123.456; abc >; ABC"));
Console.WriteLine("");

var OtherTransform = new uCalc.Transformer(uc); // This is an alternative way of constructing a new transformer
OtherTransform.Tokens.Add(MyTokens); // Imports the entire token list from the other transformer
OtherTransform.Pattern("{word:1}");

Console.WriteLine(OtherTransform.Filter("This is a test; That < 123.456; abc >; ABC").Matches.Text);

```

**Output:**
```
[This is a test]; [That < 123.456; abc >]; ABC

This
is
a
test
;
That
<
123
.
456
;
abc
>
;
ABC
```

---

### Example ID: 168

**Description:** Token Context switch

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var CommentTransform = uc.NewTransformer();
var CommentTokens = CommentTransform.Tokens;
CommentTokens.Add(".");
CommentTokens.Add("[a-z]+");

var txt = "'This is it' /* 'This is it' This is it */ This is it";

var t = uc.NewTransformer();
t.FromTo("is", "<is>");
Console.WriteLine(t.Transform(txt).Text);

// Now the context will switch between /* and */
// In that context there's no quoted text token,
t.Tokens.ContextSwitch(CommentTokens, "/\\*", "\\*/");
t.FromTo("is", "<is>");
Console.WriteLine(t.Transform(txt).Text);

```

**Output:**
```
'This is it' /* 'This is it' This <is> it */ This <is> it
'This is it' /* 'This <is> it' This <is> it */ This <is> it
```

---

### Example ID: 169

**Description:** Token Remove

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// This example removes the single quote pattern from the list

var t = uc.NewTransformer();
var txt = "This is a test, 'This is a test'";
t.FromTo("{token:1}", "<{@Self}>");
Console.WriteLine(t.Transform(txt).Text);

// Now the ' character will no longer be special
// (see the Name() example for list of token names
t.Tokens.Remove(t.Tokens["_token_string_singlequoted"]);
Console.WriteLine(t.Transform(txt).Text);
```

**Output:**
```
<This> <is> <a> <test><,> <'This is a test'>
<This> <is> <a> <test><,> <'><This> <is> <a> <test><'>
```

---

### Example ID: 170

**Description:** Token(TokenType)

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.ExpressionTokens[TokenType.AlphaNumeric].Name);
Console.WriteLine(uc.ExpressionTokens[TokenType.AlphaNumeric].Regex);
Console.WriteLine("");

// Note: In C# or VB you can simply use [TokenType::Literal, n]
// instead of ByType(TokenType::Literal, n)
Console.WriteLine(uc.ExpressionTokens.ByType(TokenType.Literal, 0).Name);
Console.WriteLine(uc.ExpressionTokens.ByType(TokenType.Literal, 1).Name);
Console.WriteLine(uc.ExpressionTokens.ByType(TokenType.Literal, 2).Name);
```

**Output:**
```
_token_alphanumeric
[a-zA-Z_][a-zA-Z0-9_]*

_token_string_singlequoted
_token_string_doublequoted
_token_string_tripledoublequoted
```

---

### Example ID: 171

**Description:** uCalc Description

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.Description = "This is the main uCalc object";
var t = uc.NewTransformer();
Console.WriteLine(t.Tokens.uCalc.Description);
```

**Output:**
```
This is the main uCalc object
```

---

### Example ID: 173

**Description:** Pattern: Simple Variable Capture

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t = "Here is the temperature: 98.6 F";

// Define the pattern first
t.Pattern("Temperature: {temp} F");

// Then execute the search
t.Find();

Console.WriteLine(t.Matches[0]);
```

**Output:**
```
temperature: 98.6 F
```

---

### Example ID: 174

**Description:** Converting from Celsius to Fahrenheit with the Transformer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Define the pattern first
t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F");

// Perform the Transform() operation
Console.WriteLine(t.Transform("Here is the temperature: 22.5 C"));
```

**Output:**
```
Here is the temperature: 72.5 F
```

---

### Example ID: 175

**Description:** Turn new line into whitespace with Tokens.Add

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("<{tag}>{code}</{tag}>", "[{tag}]{code}[/{tag}]");
var MyStr = """
<div>Single line</div>
<div>Line 1
Line 2
Line 3
Line 4</div>
""";

Console.WriteLine("New line as statement separator (default)");
Console.WriteLine("");
Console.WriteLine(t.Transform(MyStr).Text);
Console.WriteLine("");

Console.WriteLine("New line as whitespace");
Console.WriteLine("");
t.Tokens.Add("[\\r\\n]+", TokenType.Whitespace);
Console.WriteLine(t.Transform(MyStr).Text);



```

**Output:**
```
New line as statement separator (default)

[div]Single line[/div]
<div>Line 1
Line 2
Line 3
Line 4</div>

New line as whitespace

[div]Single line[/div]
[div]Line 1
Line 2
Line 3
Line 4[/div]
```

---

### Example ID: 176

**Description:** Matching by token type

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = """
This is   55.2*6 "Hello world";
'Single quote'(parenth)
""";

Console.WriteLine(t.Filter(s).Matches.Text);
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 177

**Description:** {@Alphanumeric}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("({@Alphanumeric:txt})", "<Alpha str={txt}>");

Console.WriteLine(t.Transform("Testing 123 (456) (abc) ('text') (xyz111)"));
```

**Output:**
```
Testing 123 (456) <Alpha str=abc> ('text') <Alpha str=xyz111>
```

---

### Example ID: 178

**Description:** TypeOfToken

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// See uCalc.Tokens.Count() example for list of token names

var t = uc.NewTransformer();
var MyToken = t.Tokens.Add("###");
var Alpha = t.Tokens["_token_alphanumeric"];

Console.WriteLine(MyToken.TypeOfToken == TokenType.AlphaNumeric);
Console.WriteLine(MyToken.TypeOfToken == TokenType.Generic);
Console.WriteLine(Alpha.TypeOfToken == TokenType.AlphaNumeric);
Console.WriteLine(Alpha.TypeOfToken == TokenType.Generic);


```

**Output:**
```
False
True
True
False
```

---

### Example ID: 179

**Description:** {@Whitespace}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("{@Whitespace}", ",");

Console.WriteLine(t.Transform("This is   a 'small test' about ' whitespace ' tokens."));
```

**Output:**
```
This,is,a,'small test',about,' whitespace ',tokens.
```

---

### Example ID: 184

**Description:** {@StatementSeparator}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("{@StatementSeparator}", "<sep>");
Console.WriteLine(t.Transform("a = b + c; x = y + 1;"));
```

**Output:**
```
a = b + c<sep> x = y + 1<sep>
```

---

### Example ID: 185

**Description:** {@Token} - matching a token by name

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("{@String}", "<Any quoted {@Self}>");
t.FromTo("({@Token(String_Singlequoted)})", "<Single quoted {@Self}>");
t.FromTo("({@Token(String_Doublequoted)})", "<Double quoted {@Self}>");

var s = """
"Test" '123' ("abc") ('xyz')
""";
Console.WriteLine(t.Transform(s));
```

**Output:**
```
<Any quoted "Test"> <Any quoted '123'> <Double quoted ("abc")> <Single quoted ('xyz')>
```

---

### Example ID: 187

**Description:** RulePatternTransformer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

var Pattern = uc.TransformerForRulePatterns;
var Replacement = uc.TransformerForRuleReplacements;

Pattern.FromTo("@sq", "{@Eval: '{@Token(_Token_String_SingleQuoted)}'}");
Replacement.FromTo("~", "{@Eval: '{@Self}'}");

t.FromTo("@sq", "<single quote txt = ~>");
// Same as t.FromTo("{@Token(_Token_QuoteChar_Single)}", "<single quote txt = {@Self}>");

Console.WriteLine(t.Transform("Test: 'some text'."));




```

**Output:**
```
Test: <single quote txt = 'some text'>.
```

---

### Example ID: 188

**Description:** Transformer constructor

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine("Transformer constructors");
var t1 = new uCalc.Transformer(); // New transformer in default uCalc space
var t2 = new uCalc.Transformer(uc); // New transformer inherits
var t3 = new uCalc.Transformer(t1.Tokens); // Imports tokens from t1
```

**Output:**
```
Transformer constructors
```

---

### Example ID: 189

**Description:** Whitespace

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("Hello World", "<{@Self}>");
Console.WriteLine(t.Transform("Hello World. HelloWorld. Hello     World. Hello, World."));
```

**Output:**
```
<Hello World>. HelloWorld. <Hello     World>. Hello, World.
```

---

### Example ID: 190

**Description:** Searching for two different words in parallel.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Define concurrent patterns
t.FromTo("Mango", "[Fruit]");
t.FromTo("Car", "[Vehicle]");

Console.WriteLine(t.Transform("I have a Mango and a Car."));

```

**Output:**
```
I have a [Fruit] and a [Vehicle].
```

---

### Example ID: 191

**Description:** More concurrent patterns

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.Pattern("This {etc} a");
t.Pattern("{@String}");
t.Pattern("{ big | small }");
t.Pattern("Only {words:2}");

Console.WriteLine(t.Filter("This is just a small Test to see 'how' patterns work. Only a test!").Matches.Text);
```

**Output:**
```
This is just a
small
'how'
Only a test
```

---

### Example ID: 192

**Description:** Order of concurrent patterns

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Note: Since the patterns start the same,
//       the order in which they're defined matters.
t.FromTo("An {item}", "<{@Self}>");
t.FromTo("An {item}.", "[{@Self}]");
t.FromTo("An {item:2}.", "({@Self})");
t.FromTo("An orange.", "{{@Self}}");

Console.WriteLine(t.Transform("An apple. An orange. An elephant."));
Console.WriteLine(t.Transform("An angry bear. An extremely big dog!"));
```

**Output:**
```
[An apple.] {An orange.} [An elephant.]
(An angry bear.) <An extremely big dog!>
```

---

### Example ID: 193

**Description:** Variables and anchors

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("is {etc} see", "({@Self})");
Console.WriteLine(t.Transform("This is a test to see how anchors/variables work"));
```

**Output:**
```
This (is a test to see) how anchors/variables work
```

---

### Example ID: 194

**Description:** More on variables and anchors

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Variables are {etc} and {ch}
// Anchors are "This", either "a small" or "an easy", and "Test"

t.FromTo("This {etc} {ch: a small | an easy } Test", "<{etc}> ({ch}) experiment");
Console.WriteLine(t.Transform("This is such an easy test."));
```

**Output:**
```
<is such> (an easy) experiment.
```

---

### Example ID: 195

**Description:** Named optional part

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("a [{option: small | big }] test",
"a sample test{option: categorized as '{option}'}");

Console.WriteLine(t.Transform("This is a test."));
Console.WriteLine(t.Transform("This is a big test."));
Console.WriteLine(t.Transform("This is a small test."));
Console.WriteLine(t.Transform("This is a random test."));
```

**Output:**
```
This is a sample test.
This is a sample test categorized as 'big'.
This is a sample test categorized as 'small'.
This is a random test.
```

---

### Example ID: 196

**Description:** Alternative parts

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("This is a {adjective: simple | small | nice } test",
"The adjective in '{@Self}' is: {adjective}.");

Console.WriteLine(t.Transform("This is a test"));
Console.WriteLine(t.Transform("This is a simple test"));
Console.WriteLine(t.Transform("This is a small test"));
Console.WriteLine(t.Transform("This is a nice test"));
Console.WriteLine(t.Transform("This is a random test"));

```

**Output:**
```
This is a test
The adjective in 'This is a simple test' is: simple.
The adjective in 'This is a small test' is: small.
The adjective in 'This is a nice test' is: nice.
This is a random test
```

---

### Example ID: 197

**Description:** Optional part

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("a [simple] test", "<{@Self}>");

Console.WriteLine(t.Transform("Is this a simple test, or a hard test, or just a test?"));
```

**Output:**
```
Is this <a simple test>, or a hard test, or just <a test>?
```

---

### Example ID: 198

**Description:** Optional part; value when optional part not used

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("This is a [{adj: simple}] test",
"Let's take the {adj}{!adj:short} test");

Console.WriteLine(t.Transform("This is a test"));
Console.WriteLine(t.Transform("This is a simple test"));
```

**Output:**
```
Let's take the short test
Let's take the simple test
```

---

### Example ID: 199

**Description:** Using the same pattern variable multiple times in a pattern

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// When a variable is used multiple times in a pattern,
// such as {tag} in this case, the matching text must be the same

t.FromTo("<{tag}> {words:2} {more} </{tag}>",
"tag={tag}, 2 words={words}, text={more}");

Console.WriteLine(t.Transform("<div>abc xyz more words<b>bold</b></div>").Text);
```

**Output:**
```
tag=div, 2 words=abc xyz, text=more words<b>bold</b>
```

---

### Example ID: 200

**Description:** Matching a certain number of tokens

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("is {TokenCount:4}", "is <{TokenCount}>");
Console.WriteLine("This example captures 4 tokens");
Console.WriteLine(t.Transform("This is just a small token match test"));

// Quoted text counts as one token
Console.WriteLine(t.Transform("This is a 'really really' small test with quoted text"));
```

**Output:**
```
This example captures 4 tokens
This is <just a small token> match test
This is <a 'really really' small test> with quoted text
```

---

### Example ID: 201

**Description:** {@Eval}, {@@Eval}, and escaping special characters in a pattern

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("'['{word}']'", "{@Eval: UCase(word)}");
t.FromTo("'{'{expr}'}'", "{@@Eval: expr}");

Console.WriteLine(t.Transform("Words like [this] and [that]."));
Console.WriteLine(t.Transform("Is {5*3} bigger than {5^3}?"));
```

**Output:**
```
Words like THIS and THAT.
Is 15 bigger than 125?
```

---

### Example ID: 202

**Description:** Transforming numeric ASCII codes to text characters

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("{#97#98#99}", "{#120#121#122}");
// Same as t.FromTo("abc", "xyz")

Console.WriteLine(t.Transform("abc"));
```

**Output:**
```
xyz
```

---

### Example ID: 203

**Description:** {@All}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("{@All}", "<<{@Self}>>");

Console.WriteLine(t.Transform("This is a test"));
```

**Output:**
```
<<This is a test>>
```

---

### Example ID: 205

**Description:** {@Comment}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("a {@Comment: Ignore this} b c", "x{@Comment: ignore} y z");

Console.WriteLine(t.Transform("a b. a b c. abc."));
```

**Output:**
```
a b. x y z. abc.
```

---

### Example ID: 206

**Description:** {@Define}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.Pattern("{@Define: Var: xyz = 123}");
t.FromTo("abc", "{@Eval: xyz * 10}");
Console.WriteLine(t.Transform("The value is: abc"));

```

**Output:**
```
The value is: 1230
```

---

### Example ID: 207

**Description:** {@Doc}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("a test", "'{@Self}' is part of: '{@Doc}'");

// Note: .Str(0) here is a shortcut for .Matches().Str(0)
Console.WriteLine(t.Transform("This sentence is just a test").Str(0));
```

**Output:**
```
'a test' is part of: 'This sentence is just a test'
```

---

### Example ID: 208

**Description:** {@Param}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("This {etc} big test {words:2}",
"{@Param:0}:{@Param:1}:{@Param:1+1}:{@Param:2+1}:{@Param:2*2}");
Console.WriteLine(t.Transform("This is a big test we have today"));
```

**Output:**
```
This:is a:big:test:we have today
```

---

### Example ID: 209

**Description:** {@Stop}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// without {@Stop} "end" wouldn't be a match
t.FromTo("StopAt {abc} {@Stop} end", "<{abc}>");
t.FromTo("end", "[The End]");

Console.WriteLine(t.Transform("StopAt a b c end"));

```

**Output:**
```
<a b c> [The End]
```

---

### Example ID: 210

**Description:** Ignore quote directive `

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("a {txt} c", "<{@Self}>"); // Quoted text treated as 1 token
t.FromTo("x {txt`} z", "<{@Self}>"); // Quotes treated as ordinary chars

Console.WriteLine(t.Transform("a 'b c' b c :: x 'y z' y z"));
```

**Output:**
```
<a 'b c' b c> :: <x 'y z>' y z
```

---

### Example ID: 212

**Description:** Ignore bracket directive ^

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("begin {body} end",   "bracket not ignored: <{@Self}>");
t.FromTo("begin_ {body^} end", "bracket ignored:     <{@Self}>");

Console.WriteLine(t.Transform("begin (a b c end) end"));
Console.WriteLine(t.Transform("begin_ (a b c end) end"));
```

**Output:**
```
bracket not ignored: <begin (a b c end) end>
bracket ignored:     <begin_ (a b c end>) end
```

---

### Example ID: 213

**Description:** Pattern directive to skip nested pattern matching

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("start {etc} end", "<{@Self}>");
t.FromTo("start2 {etc~} end", "<{@Self}>");

Console.WriteLine(t.Transform("start start2 a b c end end"));
Console.WriteLine(t.Transform("start2 start a b c end end"));
```

**Output:**
```
<start start2 a b c end end>
<start2 start a b c end> end
```

---

### Example ID: 214

**Description:** TransformArg directive

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("abc", "changed to xyz");
t.FromTo("Quote1({arg})", "'{arg}'");
t.FromTo("Quote2({arg%})", "'{arg}'");

Console.WriteLine(t.Transform("Quote1(abc), Quote2(abc)"));

```

**Output:**
```
'abc', 'changed to xyz'
```

---

### Example ID: 215

**Description:** WhitespaceCounts

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("A {txtA}. B {txtB$}.", "<{txtA}> <{txtB}>");

Console.WriteLine(t.Transform("A     x y z . B     x y z ."));
```

**Output:**
```
<x y z> <     x y z >
```

---

### Example ID: 216

**Description:** {@Exec}

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.Pattern("{@Define: Var: Count_a = 0}");
t.Pattern("{@Define: Var: Count_an = 0}");

t.FromTo("a", "{@Self}{@Exec: Count_a++}");
t.FromTo("an", "{@Self}{@Exec: Count_an++}");
t.FromTo(".", """
{@nl}'a' occurs {@Eval: Count_a} times
'an' occurs {@Eval: Count_an} times
""");

// Note: it is counting "a" as a token, not as a character.
Console.WriteLine(t.Transform("An apple, an eagle, a cat, an orange, a tree."));
```

**Output:**
```
An apple, an eagle, a cat, an orange, a tree
'a' occurs 2 times
'an' occurs 3 times
```

---

### Example ID: 217

**Description:** IgnoreStatementSeparator +

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.FromTo("a {txt} c", "<{@Self}>");
t.FromTo("x {txt+} z", "<{@Self}>");

Console.WriteLine(t.Transform("a b c; :: x y z; :: a b; c :: x y; z"));
```

**Output:**
```
<a b c>; :: <x y z>; :: a b; c :: <x y; z>
```

---

### Example ID: 218

**Description:** Test: Complex Nesting & Backreferences

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "Start A ( 1 2 3 ) End A ... Start B ( 9 ) End B";

// {id} captures "A". {content} captures the block.
// The final {id} MUST match the first {id} ("A" == "A").
// If the text was "Start A ... End B", this pattern would NOT match.
t.Pattern("Start {id} ( {content} ) End {id:1}");

// +++ w/o 1 in {id:1} it tries to capture more than one token at
// position.  Investigate if it should logically be possible without 1

t.Find();
Console.WriteLine($"Matches: {t.Matches.Count()}");
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
Matches: 2
Start A ( 1 2 3 ) End A
Start B ( 9 ) End B
```

---

### Example ID: 219

**Description:** Test: Complex Nesting & Backreferences using XML-style tags.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<section> <item> A </item> </section>";

// {tag} captures "section". {content} captures the inner content.
// The closing </{tag}> MUST match the opening <{tag}>.
t.Pattern("<{tag}> {content} </{tag}>");

Console.WriteLine(t.Find().Matches.Text);
// This will match the outer <section> block.
// If the text was "<section> ... </div >", it would NOT match.

Console.WriteLine("-----");
t.Str("""

<br><section> <item> A </item> </section>
<br><br><div> <item> A b c </item> </div>
<br> <div> <item> <div>x y z</div> </item> </div>

""");
Console.WriteLine(t.Find().Matches.Text);
```

**Output:**
```
<section> <item> A </item> </section>
-----
<section> <item> A </item> </section>
<div> <item> A b c </item> </div>
<div> <item> <div>x y z</div> </item> </div>
```

---

### Example ID: 220

**Description:** Change newline from statement separator to whitespace

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.Str("""

<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>

""");

t.Pattern("<div>{body}</div>");

Console.WriteLine("Newline as statement separator (default)");
Console.WriteLine("----------------------------------------");
Console.WriteLine(t.Find().Matches.Text);
Console.WriteLine("");

Console.WriteLine("Newline as whitespace");
Console.WriteLine("---------------------");
t.Tokens["_token_newline"].TypeOfToken = TokenType.Whitespace;
Console.WriteLine(t.Find().Matches.Text);
```

**Output:**
```
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
```

---

### Example ID: 221

**Description:** Change newline from statement separator to whitespace using TypeOfToken

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.Str("""

<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>

""");

t.Pattern("<div>{body}</div>");
var NewLineToken = t.Tokens["_token_newline"];

Console.WriteLine("Newline as statement separator (default)");
Console.WriteLine("----------------------------------------");
Console.WriteLine(t.Find().Matches.Text);
Console.WriteLine("");

Console.WriteLine("Newline as whitespace");
Console.WriteLine("---------------------");
NewLineToken.TypeOfToken = TokenType.Whitespace;
Console.WriteLine(t.Find().Matches.Text);
```

**Output:**
```
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
```

---

### Example ID: 223

**Description:** Using {@Whitespace} and {@Exec} to Count Indentation (for Python or YAML-like text)

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Using {@Whitespace} to Count Indentation
// A common use case for parsing structured text (like Python or YAML)
// is capturing the exact whitespace at the start of a line.

uc.DefineVariable("IndentLen");

var t = uc.NewTransformer();
t.Text = "    Item 1"; // Indented by 4 spaces

// Capture the leading whitespace into 'w' and evaluate its length
t.FromTo("{@Whitespace:w} Item {id}", "<{@Self}>{@Exec: IndentLen = Length(w)}");
t.Transform();
// We can now analyze the captured whitespace
Console.WriteLine($"Indentation length: {uc.EvalStr("IndentLen")}");
```

**Output:**
```
Indentation length: 4
```

---

### Example ID: 224

**Description:** A simple "Hello World" transformation demonstrating variable capture.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Define a rule to swap the name into a greeting
t.FromTo("Hello {name}", "Greetings, {name}!");
Console.WriteLine(t.Transform("Hello World"));
```

**Output:**
```
Greetings, World!
```

---

### Example ID: 227

**Description:** Demonstrating in-place modification with uCalc.String.Replace

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uCalc.String text = "This is foo 1, foo 2, Foo 3, foo 4";
text.After("1").Before("3").Replace("foo", "bar"); // 'text' is now modified
Console.WriteLine(text);
```

**Output:**
```
This is foo 1, bar 2, bar 3, foo 4
```

---

### Example ID: 228

**Description:** A simple Lexer/Tokenizer that categorizes content into numbers, operators, or keywords.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Note how the definition order matters if patterns overlap (though here they are distinct).
var t = uc.NewTransformer();

// Define patterns for a simple math language
t.FromTo("{d: {@Number}}", "[NUM:{d}]");
t.FromTo("{op: + | - | * | / }", "[OP:{op}]");
t.FromTo("print", "[CMD:PRINT]"); // Specific keyword

var code = "print 10 + 20";
Console.WriteLine(t.Transform(code));
```

**Output:**
```
[CMD:PRINT] [NUM:10] [OP:+] [NUM:20]
```

---

### Example ID: 229

**Description:** Testing the "Last In, First Out" precedence rule with overlapping anchors.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Priority Test: All start with "An"
// 1. Defined first (lowest priority for same start)
t.FromTo("An {item}", "Match1: {item}");

// 2. Defined second
t.FromTo("An {item}.", "Match2: {item}");

// 3. Defined last (Highest priority for same start)
t.FromTo("An orange.", "Match3: orange");

// Input text
var txt = "An orange. An apple. An elephant.";

// "An orange." matches Rule 3 (Specific, defined last)
// "An apple." fails Rule 3, matches Rule 2 (Ending in dot)
// If input is "An elephant" (no dot), it falls back to Rule 1.

Console.WriteLine(t.Transform("An orange."));   // Match3: Orange
Console.WriteLine(t.Transform("An apple."));    // Match2: apple
Console.WriteLine(t.Transform("An elephant"));  // Match1: elephant
```

**Output:**
```
Match3: orange
Match2: apple
Match1: elephant
```

---

### Example ID: 230

**Description:** Basic Key-Value extraction using a colon as an anchor.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// "ID" and ":" are Anchors. "{id}" is the Variable.
t.FromTo("ID: {id}", "Found ID: {id}");
Console.WriteLine(t.Transform("ID: 12345").Text); 
```

**Output:**
```
Found ID: 12345
```

---

### Example ID: 231

**Description:** Parsing a standard connection string. Note how the semicolon acts as both an anchor and a natural statement separator.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Anchors: "Server", "=", ";", "Database"
// Variables: {srv}, {db}
t.FromTo("Server={srv};Database={db};",
"Connecting to database '{db}' on server '{srv}'...");

var connStr = "Server = LocalHost; Database = MyData;";
Console.WriteLine(t.Transform(connStr).Text);
// Note: Spaces around '=' handled automatically by default tokenization.
```

**Output:**
```
Connecting to database 'MyData' on server 'LocalHost'...
```

---

### Example ID: 232

**Description:** Testing **Statement Separators** vs **Constraints**.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// 1. Separator Stop: {v} stops at newline (default separator)
t.FromTo("Value: {v}", "Captured: [{v}]");
Console.WriteLine(t.Transform("""
Value: 100
Value: 200
""").Text);

// 2. Constraint vs Ambiguity:
// {a}{b} is currently ambiguous (usually {a} eats everything).
// {a:2}{b:1} is deterministic.
t.FromTo("{a:2}{b:1}", "A:[{a}], B:[{b}]");
Console.WriteLine(t.Transform("one two three"));
```

**Output:**
```
Captured: [100]
Captured: [200]
A:[one two], B:[three]
```

---

### Example ID: 234

**Description:** Using **Conditional Blocks** to format an optional title.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Pattern: Name followed optionally by a Title in parens.
t.FromTo("Name: {n} [({title})]",
"User: {n} {title:[Title: {title}]}");

// Case 1: Title exists
Console.WriteLine(t.Transform("Name: Alice (Manager)"));

// Case 2: Title missing
Console.WriteLine(t.Transform("Name: Bob"));
// (The entire "[Title: ...]" block is omitted)
```

**Output:**
```
User: Alice [Title: Manager]
User: Bob
```

---

### Example ID: 236

**Description:** Matching one of several keywords.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("Status: { OK | Error | Pending }", "Found Status");

Console.WriteLine(t.Transform("Status: OK"));    // Output: Found Status
Console.WriteLine(t.Transform("Status: Error")); // Output: Found Status
Console.WriteLine(t.Transform("Status: Fail"));  // No Match (Output unchanged)
```

**Output:**
```
Found Status
Found Status
Status: Fail
```

---

### Example ID: 237

**Description:** Parsing boolean values that might be represented differently.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Normalize "True/Yes/On" to "TRUE" and "False/No/Off" to "FALSE"
t.FromTo("{ True | Yes | On }", "TRUE");
t.FromTo("{ False | No | Off }", "FALSE");

Console.WriteLine(t.Transform("System is On"));    // Output: System is TRUE
Console.WriteLine(t.Transform("Power is False"));  // Output: Power is FALSE
```

**Output:**
```
System is TRUE
Power is FALSE
```

---

### Example ID: 238

**Description:** Nested alternatives and variable capture.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Pattern: "Set" followed by (Color OR (Size followed by Big/Small))
// Note: Nesting syntax { A | { B | C } } validation
t.FromTo("Set { Color | Size { Big | Small } }", "Matched");

Console.WriteLine(t.Transform("Set Color"));      // Match
Console.WriteLine(t.Transform("Set Size Big"));   // Match
Console.WriteLine(t.Transform("Set Size Medium"));// No Match
```

**Output:**
```
Matched
Matched
Set Size Medium
```

---

### Example ID: 239

**Description:** Handling an optional trailing semicolon.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("Statement: {val} [;]", "Found: {val}");

Console.WriteLine(t.Transform("Statement: x = 1;")); // Output: Found: x = 1
Console.WriteLine(t.Transform("Statement: y = 2"));  // Output: Found: y = 2
```

**Output:**
```
Found: x = 1
Found: y = 2
```

---

### Example ID: 240

**Description:** Parsing names with an optional middle name.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Matches "First Last" OR "First Middle Last"
// Constraint Note: We use {name:1} to ensure each variable captures exactly one token.
// Replacement Note: We use {middle: {middle}} instead of just {middle} to prepend
// a space only if the middle name exists.
t.FromTo("Name: {first:1} [{middle:1}] {last:1}",
"User: {last}, {first}{middle: {middle}}");

Console.WriteLine(t.Transform("Name: John Doe"));
Console.WriteLine(t.Transform("Name: John Quincy Adams")); 
```

**Output:**
```
User: Doe, John
User: Adams, John Quincy
```

---

### Example ID: 241

**Description:** Nested optional blocks.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Pattern: A, optionally followed by B, which is optionally followed by C.
// Valid inputs: "A", "A B", "A B C". Invalid: "A C" (since C requires B).
t.FromTo("A [ B [ C ] ]", "Matched");

Console.WriteLine(t.Transform("A"));     // Matched
Console.WriteLine(t.Transform("A B"));   // Matched
Console.WriteLine(t.Transform("A B C")); // Matched
Console.WriteLine(t.Transform("A C"));   // Matched C
```

**Output:**
```
Matched
Matched
Matched
Matched C
```

---

### Example ID: 242

**Description:** Grouping alternatives to limit scope.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Matches "File Open" or "File Close".
// Capture needs explicit naming.
t.FromTo("File {cmd: Open | Close }", "Command: {cmd}");

Console.WriteLine(t.Transform("File Open"));
Console.WriteLine(t.Transform("File Close"));
```

**Output:**
```
Command: Open
Command: Close
```

---

### Example ID: 243

**Description:** Nested grouping for complex commands.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Pattern: "Set" followed by (Color OR (Size followed by Big/Small))
t.FromTo("Set {prop: Color | Size { Big | Small } }", "Property: {prop}");

Console.WriteLine(t.Transform("Set Color"));
Console.WriteLine(t.Transform("Set Size Big"));
Console.WriteLine(t.Transform("Set Size Small"));
```

**Output:**
```
Property: Color
Property: Size Big
Property: Size Small
```

---

### Example ID: 244

**Description:** Recursive Nesting: Alternation -> Optional -> Alternation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Structure:
// 1. Alternation: "Open" OR "Save"
// 2. Inside "Open": Optional "Recent"
// 3. Inside "Recent": Alternation "File" OR "Project"
var pattern = "Menu { Open [ Recent {type: File | Project } ] | Save }";

t.FromTo(pattern, "Action Detected");

Console.WriteLine(t.Transform("Menu Save"));                 // Match (Simple Alternation)
Console.WriteLine(t.Transform("Menu Open"));                 // Match (Optional omitted)
Console.WriteLine(t.Transform("Menu Open Recent File"));     // Match (Deep nesting)
Console.WriteLine(t.Transform("Menu Open Recent Project"));  // Match (Deep nesting alt)
```

**Output:**
```
Action Detected
Action Detected
Action Detected
Action Detected
```

---

### Example ID: 245

**Description:** Matching tokens by category.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Match a word (Alpha) followed by equals and a Number (Literal)
t.FromTo("{@Alpha} = {@Number}", "Assignment Detected");

Console.WriteLine(t.Transform("x = 10")); 
```

**Output:**
```
Assignment Detected
```

---

### Example ID: 246

**Description:** Customizing token definitions (e.g., treating hyphens as part of a word).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Now capture it using the {@Alpha} category
t.FromTo("{@Alpha:w}", "<{w}>");

Console.WriteLine("Before:");
Console.WriteLine(t.Transform("1. Start-Up 'big ideas' well-knwon."));

// Define a new token pattern for hyphenated words
// We assign it to the 'AlphaNumeric' category so it behaves like a word
t.Tokens.Add("[a-zA-Z-]+", TokenType.AlphaNumeric);
Console.WriteLine("After:");
Console.WriteLine(t.Transform("1. Start-Up 'big ideas' well-knwon."));
```

**Output:**
```
Before:
1. <Start>-<Up> 'big ideas' <well>-<knwon>.
After:
1. <Start-Up> 'big ideas' <well-knwon>.
```

---

### Example ID: 247

**Description:** Handling Brackets and Literals.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Capture a function call.
// {@Alpha} matches the name.
// '(' and ')' are Bracket tokens that ensure the content is captured correctly.
t.FromTo("{@Alpha:func} ( {args} )", "Call: {func} with {args}");

Console.WriteLine(t.Transform("myfunc('Hello World', (x + y) * 2 )"));
```

**Output:**
```
Call: myfunc with 'Hello World', (x + y) * 2
```

---

### Example ID: 250

**Description:** Extracting keys from a key-value list where keys must be identifiers.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Capture the alphanumeric key and any literal value
t.FromTo("{@Alpha:key} = {@Literal:val}", "KEY:[{key}] VAL:[{val}]");

var input = "Timeout = 100; User = 'Admin'";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
KEY:[Timeout] VAL:[100]; KEY:[User] VAL:['Admin']
```

---

### Example ID: 251

**Description:** (Real World: Currency Formatter) Finding raw numbers in a text stream and converting them to a formatted currency string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("Price: {@Number:amt}", "Price: ${amt}");

string input = "Item A Price: 19.99, Item B Price: 5";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
Item A Price: $19.99, Item B Price: $5
```

---

### Example ID: 252

**Description:** Finding instances where there are two or more consecutive whitespace tokens and reducing them to a single space.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Match two whitespace tokens and replace with one space
t.FromTo("{@Whitespace}", " ");

string messy = "var    x   =  100;";
Console.WriteLine(t.Transform(messy));
```

**Output:**
```
var x = 100;
```

---

### Example ID: 255

**Description:** Quick Start

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create a new instance
using (var calc = new uCalc()) {
   
   // Evaluate an expression
   Console.WriteLine(calc.Eval("2 + 3"));
}
```

**Output:**
```
5
```

---

### Example ID: 256

**Description:** Creating isolated evaluation contexts.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var main = new uCalc();
main.DefineVariable("rate = 0.05");

var scenarioA = main.Clone();
var scenarioB = main.Clone();

scenarioA.DefineVariable("rate = 0.10");
scenarioB.DefineVariable("rate = 0.20");

Console.WriteLine($"A: {scenarioA.Eval("1000 * rate")}");
Console.WriteLine($"B: {scenarioB.Eval("1000 * rate")}");
Console.WriteLine($"Main: {main.Eval("1000 * rate")}");
main.Release();
scenarioA.Release();
scenarioB.Release();

```

**Output:**
```
A: 100
B: 200
Main: 50
```

---

### Example ID: 258

**Description:** Registers a handler to log when division by zero occurs.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void LogAndResume(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine($"Logged error: {uc.Error.Message}");
   uc.Error.Response = ErrorHandlerResponse.Resume;
}


uc.Error.TrapOnDivideByZero = true;
uc.Error.AddHandler(LogAndResume);

Console.WriteLine("Start");
var Result = uc.Eval("5/0");   // Division by zero
Console.WriteLine("End");
```

**Output:**
```
Start
Logged error: Division by 0
End
```

---

### Example ID: 260

**Description:** Verifying alias removal and fallback behavior.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("a = 100");

var aliasB = uc.CreateAlias("b", "a");

Console.WriteLine($"Before release: {uc.EvalStr("b")}");
aliasB.Release();
Console.WriteLine($"After release: {uc.EvalStr("b")}");
```

**Output:**
```
Before release: 100
After release: Undefined identifier
```

---

### Example ID: 269

**Description:** Internal Test: Verifies the stack-like (LIFO) behavior of default instances using a scoped object.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Original default instance
uCalc.DefaultInstance.DefineVariable("id = 'Original'");
Console.WriteLine($"Current Default ID: {uCalc.DefaultInstance.EvalStr("id")}");

// Push a new default instance onto the stack
var ucA = new uCalc();
ucA.DefineVariable("id = 'Instance A'");
ucA.IsDefault = true;
Console.WriteLine($"Current Default ID: {uCalc.DefaultInstance.EvalStr("id")}");

// The 'NewUsing' block creates a temporary, scoped default instance

// The following instance will be auto-released at the end of the block
using (var ucB = new uCalc()) {
   ucB.DefineVariable("id = 'Instance B (temp)'");
   ucB.IsDefault = true; // Pushes 'ucB' onto the stack
   Console.WriteLine($"Current Default ID: {uCalc.DefaultInstance.EvalStr("id")}");
}

// 'ucB' has gone out of scope, so the default reverts to the previous one ('ucA')
Console.WriteLine($"Current Default ID (after scope exit): {uCalc.DefaultInstance.EvalStr("id")}");

// Manually unset 'ucA'
ucA.IsDefault = false;
Console.WriteLine($"Current Default ID (after unset): {uCalc.DefaultInstance.EvalStr("id")}");
```

**Output:**
```
Current Default ID: Original
Current Default ID: Instance A
Current Default ID: Instance B (temp)
Current Default ID (after scope exit): Instance A
Current Default ID (after unset): Original
```

---

### Example ID: 270

**Description:** Shows the initial count of default instances upon application startup.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// By default, a single uCalc instance is always available on the stack.
Console.WriteLine($"Initial default instance count: {uCalc.DefaultCount}");
```

**Output:**
```
Initial default instance count: 1
```

---

### Example ID: 271

**Description:** Manage separate parser contexts for different application modules.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// --- Main Application Context ---
// Starting with the 'uc' object as the initial default.
uCalc.DefaultInstance.DefineConstant("PI = 3.14159");
Console.WriteLine($"Initial Count: {uCalc.DefaultCount}");

// --- A Plugin needs a temporary, isolated context ---
using (var moduleCalc = new uCalc()) {
   moduleCalc.IsDefault = true; // Push the new instance onto the stack.
   Console.WriteLine($"Count after module pushes new default: {uCalc.DefaultCount}");

   // The module's context is now active.
   // uCalc::DefaultInstance() would now return 'moduleCalc'.
}

// When 'moduleCalc' goes out of scope, it's destroyed and automatically
// removed from the stack, restoring the previous default.

Console.WriteLine($"Count after module instance is disposed: {uCalc.DefaultCount}");

// Verify the original default instance is active again.
var result = uCalc.DefaultInstance.EvalStr("PI");
Console.WriteLine($"Original context restored. PI = {result}");
```

**Output:**
```
Initial Count: 1
Count after module pushes new default: 2
Count after module instance is disposed: 1
Original context restored. PI = 3.14159
```

---

### Example ID: 272

**Description:** Internal Test: Verify stack count during creation, stacking, and clearing.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine($"Initial: {uCalc.DefaultCount}");

// The implicit 'uc' is the first default. Pushing it again adds to the stack.
uc.IsDefault = true;
Console.WriteLine($"After pushing 'uc' again: {uCalc.DefaultCount}");

var ucB = new uCalc();
ucB.IsDefault = true;
Console.WriteLine($"After pushing ucB: {uCalc.DefaultCount}");

var ucC = new uCalc();
ucC.IsDefault = true;
Console.WriteLine($"After pushing ucC: {uCalc.DefaultCount}");

// Clear all user-defined defaults, leaving only the mandatory root instance.
uCalc.DefaultClear();
Console.WriteLine($"After Clear: {uCalc.DefaultCount}");
```

**Output:**
```
Initial: 1
After pushing 'uc' again: 2
After pushing ucB: 3
After pushing ucC: 4
After Clear: 1
```

---

### Example ID: 273

**Description:** Inspecting the stack depth as new defaults are added and cleared

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Check initial state (Root instance only)
Console.WriteLine(uCalc.DefaultCount);

// Push the current 'uc' instance onto the stack
uc.IsDefault = true;
Console.WriteLine(uCalc.DefaultCount);

// Create a new instance and push it
var ucB = new uCalc();
ucB.IsDefault = true;
Console.WriteLine(uCalc.DefaultCount);

// Create another instance and push it
var ucC = new uCalc();
ucC.IsDefault = true;
Console.WriteLine(uCalc.DefaultCount);

// Clear all custom defaults, reverting to the root instance
uCalc.DefaultClear();
Console.WriteLine(uCalc.DefaultCount);
```

**Output:**
```
1
2
3
4
1
```

---

### Example ID: 274

**Description:** Quick Start: Getting and Setting the Default Type

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Check startup default (usually Double)
Console.WriteLine($"Start: {uc.DefaultDataType.Name}");

// 2. Change default to 32-bit Integer
uc.SetDefaultDataType(BuiltInType.Integer_32);
Console.WriteLine($"New: {uc.DefaultDataType.Name}");

// 3. Reset to Double using string shortcut
uc.SetDefaultDataType("Double");
Console.WriteLine($"Reset: {uc.DefaultDataType.Name}");

```

**Output:**
```
Start: double
New: int
Reset: double
```

---

### Example ID: 276

**Description:** Internal Test: Default Type Scope and Isolation

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create a separate instance to verify isolation
var uc2 = new uCalc();

// Set main instance to String
uc.SetDefaultDataType("String");

// Set second instance to Int32
uc2.SetDefaultDataType("Int32");

Console.WriteLine($"uc1 Default: {uc.DefaultDataType.Name}");
Console.WriteLine($"uc2 Default: {uc2.DefaultDataType.Name}");

uc2.DefineFunction("Add(a, b) = a + b");
Console.WriteLine($"Numeric Add: {uc2.EvalStr("Add(5, 5)")}");

// Check Eval behavior with String default
// "5" + "5" should be string concatenation "55"
uc.DefineFunction("Add(a, b) = a + b");
Console.WriteLine($"String Add: {uc.EvalStr("Add(5, 5)")}");
```

**Output:**
```
uc1 Default: string
uc2 Default: int
Numeric Add: 10
String Add: 55
```

---

### Example ID: 277

**Description:** Introspection and conversion using standard types

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Inspect basic properties of built-in types
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_8u).Name);
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_32).ByteSize);

// Testing edge case conversions mentioned in development notes
// Also string conversion behavior for signed vs unsigned and complex types
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_8u).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.Integer_16u).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.String).ToString("-1"));
Console.WriteLine(uc.DataTypeOf(BuiltInType.Boolean).ToString("-1"));
```

**Output:**
```
int8u
4
255
65535
-1
true
```

---

### Example ID: 278

**Description:** Checking variable types against BuiltInType

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a variable with a specific type
uc.DefineVariable("myVar As Int16");

// Retrieve the generic Int16 type object
var typeObj = uc.DataTypeOf(BuiltInType.Integer_16);

// Check if the variable's type matches Int16
if (uc.ItemOf("myVar").DataType.BuiltInTypeEnum == typeObj.BuiltInTypeEnum) {
   Console.WriteLine("Variable 'myVar' is an Int16.");
} else {
   Console.WriteLine("Type mismatch.");
}
```

**Output:**
```
Variable 'myVar' is an Int16.
```

---

### Example ID: 284

**Description:** Practical: Introspecting variables and functions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a variable and a function
uc.DefineVariable("myVar As Int16 = 55");
uc.DefineFunction("myFunc(x) = x * 10.5"); // Implicitly returns Double

// Inspect their types dynamically
var typeVar = uc.DataTypeOf("myVar");
var typeFunc = uc.DataTypeOf("myFunc");

Console.WriteLine($"Variable Type: {typeVar.Name}");
Console.WriteLine($"Function Return: {typeFunc.Name}");

// Check specific properties
if (typeVar.BuiltInTypeEnum == BuiltInType.Integer_16) {
   Console.WriteLine("Variable is strictly a 16-bit integer.");
}
```

**Output:**
```
Variable Type: int16
Function Return: double
Variable is strictly a 16-bit integer.
```

---

### Example ID: 285

**Description:** Internal Test: aliases and comparison logic.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// "Int" is a synonym for Int32
Console.WriteLine(uc.DataTypeOf("Int").Name);

// Boolean logic expression returns bool type
Console.WriteLine(uc.DataTypeOf("3 < 10").Name);

// String concatenation returns string
Console.WriteLine(uc.DataTypeOf(" 'A' + 'B' ").Name);

// Complex number syntax
Console.WriteLine(uc.DataTypeOf("5 + 7 * #i").Name);
```

**Output:**
```
int
bool
string
complex
```

---

### Example ID: 286

**Description:** Quickly defines the mathematical constant PI and uses it in a simple calculation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineConstant("PI = 3.14159");
Console.WriteLine(uc.Eval("2 * PI"));
```

**Output:**
```
6.28318
```

---

### Example ID: 287

**Description:** Defines several application-level configuration constants for use in expressions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineConstant("MAX_USERS = 100");
uc.DefineConstant("API_VERSION = 'v2.1'");
uc.DefineConstant("ENABLE_LOGGING = true");

Console.WriteLine("Configuration Settings:");
Console.WriteLine($"Max Users: {uc.Eval("MAX_USERS")}");
Console.WriteLine($"API Version: {uc.EvalStr("API_VERSION")}");
Console.WriteLine($"Logging Enabled: {uc.EvalStr("ENABLE_LOGGING")}");

// Use in a conditional expression
int currentUserCount = 99;
if (uc.EvalStr((currentUserCount).ToString() + " < MAX_USERS") == "true") {
   Console.WriteLine("System capacity is OK.");
}
```

**Output:**
```
Configuration Settings:
Max Users: 100
API Version: v2.1
Logging Enabled: true
System capacity is OK.
```

---

### Example ID: 288

**Description:** Internal Test: Validates that end-users cannot modify a locked constant.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineConstant("LOCKED_VAL = 1000");
Console.WriteLine($"Initial value: {uc.Eval("LOCKED_VAL")}");

// 1. End-user attempts to assign a value. This should fail.
uc.Eval("LOCKED_VAL = 2000");
Console.WriteLine($"Error after assignment attempt: {uc.Error.Message}");
Console.WriteLine($"Value remains unchanged: {uc.Eval("LOCKED_VAL")}");

```

**Output:**
```
Initial value: 1000
Error after assignment attempt: Value cannot be assigned here
Value remains unchanged: 1000
```

---

### Example ID: 289

**Description:** Sets and retrieves a description for the main uCalc object.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Assign a description to the main uCalc instance
uc.Description = "Primary evaluator for financial calculations";

// Retrieve and print the description
Console.WriteLine(uc.Description);
```

**Output:**
```
Primary evaluator for financial calculations
```

---

### Example ID: 292

**Description:** Sample example

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine("This is a sample example");
```

**Output:**
```
This is a sample example
```

---

### Example ID: 293

**Description:** Defining a simple variable and function.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a variable and a function using the core Define method
uc.Define("Variable: my_var = 100");
uc.Define("Function: square(x) = x * x");

Console.WriteLine(uc.Eval("my_var * square(5)"));
```

**Output:**
```
2500
```

---

### Example ID: 295

**Description:** Internal Test: Verifying 'Overwrite' for interdependent definitions in a spreadsheet simulation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define interdependent 'cells' using the Overwrite command.
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

Console.WriteLine($"Initial C1: {uc.Eval("C1()")}"); // Should be 10 + (10 * 2) = 30

// Now, overwrite the source cell A1. All dependent cells should automatically update.
uc.Define("Overwrite ~~ Function: A1() = 50");

Console.WriteLine($"Updated B1: {uc.Eval("B1()")}"); // Should now be 50 * 2 = 100
Console.WriteLine($"Updated C1: {uc.Eval("C1()")}"); // Should now be 50 + 100 = 150
```

**Output:**
```
Initial C1: 30
Updated B1: 100
Updated C1: 150
```

---

### Example ID: 296

**Description:** A minimal example defining a function inline to calculate the area of a rectangle.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 5");
uc.DefineFunction("Area(length, width) = length * width");
Console.WriteLine(uc.Eval("Area(4, x) + 7"));
```

**Output:**
```
27
```

---

### Example ID: 297

**Description:** Demonstrates defining a function that is implemented by a native callback in the host application.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyAreaCallback(uCalc.Callback cb) {
   var length = cb.Arg(1);
   var width = cb.Arg(2);
   cb.Return(length * width);
}


// The signature is defined, but the logic is provided by 'MyAreaCallback'.
uc.DefineFunction("Area(x, y)", MyAreaCallback);
Console.WriteLine(uc.Eval("Area(3, 4)"));
```

**Output:**
```
12
```

---

### Example ID: 298

**Description:** Shows how to create overloaded functions that uCalc distinguishes based on parameter count and type.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Overload for two numbers
uc.DefineFunction("Combine(x, y) = x + y");

// Overload for two strings
uc.DefineFunction("Combine(x As String, y As String) As String = x + y");

// Overload for three numbers
uc.DefineFunction("Combine(x, y, z) = x + y + z");

Console.WriteLine($"Two numbers: {uc.EvalStr("Combine(5, 10)")}");
Console.WriteLine($"Two strings: {uc.EvalStr("Combine('Hello, ', 'World!')")}");
Console.WriteLine($"Three numbers: {uc.EvalStr("Combine(5, 10, 20)")}");
```

**Output:**
```
Two numbers: 15
Two strings: Hello, World!
Three numbers: 35
```

---

### Example ID: 299

**Description:** Defines a recursive Factorial function using the IIf function for conditional logic.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineFunction("Factorial(n) = IIf(n > 1, n * Factorial(n - 1), 1)");
Console.WriteLine(uc.Eval("Factorial(5)"));
```

**Output:**
```
120
```

---

### Example ID: 305

**Description:** A minimal example defining a variable and using it in an expression.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 10");
Console.WriteLine(uc.Eval("x * 5"));
```

**Output:**
```
50
```

---

### Example ID: 306

**Description:** Defines variables with explicit types, inferred types, and default types.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Explicit type definition
uc.DefineVariable("explicitInt As Int = 123");

// Type inferred from the initial string value
uc.DefineVariable("inferredStr = 'hello'");

// Type defaults to Double as no type or value is given
var defaultVar = uc.DefineVariable("defaultVar");

Console.WriteLine($"explicitInt type: {uc.ItemOf("explicitInt").DataType.Name}");
Console.WriteLine($"inferredStr type: {uc.ItemOf("inferredStr").DataType.Name}");
Console.WriteLine($"defaultVar type: {defaultVar.DataType.Name}");
```

**Output:**
```
explicitInt type: int
inferredStr type: string
defaultVar type: double
```

---

### Example ID: 307

**Description:** Demonstrates defining a fixed-size array and an array with an initializer list.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Fixed-size array of 3 doubles
uc.DefineVariable("fixedArray[3]");
uc.Eval("fixedArray[0]=1.1; fixedArray[1]=2.2; fixedArray[2]=3.3;");

// Array initialized with values; size and type are inferred
uc.DefineVariable("initArray[] = {'a', 'b', 'c'}");

Console.WriteLine($"Fixed Array Element 1: {uc.EvalStr("fixedArray[1]")}");
Console.WriteLine($"Initialized Array Element 2: {uc.EvalStr("initArray[2]")}");
Console.WriteLine($"Initialized Array Size: {uc.ItemOf("initArray").Count}");
```

**Output:**
```
Fixed Array Element 1: 2.2
Initialized Array Element 2: c
Initialized Array Size: 3
```

---

### Example ID: 310

**Description:** A quick example demonstrating how to set and get a description on a variable.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a variable and chain the Description() call to set metadata
var myVar = uc.DefineVariable("x = 10").SetDescription("Stores the current iteration count.");

// Retrieve and display the description
Console.WriteLine($"Description for 'x': {myVar.Description}");
```

**Output:**
```
Description for 'x': Stores the current iteration count.
```

---

### Example ID: 318

**Description:** An internal test to confirm that ErrorExpression returns an empty string for an error triggered manually by a user function during evaluation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyFunc(uCalc.Callback cb) {
   // This error occurs during evaluation, not parsing.
   cb.Error.Raise("Manual evaluation failure!");
}

static void MyHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine($"Handler triggered for error: {uc.Error.Message}");
   Console.WriteLine($"ErrorExpression() returned: '{uc.Error.Expression}'");
   Console.WriteLine($"Is expression empty? {uc.Error.Expression == ""}");
}


uc.DefineFunction("MyFunc()", MyFunc);
uc.Error.AddHandler(MyHandler);

// The expression 'MyFunc()' itself is valid syntactically.
Console.WriteLine(uc.EvalStr("MyFunc()"));
```

**Output:**
```
Handler triggered for error: Manual evaluation failure!
ErrorExpression() returned: ''
Is expression empty? True
Manual evaluation failure!
```

---

### Example ID: 321

**Description:** Capturing both parsing-stage and evaluation-stage errors to see how ErrorLocation behaves differently.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyErrorHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("--- Error Captured ---");
   Console.WriteLine($"Message: {uc.Error.Message}");
   Console.WriteLine($"Symbol: '{uc.Error.Symbol}'");
   Console.WriteLine($"Location: {uc.Error.Location}");
   Console.WriteLine($"Expression: '{uc.Error.Expression}'");
}


uc.Error.AddHandler(MyErrorHandler);

Console.WriteLine("Demonstrating a PARSING error:");
uc.EvalStr("123//456");

Console.WriteLine("");
Console.WriteLine("Demonstrating an EVALUATION error:");
uc.Error.TrapOnDivideByZero = true;
uc.EvalStr("5/0");
```

**Output:**
```
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'

Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: ''
```

---

### Example ID: 322

**Description:** Demonstrates getting the last error message after a failed operation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Attempt to evaluate an expression with unbalanced parenthesis causing a syntax error.
uc.EvalStr("5 * (10 +");

// Check the error message from the last operation.
Console.WriteLine($"Last error message: {uc.Error.Message}");
```

**Output:**
```
Last error message: Bracket delimiter error
```

---

### Example ID: 323

**Description:** Retrieves the generic message for a specific error code and compares it to the last error message.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Retrieve the built-in message for a specific error code, without triggering an error.
Console.WriteLine($"Generic 'Undefined Identifier' message: {uc.Error.GetMessage(ErrorCode.Undefined_Identifier)}");

// Now, trigger a specific error by using an undefined variable.
uc.EvalStr("MyUndefinedVar + 5");

// Check the message and number for the last error that occurred.
Console.WriteLine($"Last error message: {uc.Error.Message}");
Console.WriteLine($"Last error number: {(int)uc.Error.Code}");
```

**Output:**
```
Generic 'Undefined Identifier' message: Undefined identifier
Last error message: Undefined identifier
Last error number: 258
```

---

### Example ID: 324

**Description:** Internal Test: Verifies that the error state is correctly cleared after a subsequent successful operation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Internal Test: Verify error state is cleared
Console.WriteLine("--- Testing Error State Lifecycle ---");

// 1. Trigger a division-by-zero error.
uc.Error.TrapOnDivideByZero = true;
uc.EvalStr("1 / 0");
Console.WriteLine($"Message after 1/0: '{uc.Error.Message}'");
Console.WriteLine($"Error number is not None: {uc.Error.Code != ErrorCode.None}");

// 2. Perform a successful operation, which should clear the previous error state.
uc.EvalStr("1 + 1");

// 3. Verify the error message and number have been reset.
Console.WriteLine($"Message after successful op: '{uc.Error.Message}'");
Console.WriteLine($"Error number is now None: {uc.Error.Code == ErrorCode.None}");
```

**Output:**
```
--- Testing Error State Lifecycle ---
Message after 1/0: 'Division by 0'
Error number is not None: True
Message after successful op: 'No error'
Error number is now None: True
```

---

### Example ID: 325

**Description:** Checking the error code for a simple syntax error using a callback.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   // Retrieve the error code as an integer for display
   int code = (int)uc.Error.Code;
   Console.WriteLine($"Caught Error Code: {code}");

   // Compare the error code against the ErrorCode enum for logic
   if (uc.Error.Code == ErrorCode.Syntax_Error) {
      Console.WriteLine("This was a syntax error.");
   }
}


// Register the error handler
uc.Error.AddHandler(MyHandler);

// Intentionally cause a syntax error, which will trigger the handler
Console.WriteLine(uc.EvalStr("5 *"));
```

**Output:**
```
Caught Error Code: 257
This was a syntax error.
Syntax error
```

---

### Example ID: 326

**Description:** Creating an error handler that automatically defines variables on the fly by checking for an 'Undefined Identifier' error.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void AutoDefineHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   // Check if the error is specifically an undefined identifier
   if (uc.Error.Code == ErrorCode.Undefined_Identifier) {
      // If so, define the missing variable and instruct uCalc to resume
      Console.WriteLine($"Auto-defining variable: '{uc.Error.Symbol}'");
      uc.DefineVariable(uc.Error.Symbol);
      uc.Error.Response = ErrorHandlerResponse.Resume;
   }
}


uc.Error.AddHandler(AutoDefineHandler);

// 'x' doesn't exist, but the handler will intercept the error and create it.
var Result = uc.EvalStr("x = 10; x * 5");
Console.WriteLine($"Result: {Result}");
```

**Output:**
```
Auto-defining variable: 'x'
Result: 50
```

---

### Example ID: 327

**Description:** Internal Test: Verifies that the error code is correctly cleared after a successful operation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Trigger an error and check the code
uc.EvalStr("1+");
Console.WriteLine($"1. Error code after failure: {(int)uc.Error.Code}");

// A successful evaluation should clear the error code
uc.EvalStr("1+1");
Console.WriteLine($"2. Error code after success: {(int)uc.Error.Code}");

// Trigger a different type of error
uc.Error.TrapOnDivideByZero = true;
uc.EvalStr("1/0");
Console.WriteLine($"3. Error code after new failure: {(int)uc.Error.Code}");

// A successful definition should also clear the error code
uc.DefineVariable("x=5");
Console.WriteLine($"4. Error code after successful definition: {(int)uc.Error.Code}");
```

**Output:**
```
1. Error code after failure: 257
2. Error code after success: 0
3. Error code after new failure: 8
4. Error code after successful definition: 0
```

---

### Example ID: 329

**Description:** Practical: Creates a robust error handler that automatically defines variables on-the-fly when an 'Undefined Identifier' error occurs.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// This error handler allows you to use variables that were not
// explicitly defined previously by defining unrecognized identifiers
// as variables instead of returning an error.
static void AutoVariableDef(Handle_uCalc h) {
   var uc = new uCalc(h);
   if (uc.Error.Code == ErrorCode.Undefined_Identifier) {
      uc.DefineVariable(uc.Error.Symbol);
      uc.Error.Response = ErrorHandlerResponse.Resume;
   }
}


uc.Error.AddHandler(AutoVariableDef);
// The handler will automatically define 'AutoTest' on first use.
Console.WriteLine(uc.Eval("AutoTest = 123"));
Console.WriteLine(uc.Eval("AutoTest * 1000"));
```

**Output:**
```
123
123000
```

---

### Example ID: 334

**Description:** Quickly evaluates several basic mathematical and function-based expressions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Eval provides a direct way to compute results from strings.
Console.WriteLine(uc.Eval("1+1"));
Console.WriteLine(uc.Eval("5*(3+9)^2"));
Console.WriteLine(uc.Eval("Sqrt(16) + Sin(0)"));
Console.WriteLine(uc.Eval("Length('This is a test')"));
```

**Output:**
```
2
720
4
14
```

---

### Example ID: 335

**Description:** Calculates simple interest by defining variables and then evaluating an expression string that uses them.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define variables representing configuration or user inputs.
uc.DefineVariable("principal = 20000");
uc.DefineVariable("annual_rate = 0.0575");
uc.DefineVariable("years = 4");

// Evaluate an expression combining these variables.
var interest = uc.Eval("principal * annual_rate * years");
Console.WriteLine($"Total Interest: {interest}");
```

**Output:**
```
Total Interest: 4600
```

---

### Example ID: 337

**Description:** Demonstrates basic, one-line evaluations for numeric, string, and boolean expressions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Basic arithmetic
Console.WriteLine(uc.EvalStr("15 * (4 + 3)"));
// String manipulation
Console.WriteLine(uc.EvalStr("UCase('hello') + ', world!'"));
// Boolean logic
Console.WriteLine(uc.EvalStr("10 > 5 AndAlso 'a' < 'b'"));
```

**Output:**
```
105
HELLO, world!
true
```

---

### Example ID: 338

**Description:** Calculates a total price using predefined variables and demonstrates the effect of output formatting.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define some context for the expression
uc.DefineVariable("price = 49.99");
uc.DefineVariable("quantity = 3");
uc.DefineConstant("TAX_RATE = 0.0825");

// Define a format for currency output
uc.Format("DataType: Double, Def: result = '$' + result");

// Expression to calculate total price, using variables
var expression = "price * quantity * (1 + TAX_RATE)";

// Evaluate with formatting enabled
Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, true)}");

// Evaluate with formatting disabled
Console.WriteLine($"Raw Total: {uc.EvalStr(expression, false)}");
```

**Output:**
```
Formatted Total: $162.342525
Raw Total: 162.342525
```

---

### Example ID: 340

**Description:** Quick Start: Inspects the regex pattern for a single, common token type (alphanumeric identifiers).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var tokens = uc.ExpressionTokens;
var alphanumericToken = tokens[TokenType.AlphaNumeric];

Console.WriteLine("The regex for alphanumeric tokens is:");
Console.WriteLine(alphanumericToken.Regex);
```

**Output:**
```
The regex for alphanumeric tokens is:
[a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 342

**Description:** Extends the parser to support C-style `0x` hex and `0b` binary notations using a token transformer.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a token for C-like 0x hex notation
uc.ExpressionTokens.Add("0x[0-9A-Fa-f]+", TokenType.TokenTransform);
uc.TokenTransformer.FromTo("{'0x'}{Num:'[0-9A-Fa-f]+'}", "BaseConvert('{Num}', 16)");
Console.WriteLine($"0xFF is evaluated as: {uc.EvalStr("0xFF")}");

// Define a token for C++-style 0b binary notation
uc.ExpressionTokens.Add("0b[01]+", TokenType.TokenTransform);

// Using {@Eval} is more efficient as the conversion happens once during the token transform pass.
uc.TokenTransformer.FromTo("{'0b'}{Num:'[01]+'}", "{@Eval: BaseConvert(Num, 2)}");
Console.WriteLine($"0b1011 is evaluated as: {uc.EvalStr("0b1011")}");

// Note: uCalc has built-in support for hex/binary using # notation (e.g., #hFF, #b1011)
Console.WriteLine($"uCalc's built-in #hFF is: {uc.EvalStr("#hFF")}");
```

**Output:**
```
0xFF is evaluated as: 255
0b1011 is evaluated as: 11
uCalc's built-in #hFF is: 255
```

---

### Example ID: 346

**Description:** Demonstrates using `RewindOnChange(true)` to perform recursive-style transformations, such as creating a variadic `AddUp` function.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.ExpressionTransformer;

// Base case: a single argument
t.FromTo("AddUp({x})", "{x}");

// Recursive case: multiple arguments
// RewindOnChange(true) causes the transformer to re-scan the string after a replacement.
// This allows AddUp(1,2,3) -> (1 + AddUp(2,3)) -> (1 + (2 + AddUp(3))) -> (1 + (2 + 3))
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").RewindOnChange = true;

Console.WriteLine("Input: AddUp(1, 2, 3, 4)");
Console.WriteLine($"Result: {uc.Eval("AddUp(1, 2, 3, 4)")}");
```

**Output:**
```
Input: AddUp(1, 2, 3, 4)
Result: 10
```

---

### Example ID: 347

**Description:** Internal Test: Verifies that multi-pass transformations work correctly when `RewindOnChange` is enabled for the entire rule set.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.ExpressionTransformer;

// Enable RewindOnChange for all subsequently added rules
t.DefaultRuleSet.RewindOnChange = true;

// Define a chain of simple transformations
t.FromTo("A", "B");
t.FromTo("B", "C");
t.FromTo("C", "D");

// The transformer should apply all rules in sequence: A -> B -> C -> D
var result = t.Transform("A").Text;
Console.WriteLine($"Transform('A') -> {result}");
Console.WriteLine($"Is correct: {result == "D"}");
```

**Output:**
```
Transform('A') -> D
Is correct: True
```

---

### Example ID: 348

**Description:** The getter and setter functionality for a single flag.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Get the initial state (default is 0, no errors raised)
Console.WriteLine($"Initial flags: {uc.Error.FloatingPointErrorsToTrap}");

// Enable raising an error for division by zero
uc.Error.FloatingPointErrorsToTrap = (int)ErrorCode.FloatDivisionByZero;

// Verify the new state
Console.WriteLine($"Updated flags: {uc.Error.FloatingPointErrorsToTrap}");

// Test the behavior
Console.WriteLine($"1/0 = {uc.EvalStr("1/0")}");

// Disable the flag by setting it back to 0
uc.Error.FloatingPointErrorsToTrap = 0;
Console.WriteLine($"Flags after reset: {uc.Error.FloatingPointErrorsToTrap}");
Console.WriteLine($"1/0 after reset = {uc.EvalStr("1/0")}");
```

**Output:**
```
Initial flags: 0
Updated flags: 8
1/0 = Division by 0
Flags after reset: 0
1/0 after reset = inf
```

---

### Example ID: 349

**Description:** Demonstrates enabling multiple floating-point error types and observing the results.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine("--- Default Behavior (No Errors Raised) ---");
Console.WriteLine($"1/0: {uc.EvalStr("1/0")}");
Console.WriteLine($"0/0: {uc.EvalStr("0/0")}");
Console.WriteLine($"Overflow (5*10^308): {uc.EvalStr("5*10^308")}");
Console.WriteLine($"Underflow (10^-308/10000): {uc.EvalStr("10^-308/10000")}");

Console.WriteLine("");
Console.WriteLine("--- Enable Invalid Operation & Underflow ---");
// You can pass multiple enum members to enable them simultaneously
uc.Error.SetFloatingPointErrorsToTrap(ErrorCode.FloatInvalid, ErrorCode.FloatUnderflow);
Console.WriteLine($"Current flags: {uc.Error.FloatingPointErrorsToTrap}"); // Should be 16 (Invalid) + 2 (Underflow) = 18

Console.WriteLine($"1/0: {uc.EvalStr("1/0")}"); // Not enabled, returns inf
Console.WriteLine($"0/0: {uc.EvalStr("0/0")}"); // Enabled, raises error
Console.WriteLine($"Overflow (5*10^308): {uc.EvalStr("5*10^308")}"); // Not enabled, returns inf
Console.WriteLine($"Underflow (10^-308/10000): {uc.EvalStr("10^-308/10000")}"); // Enabled, raises error
```

**Output:**
```
--- Default Behavior (No Errors Raised) ---
1/0: inf
0/0: nan
Overflow (5*10^308): inf
Underflow (10^-308/10000): 0

--- Enable Invalid Operation & Underflow ---
Current flags: 18
1/0: inf
0/0: Invalid floating point operation
Overflow (5*10^308): inf
Underflow (10^-308/10000): Floating point underflow
```

---

### Example ID: 350

**Description:** Internal Test: Verifies that setting and clearing all possible floating-point flags works correctly.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Combine all flags using integer values (or bitwise OR on enums)
var allFlags = 2 | 4 | 8 | 16; // Underflow, Overflow, DivByZero, Invalid
uc.Error.FloatingPointErrorsToTrap = allFlags;
Console.WriteLine($"All flags set: {uc.Error.FloatingPointErrorsToTrap}");

// Test all conditions
Console.WriteLine($"Underflow: {uc.EvalStr("1e-320")}");
Console.WriteLine($"Overflow: {uc.EvalStr("1e320")}");
Console.WriteLine($"DivByZero: {uc.EvalStr("1/0")}");
Console.WriteLine($"Invalid: {uc.EvalStr("0/0")}");

// Clear all flags
uc.Error.FloatingPointErrorsToTrap = 0;
Console.WriteLine("");
Console.WriteLine($"All flags cleared: {uc.Error.FloatingPointErrorsToTrap}");

// Verify they are cleared
Console.WriteLine($"Underflow: {uc.EvalStr("1e-320")}");
Console.WriteLine($"Overflow: {uc.EvalStr("1e320")}");
Console.WriteLine($"DivByZero: {uc.EvalStr("1/0")}");
Console.WriteLine($"Invalid: {uc.EvalStr("0/0")}");
```

**Output:**
```
All flags set: 30
Underflow: Floating point underflow
Overflow: Floating point overflow
DivByZero: Division by 0
Invalid: Invalid floating point operation

All flags cleared: 0
Underflow: 0
Overflow: inf
DivByZero: inf
Invalid: nan
```

---

### Example ID: 351

**Description:** A basic example that prepends text to all numeric output.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a format that only applies to Double data types.
var doubleType = uc.DataTypeOf("Double");
var fmt = uc.Format("Result = 'Value: ' + Result", doubleType);

Console.WriteLine(uc.EvalStr("10 * 2.5"));
Console.WriteLine(uc.EvalStr("'Hello'")); // String output is unaffected.

// Clean up the format rule
fmt.Release();
Console.WriteLine(uc.EvalStr("10 * 2.5")); // No longer formatted
```

**Output:**
```
Value: 25
Hello
25
```

---

### Example ID: 352

**Description:** Practical: Using the C++ style `Format()` function for currency and text alignment.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Note: The C++ based format in uCalc, used here, works only in Windows as of this writing.
// This is because uCalc is currently compiled with C++ 20 to get the right balance
// between maximum compatibility across platforms and access to modern C++ functionality.
// *std::format* is technically part of C++ 20, but it's not universally implemented in
// different compilers using the C++ 20 compilation directive.

// Rule 1: Format Doubles as currency with two decimal places.
var doubleType = uc.DataTypeOf(BuiltInType.Float_Double);
uc.Format("Result = '$' + Format('{:.2f}', double(Result))", doubleType);

// Rule 2: Center-align strings in a 15-character field padded with '-'.
var strType = uc.DataTypeOf(BuiltInType.String);
uc.Format("Result = Format('{:-^15}', Result)", strType);

Console.WriteLine($"Price: {uc.EvalStr("199.999")}");
Console.WriteLine($"Discount: {uc.EvalStr("7.5")}");
Console.WriteLine($"Label: {uc.EvalStr("'Summary'")}");
```

**Output:**
```
Price: $200.00
Discount: $7.50
Label: ----Summary----
```

---

### Example ID: 353

**Description:** Internal Test: Verifies the layering and precedence of multiple format rules using `InsertAt`.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var strType = uc.DataTypeOf("String");

// Rule A (will be applied second)
uc.Format("val = '[' + val + ']'");

// Rule B (will be applied first)
uc.Format("val = 'inner:(' + val + ')'");

Console.WriteLine($"Default layering: {uc.EvalStr("'text'")}");

// Rule C: Insert this rule at position 0, making it apply LAST.
uc.Format("InsertAt: 0, Def: val = 'outer: {' + val + '}'");

Console.WriteLine($"With InsertAt: {uc.EvalStr("'text'")}");
```

**Output:**
```
Default layering: [inner:(text)]
With InsertAt: outer: {[inner:(text)]}
```

---

### Example ID: 366

**Description:** A simple check to see which uCalc instance is the default.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// The implicit 'uc' object is not the default upon creation.
Console.WriteLine($"Is 'uc' the default instance? {uc.IsDefault}");

// Create a new uCalc instance. It also won't be the default.
var myCalc = new uCalc();
Console.WriteLine($"Is 'myCalc' the default instance? {myCalc.IsDefault}");

// Let's get the actual default instance and check it.
uCalc defaultInstance = uCalc.DefaultInstance;
Console.WriteLine($"Is the instance from uCalc.DefaultInstance the default? {defaultInstance.IsDefault}");
```

**Output:**
```
Is 'uc' the default instance? False
Is 'myCalc' the default instance? False
Is the instance from uCalc.DefaultInstance the default? True
```

---

### Example ID: 367

**Description:** Manage different parser configurations by switching the default instance.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Setup a "Scientific" configuration
var scientificCalc = new uCalc();
scientificCalc.DefineFunction("sqrt(x) = x^0.5");
scientificCalc.DefineVariable("pi = 3.14159");

// Setup a "Financial" configuration
var financialCalc = new uCalc();
financialCalc.DefineFunction("tax(amount, rate) = amount * (rate/100)");

// Set the scientific calculator as the default
scientificCalc.IsDefault = true;
Console.WriteLine($"Current default is scientific? {scientificCalc.IsDefault}");

// Components that rely on the default instance now use the scientific setup.
uCalc.Expression expr1 = "2 * pi";
Console.WriteLine($"2 * pi = {expr1.Evaluate()}");

// Now, switch the default to the financial calculator
financialCalc.IsDefault = true;
Console.WriteLine($"Current default is scientific? {scientificCalc.IsDefault}"); // Should be false now
Console.WriteLine($"Current default is financial? {financialCalc.IsDefault}");

// New components will use the financial setup.
uCalc.Expression expr2 = "tax(50000, 20)";
Console.WriteLine($"Tax on 50000 at 20% = {expr2.Evaluate()}");
```

**Output:**
```
Current default is scientific? True
2 * pi = 6.28318
Current default is scientific? False
Current default is financial? True
Tax on 50000 at 20% = 10000
```

---

### Example ID: 368

**Description:** Internal Test: Verify the stack-like behavior of the default instance list.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a variable in the original default to distinguish it.
// Note: This variable won't exist in the implicit 'uc' instance.
uCalc.DefaultInstance.DefineVariable("id='Original'");
Console.WriteLine($"Initial default: {uCalc.DefaultInstance.EvalStr("id")}");

var ucA = new uCalc();
ucA.DefineVariable("id='A'");
ucA.IsDefault = true; // Default stack: [Original, A]
Console.WriteLine($"Current default: {uCalc.DefaultInstance.EvalStr("id")}");

var ucB = new uCalc();
ucB.DefineVariable("id='B'");
ucB.IsDefault = true; // Default stack: [Original, A, B]
Console.WriteLine($"Current default: {uCalc.DefaultInstance.EvalStr("id")}");

var ucC = new uCalc();
ucC.DefineVariable("id='C'");
ucC.IsDefault = true; // Default stack: [Original, A, B, C]
Console.WriteLine($"Current default: {uCalc.DefaultInstance.EvalStr("id")}");

Console.WriteLine("--- Unsetting instances ---");
// Unset B. The default should remain C.
ucB.IsDefault = false;
Console.WriteLine($"After unsetting B, current default: {uCalc.DefaultInstance.EvalStr("id")}");

// Unset C. The default should revert to A.
ucC.IsDefault = false;
Console.WriteLine($"After unsetting C, current default: {uCalc.DefaultInstance.EvalStr("id")}");

// Unset A. Reverts to the original default.
ucA.IsDefault = false;
Console.WriteLine($"After unsetting A, current default: {uCalc.DefaultInstance.EvalStr("id")}");
```

**Output:**
```
Initial default: Original
Current default: A
Current default: B
Current default: C
--- Unsetting instances ---
After unsetting B, current default: C
After unsetting C, current default: A
After unsetting A, current default: Original
```

---

### Example ID: 374

**Description:** A simple lookup to retrieve a defined variable by its name and display its value.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("MyVar = 123");

// Retrieve the item by name
var item = uc.ItemOf("MyVar");

// Check if the item was found and print its value
if (item.NotEmpty()) {
   Console.WriteLine($"Value of MyVar is: {item.Value()}");
}
```

**Output:**
```
Value of MyVar is: 123
```

---

### Example ID: 375

**Description:** Use the 'properties' parameter to disambiguate between the infix (binary) and prefix (unary) versions of the minus '-' operator.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Get the infix (subtraction) operator and check its operand count
var infixOp = uc.ItemOf("-", ItemIs.Infix);
Console.Write("Infix '-' operator has "); Console.Write(infixOp.Count);
Console.WriteLine(" operand(s).");

// Get the prefix (negation) operator
var prefixOp = uc.ItemOf("-", ItemIs.Prefix);
Console.Write("Prefix '-' operator has "); Console.Write(prefixOp.Count);
Console.WriteLine(" operand(s).");
```

**Output:**
```
Infix '-' operator has 2 operand(s).
Prefix '-' operator has 1 operand(s).
```

---

### Example ID: 384

**Description:** Lists the names of all user-defined and built-in functions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
Console.WriteLine("Defined Functions:");
foreach(var item in uc.GetItems(ItemIs.Function)) {
   Console.WriteLine($" - {item.Name}");
}
```

**Output:**
```
Defined Functions:
 - abs
 - acos
 - acosh
 - addptr
 - addressof
 - anytype
 - append
 - append_copy
 - arg
 - argcount
 - asc
 - asin
 - asinh
 - atan
 - atan2
 - atanh
 - back
 - baseconvert
 - bin
 - bool
 - bool
 - int8u
 - c_str
 - cbrt
 - ceil
 - chr
 - clear
 - compare
 - complex
 - conj
 - contains
 - copysign
 - cos
 - cosh
 - define
 - doloop
 - double
 - endswith
 - erase
 - erase_copy
 - erf
 - erfc
 - error
 - eval
 - evalstr
 - evaluate
 - evaluateint
 - evaluatestr
 - exp
 - exp2
 - expm1
 - exprptr
 - fabs
 - fdim
 - file
 - filesize
 - fill
 - find_first_not_of
 - find_first_of
 - find_last_not_of
 - find_last_of
 - single
 - floor
 - fmax
 - fmin
 - fmod
 - forloop
 - format
 - fpclassify
 - frac
 - frexp
 - fromto
 - gcd
 - goto
 - hex
 - hypot
 - iif
 - ilogb
 - imag
 - indexof
 - inf
 - insert
 - insert_copy
 - int
 - int16
 - int16u
 - int
 - int32u
 - int64
 - int64u
 - int8
 - int8u
 - int
 - isfinite
 - isinf
 - isnan
 - isnormal
 - lastindexof
 - lcase
 - lcm
 - ldexp
 - length
 - lgamma
 - llrint
 - llround
 - log
 - log10
 - log1p
 - log2
 - logb
 - lrint
 - lround
 - ltrim
 - max
 - min
 - modf
 - nan
 - nearbyint
 - nextafter
 - nexttoward
 - norm
 - oct
 - omnitype
 - padleft
 - padright
 - parse
 - pointer
 - polar
 - pop
 - pow
 - precedence
 - proj
 - push
 - rand
 - randfromsameseed
 - randomnumber
 - randomseed
 - real
 - remainder
 - remquo
 - repeat
 - replace
 - replace_copy
 - reset
 - rint
 - round
 - rtrim
 - sametypeas
 - scalbln
 - scalbn
 - setvar
 - sgn
 - signbit
 - sin
 - single
 - sinh
 - size_t
 - sizeof
 - sort
 - sqr
 - sqrt
 - startswith
 - str
 - string
 - substr
 - subtractptr
 - swap
 - tan
 - tanh
 - tgamma
 - trim
 - trunc
 - ucalcinstance
 - ucase
 - valueat
 - valueattype
 - void
```

---

### Example ID: 392

**Description:** A simple replacement demonstrating how to swap specific word patterns.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("Hello {name}", "Greetings, {name}!");
Console.WriteLine(t.Transform("Hello World"));
```

**Output:**
```
Greetings, World!
```

---

### Example ID: 396

**Description:** A simple demonstration of parsing an expression and then evaluating it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine("Parsing the expression '100 / 4'...");
using (var parsedExpr = new uCalc.Expression("100 / 4")) {
   //var parsedExpr = uc.Parse("100 / 4");

   Console.WriteLine("Evaluating the result...");
   Console.WriteLine($"Result: {parsedExpr.Evaluate()}");
}
```

**Output:**
```
Parsing the expression '100 / 4'...
Evaluating the result...
Result: 25
```

---

### Example ID: 403

**Description:** Toggling the error-raising behavior for division by zero.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Default behavior: returns infinity
Console.WriteLine($"Default: {uc.EvalStr("1/0")}");

// Enable error raising
uc.Error.TrapOnDivideByZero = true;
Console.WriteLine($"Error Enabled: {uc.EvalStr("1/0")}");

// Disable error raising
uc.Error.TrapOnDivideByZero = false;
Console.WriteLine($"Error Disabled: {uc.EvalStr("1/0")}");
```

**Output:**
```
Default: inf
Error Enabled: Division by 0
Error Disabled: inf
```

---

### Example ID: 405

**Description:** Internal Test: Verifies that only the division by zero flag is affected, while other floating-point exceptions like overflow remain unchanged by default.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Enable only the division by zero error
uc.Error.TrapOnDivideByZero = true;

// This should now raise a uCalc error
Console.WriteLine($"Test 1 (Div by Zero): {uc.EvalStr("1/0")}");

// This should still return 'inf' by default, as we didn't enable overflow errors
Console.WriteLine($"Test 2 (Overflow): {uc.EvalStr("1e308 * 2")}");

// For comparison, enable overflow errors as well
uc.Error.TrapOnOverflow = true;
Console.WriteLine($"Test 3 (Overflow with error): {uc.EvalStr("1e308 * 2")}");
```

**Output:**
```
Test 1 (Div by Zero): Division by 0
Test 2 (Overflow): inf
Test 3 (Overflow with error): Floating point overflow
```

---

### Example ID: 406

**Description:** How to enable error raising for Invalid floating point operations.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// By default, invalid floating point operations return 'nan'
Console.WriteLine(uc.EvalStr("sqrt(-1)"));

// Enable error raising for this specific case
uc.Error.TrapOnInvalid = true;

// Now, the same operation returns a descriptive error message
Console.WriteLine(uc.EvalStr("sqrt(-1)"));
```

**Output:**
```
nan
Invalid floating point operation
```

---

### Example ID: 407

**Description:** A practical example using an error handler to provide a custom, user-friendly message when an Invalid floating point operation occurs.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyErrorHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   // Check if the specific 'FloatInvalid' error was raised
   if (uc.Error.Code == ErrorCode.FloatInvalid) {
      Console.WriteLine("Error: The calculation resulted in an invalid number (e.g., square root of a negative).");
      // Stop further processing
      uc.Error.Response = ErrorHandlerResponse.Abort;
   }
}


// Register the custom error handler
uc.Error.AddHandler(MyErrorHandler);

// Tell uCalc to raise an error instead of returning 'nan'
uc.Error.TrapOnInvalid = true;

// This will now trigger our custom error handler's message
uc.EvalStr("sqrt(-4)");
```

**Output:**
```
Error: The calculation resulted in an invalid number (e.g., square root of a negative).
```

---

### Example ID: 408

**Description:** Internal test verifying the behavior of all `RaiseErrorOn...` flag methods.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// --- Division by Zero ---
Console.WriteLine(uc.EvalStr("1/0"));
uc.Error.TrapOnDivideByZero = true;
Console.WriteLine(uc.EvalStr("1/0"));

// --- Invalid floating point operation ---
Console.WriteLine(uc.EvalStr("Sqrt(-1)"));
uc.Error.TrapOnInvalid = true;
Console.WriteLine(uc.EvalStr("Sqrt(-1)"));

// --- Overflow ---
Console.WriteLine(uc.EvalStr("5*10^308"));
uc.Error.TrapOnOverflow = true;
Console.WriteLine(uc.EvalStr("5*10^308"));

// --- Underflow ---
Console.WriteLine(uc.EvalStr("10^-308/10000"));
uc.Error.TrapOnUnderflow = true;
Console.WriteLine(uc.EvalStr("10^-308/10000"));
```

**Output:**
```
inf
Division by 0
nan
Invalid floating point operation
inf
Floating point overflow
0
Floating point underflow
```

---

### Example ID: 409

**Description:** How to toggle overflow error reporting on and off.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Default behavior: returns 'inf'
Console.WriteLine(uc.EvalStr("1e308 * 10"));

// 2. Enable error raising for overflow
uc.Error.TrapOnOverflow = true;
Console.WriteLine(uc.EvalStr("1e308 * 10"));

// 3. Disable it again to revert to default
uc.Error.TrapOnOverflow = false;
Console.WriteLine(uc.EvalStr("1e308 * 10"));
```

**Output:**
```
inf
Floating point overflow
inf
```

---

### Example ID: 410

**Description:** A practical example demonstrating all four related floating-point error configuration methods.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine($"Divide by Zero (Default): {uc.EvalStr("1/0")}");
uc.Error.TrapOnDivideByZero = true;
Console.WriteLine($"Divide by Zero (Error Enabled): {uc.EvalStr("1/0")}");

Console.WriteLine("");
Console.WriteLine($"Invalid floating point operation (Default): {uc.EvalStr("Sqrt(-1)")}");
uc.Error.TrapOnInvalid = true;
Console.WriteLine($"Invalid floating point operation (Error Enabled): {uc.EvalStr("Sqrt(-1)")}");

Console.WriteLine("");
Console.WriteLine($"Overflow (Default): {uc.EvalStr("5*10^308")}");
uc.Error.TrapOnOverflow = true;
Console.WriteLine($"Overflow (Error Enabled): {uc.EvalStr("5*10^308")}");

Console.WriteLine("");
Console.WriteLine($"Underflow (Default): {uc.EvalStr("10^-308/10000")}");
uc.Error.TrapOnUnderflow = true;
Console.WriteLine($"Underflow (Error Enabled): {uc.EvalStr("10^-308/10000")}");
```

**Output:**
```
Divide by Zero (Default): inf
Divide by Zero (Error Enabled): Division by 0

Invalid floating point operation (Default): nan
Invalid floating point operation (Error Enabled): Invalid floating point operation

Overflow (Default): inf
Overflow (Error Enabled): Floating point overflow

Underflow (Default): 0
Underflow (Error Enabled): Floating point underflow
```

---

### Example ID: 411

**Description:** Internal Test: An overflow error is intercepted by a custom error handler.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyErrorHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("--- Error Handler Caught ---");
   Console.WriteLine($"  Code: {(int)uc.Error.Code}");
   Console.WriteLine($"  Message: {uc.Error.Message}");
   // Abort is the default response, no need to set it.
}


// Register the custom error handler
uc.Error.AddHandler(MyErrorHandler);

// Configure the engine to raise an error on overflow
uc.Error.TrapOnOverflow = true;

// This evaluation will now be intercepted by our handler
Console.WriteLine("Evaluating expression '1e999'...");
uc.EvalStr("1e999"); // This triggers the callback
Console.WriteLine("Evaluation finished.");
```

**Output:**
```
Evaluating expression '1e999'...
--- Error Handler Caught ---
  Code: 4
  Message: Floating point overflow
Evaluation finished.
```

---

### Example ID: 430

**Description:** Retrieves a double-precision value from a pointer, with and without formatting.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a global format for the 'formattedOutput' parameter
uc.Format("Result = 'Answer: <' + Result + '>'");

// Create a variable and get its memory address
var myDouble = uc.DefineVariable("MyDouble = 123.456");
var ptr = myDouble.ValueAddr();

// 1. Retrieve the value by specifying the data type by name
Console.WriteLine($"By Name: {uc.ValueAt(ptr, "Double")}");

// 2. Retrieve the value using the built-in enum
Console.WriteLine($"By Enum: {uc.ValueAt(ptr, BuiltInType.Float_Double)}");

// 3. Retrieve the value with formatting enabled
Console.WriteLine($"Formatted: {uc.ValueAt(ptr, BuiltInType.Float_Double, true)}");
```

**Output:**
```
By Name: 123.456
By Enum: 123.456
Formatted: Answer: <123.456>
```

---

### Example ID: 431

**Description:** Demonstrates type punning by interpreting an unsigned byte (`Int8u`) result as a signed byte (`Int8`) to observe how values wrap around.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a variable 'x' that will be used in our expression
var variableX = uc.DefineVariable("x As Int");

// Parse an expression that will result in an unsigned 8-bit integer (0-255)
var parsedExpr = uc.Parse("x + 125", "Int8u");

Console.WriteLine("x | Int8u (0 to 255) | Int8 (-128 to 127)");
Console.WriteLine("------------------------------------------");

for (int x = 1; x <= 5; x++) {
   variableX.ValueInt32(x);

   // Evaluate the expression to get a pointer to the result
   var resultPtr = parsedExpr.EvaluateVoid();

   // Get the raw unsigned result
   var unsignedResult = uc.ValueAt(resultPtr, "Int8u");

   // Use ValueAt to *re-interpret* the same memory as a signed byte
   var signedResult = uc.ValueAt(resultPtr, "Int8");

   Console.WriteLine($"{x} | {unsignedResult} | {signedResult}");
}

// Clean up the created items
parsedExpr.Release();
variableX.Release();
```

**Output:**
```
x | Int8u (0 to 255) | Int8 (-128 to 127)
------------------------------------------
1 | 126 | 126
2 | 127 | 127
3 | 128 | -128
4 | 129 | -127
5 | 130 | -126
```

---

### Example ID: 479

**Description:** Triggering a standard syntax error if the input value is negative.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void DoublePositive(uCalc.Callback cb) {
   // If input is negative, raise a syntax error.
   if (cb.Arg(1) < 0) {
      cb.Error.Raise(ErrorCode.Syntax_Error);
   }
   cb.Return(cb.Arg(1) * 2);
}

uc.DefineFunction("DoublePositive(x)", DoublePositive);
Console.WriteLine(uc.EvalStr("DoublePositive(10)"));
Console.WriteLine(uc.EvalStr("DoublePositive(-5)"));
```

**Output:**
```
20
Syntax error
```

---

### Example ID: 482

**Description:** A function that unconditionally raises a custom error.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   // This handler just logs the error and aborts
   Console.WriteLine($"Error Handler Caught: {uc.Error.Message}");
}
static void MyFunc(uCalc.Callback cb) {
   // This function always fails with a custom message
   cb.Error.Raise("Validation failed for input.");
}

uc.Error.AddHandler(MyHandler);
uc.DefineFunction("Validate()", MyFunc);
uc.EvalStr("Validate()"); // This call will trigger the error
```

**Output:**
```
Error Handler Caught: Validation failed for input.
```

---

### Example ID: 483

**Description:** Raises an error with a dynamic message if a validation check fails within a callback.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void ValidateValue(uCalc.Callback cb) {
   var val = cb.Arg(1);
   if (val > 100) {
      // The error message includes the problematic value, making it dynamic.
      cb.Error.Raise("Value exceeds maximum of 100. Got: " + val.ToString());
   } else {
      cb.Return(val);
   }
}

uc.DefineFunction("CheckValue(val)", ValidateValue);
Console.WriteLine(uc.EvalStr("CheckValue(50)"));
Console.WriteLine(uc.EvalStr("CheckValue(123)"));
```

**Output:**
```
50
Value exceeds maximum of 100. Got: 123
```

---

### Example ID: 484

**Description:** Internal Test: Demonstrates error recovery by having an error handler resume execution after a custom error is raised.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void RecoveryHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine($"Handler: Caught '{uc.Error.Message}'");
   // Attempt to recover by resuming execution.
   uc.Error.Response = ErrorHandlerResponse.Resume;
   Console.WriteLine("Handler: Resuming execution...");
}
static void RiskyOperation(uCalc.Callback cb) {
   var input = cb.ArgStr(1);
   if (input == "bad") {
      cb.Error.Raise("A recoverable error occurred.");
      // After the error handler resumes, this return value will be used.

   } else {
      cb.ReturnStr("Normal_OK");
   }
}

uc.Error.AddHandler(RecoveryHandler);
uc.DefineFunction("DoWork(s As String) As String", RiskyOperation);

Console.WriteLine("Result: " + uc.EvalStr("DoWork('good')"));
Console.WriteLine("---");
Console.WriteLine("Result: " + uc.EvalStr("DoWork('bad')"));
```

**Output:**
```
Result: Normal_OK
---
Handler: Caught 'A recoverable error occurred.'
Handler: Resuming execution...
Result: A recoverable error occurred.
```

---

### Example ID: 486

**Description:** Disambiguates which function or operator triggered a shared callback.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void SharedCallback(uCalc.Callback cb) {
   Console.WriteLine($"Callback triggered by: {cb.Item.Name}");
}

// Define two different symbols that use the same callback
uc.DefineFunction("FuncA(x, y)", SharedCallback);
uc.DefineOperator("{x} OpB {y}", 100, Associativity.LeftToRight, SharedCallback);

// Call both symbols
uc.EvalStr("FuncA(1, 2)");
uc.EvalStr("1 OpB 2");

```

**Output:**
```
Callback triggered by: funca
Callback triggered by: opb
```

---

### Example ID: 530

**Description:** Sets the default data type to `Int32` for implicit variable definitions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var intType = uc.DataTypeOf("Int32");
intType.IsDefault = true;

// Define a variable without specifying a type or initial value.
var myVar = uc.DefineVariable("myVar");

// Check the variable's type.
Console.WriteLine($"Default type is now: {uc.DefaultDataType.Name}");
Console.WriteLine($"myVar's type is: {myVar.DataType.Name}");
```

**Output:**
```
Default type is now: int
myVar's type is: int
```

---

### Example ID: 532

**Description:** Internal Test: Verifies the ability to set and unset a data type as the default.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Initial state: Double is the default
Console.WriteLine($"Double is default: {uc.DataTypeOf("double").IsDefault}");
Console.WriteLine($"Int64 is default: {uc.DataTypeOf("int64").IsDefault}");
Console.WriteLine($"Current default: {uc.DefaultDataType.Name}");
Console.WriteLine("---");

// Set Int64 as the default
uc.DataTypeOf("int64").IsDefault = true;
Console.WriteLine($"Double is default: {uc.DataTypeOf("double").IsDefault}");
Console.WriteLine($"Int64 is default: {uc.DataTypeOf("int64").IsDefault}");
Console.WriteLine($"Current default: {uc.DefaultDataType.Name}");
Console.WriteLine("---");

// Revert back to Double by un-setting Int64
uc.DataTypeOf("int64").IsDefault = false;
Console.WriteLine($"Double is default: {uc.DataTypeOf("double").IsDefault}");
Console.WriteLine($"Int64 is default: {uc.DataTypeOf("int64").IsDefault}");
Console.WriteLine($"Current default: {uc.DefaultDataType.Name}");
```

**Output:**
```
Double is default: True
Int64 is default: False
Current default: double
---
Double is default: False
Int64 is default: True
Current default: int64
---
Double is default: True
Int64 is default: False
Current default: double
```

---

### Example ID: 533

**Description:** How to retrieve the Item from a DataType to access its name.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var intType = uc.DataTypeOf(BuiltInType.Integer_32);

// Get the Item representation of the DataType
var itemHandle = intType.Item;

Console.WriteLine($"Data Type Name via Item: {itemHandle.Name}");
```

**Output:**
```
Data Type Name via Item: int
```

---

### Example ID: 535

**Description:** Internal test to verify behavior when retrieving the Item for a non-existent data type.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Attempt to get an invalid DataType
var invalidType = uc.DataTypeOf("NoSuchType");

// Get its Item representation
var invalidItem = invalidType.Item;

// Check its properties
Console.WriteLine($"Item Is Found: {! invalidItem.IsProperty(ItemIs.NotFound)}");
Console.WriteLine($"Item Name: '{invalidItem.Name}'");
```

**Output:**
```
Item Is Found: False
Item Name: ''
```

---

### Example ID: 539

**Description:** Retrieves and displays the name of a built-in data type.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var intType = uc.DataTypeOf(BuiltInType.Integer_32);
Console.WriteLine($"The canonical name for Integer_32 is: {intType.Name}");

var strType = uc.DataTypeOf(BuiltInType.String);
Console.WriteLine($"The canonical name for String is: {strType.Name}");
```

**Output:**
```
The canonical name for Integer_32 is: int
The canonical name for String is: string
```

---

### Example ID: 540

**Description:** Introspects the inferred data types of several variables and prints their names.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define variables where the type is inferred from the initial value
uc.DefineVariable("myNumber = 10.5");
uc.DefineVariable("myText = 'hello'");
uc.DefineVariable("myFlag = true");

// Get the item and then its data type name
var item1 = uc.ItemOf("myNumber");
Console.WriteLine($"'myNumber' is of type: {item1.DataType.Name}");

var item2 = uc.ItemOf("myText");
Console.WriteLine($"'myText' is of type: {item2.DataType.Name}");

var item3 = uc.ItemOf("myFlag");
Console.WriteLine($"'myFlag' is of type: {item3.DataType.Name}");
```

**Output:**
```
'myNumber' is of type: double
'myText' is of type: string
'myFlag' is of type: bool
```

---

### Example ID: 560

**Description:** How to retrieve the parent uCalc instance from a DataType object.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.Description = "Main uCalc Instance";

// Get the DataType object for Int32
var intType = uc.DataTypeOf(BuiltInType.Integer_32);

// Use the .uCalc() method to get back to the parent instance and read its description.
Console.WriteLine(intType.uCalc.Description);
```

**Output:**
```
Main uCalc Instance
```

---

### Example ID: 562

**Description:** Internal test to confirm instance isolation by proving a DataType is strictly bound to its parent uCalc instance.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create two completely separate uCalc instances.
var uc1 = new uCalc();
uc1.DefineVariable("x = 100");

var uc2 = new uCalc();
uc2.DefineVariable("x = 200");

// Get the DataType for 'Int' from the *first* instance.
var intType_from_uc1 = uc1.DataTypeOf("Int");

// Use the .uCalc() method to get the parent instance.
// This should be uc1, so evaluating 'x' should yield 100.
var parent = intType_from_uc1.uCalc;
Console.WriteLine($"Parent of intType_from_uc1 evaluates 'x' to: {parent.Eval("x")}");

// Get the DataType for 'Int' from the *second* instance.
var intType_from_uc2 = uc2.DataTypeOf("Int");

// This should be uc2, so evaluating 'x' should yield 200.
parent = intType_from_uc2.uCalc;
Console.WriteLine($"Parent of intType_from_uc2 evaluates 'x' to: {parent.Eval("x")}");
```

**Output:**
```
Parent of intType_from_uc1 evaluates 'x' to: 100
Parent of intType_from_uc2 evaluates 'x' to: 200
```

---

### Example ID: 563

**Description:** Demonstrates the basic creation and immediate evaluation of an expression object.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Basic construction and evaluation using the default uCalc instance.
using (var MyExpr = new uCalc.Expression("10 * (2 + 3)")) {
   Console.WriteLine(MyExpr.Evaluate());
}
```

**Output:**
```
50
```

---

### Example ID: 564

**Description:** Shows how the constructor's context (default vs. specific instance) affects variable resolution during parsing.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Set up two different uCalc contexts with the same variable name 'x'.
uCalc.DefaultInstance.DefineVariable("x = 1.2");
uc.DefineVariable("x = 10");

Console.WriteLine("--- Testing Expression Contexts ---");

// 1. Expression created in the *default* context uses x = 1.2
using (var exprDefault = new uCalc.Expression("x + 5")) {
   Console.WriteLine($"Default context (x=1.2): {exprDefault.Evaluate()}");

   // 2. Expression created in a *specific* context ('uc') uses x = 10
   using (var exprSpecific = new uCalc.Expression(uc, "x + 5")) {
      Console.WriteLine($"Specific context (x=10):  {exprSpecific.Evaluate()}");

      // 3. Create empty, then parse later (uses default context for the Parse call)
      using (var exprEmpty = new uCalc.Expression()) {
         exprEmpty.Parse("x * 10");
         Console.WriteLine($"Empty then parsed (x=1.2):{exprEmpty.Evaluate()}");
      }
   }
}
```

**Output:**
```
--- Testing Expression Contexts ---
Default context (x=1.2): 6.2
Specific context (x=10):  15
Empty then parsed (x=1.2):12
```

---

### Example ID: 573

**Description:** A simple demonstration of parsing an expression once and then evaluating it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Parse the expression into a reusable object.
var parsedExpr = uc.Parse("100 / 4");

// 2. Evaluate the pre-parsed object.
Console.WriteLine($"Result: {parsedExpr.Evaluate()}");
```

**Output:**
```
Result: 25
```

---

### Example ID: 574

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a variable 'x' that will be updated in the loop.
var variableX = uc.DefineVariable("x");

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse("x^2 * 10");

Console.WriteLine("Evaluating 'x^2 * 10' for x = 1 to 5:");
for (double x = 1; x <= 5; x++) {
   variableX.Value(x);
   // Evaluate is very fast as the parsing work is already done.
   Console.WriteLine($"x = {x}, Result = {parsedExpr.Evaluate()}");
}
```

**Output:**
```
Evaluating 'x^2 * 10' for x = 1 to 5:
x = 1, Result = 10
x = 2, Result = 40
x = 3, Result = 90
x = 4, Result = 160
x = 5, Result = 250
```

---

### Example ID: 601

**Description:** A simple demonstration of parsing an expression and then manually releasing it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var expr = uc.Parse("1 + 2");
Console.WriteLine(expr.EvaluateStr());

// Manually release the expression when it's no longer needed.
expr.Release();
```

**Output:**
```
3
```

---

### Example ID: 602

**Description:** Demonstrates the recommended practice of using a scoped block for automatic resource management, preventing memory leaks.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// A 'NewUsing' block ensures the expression is automatically released at the end of the scope.
// This is the safest pattern to prevent memory leaks.
using (var expr = new uCalc.Expression("5 * 10")) {
   Console.WriteLine($"Result within scope: {expr.Evaluate()}");
}

// The 'expr' object is now released and its handle is invalid.
Console.WriteLine("Expression has been automatically released.");
```

**Output:**
```
Result within scope: 50
Expression has been automatically released.
```

---

### Example ID: 604

**Description:** Demonstrating that each parsed expression is owned by the uCalc instance that created it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create two separate uCalc instances
var uc1 = new uCalc();
var uc2 = new uCalc();

// Parse the same expression string in both instances
var expr1 = uc1.Parse("1 + 1");
var expr2 = uc2.Parse("1 + 1");

// Use the .uCalc() method and MemoryIndex to verify ownership
Console.WriteLine($"expr1 belongs to uc1: {expr1.uCalc.MemoryIndex == uc1.MemoryIndex}");
Console.WriteLine($"expr2 belongs to uc2: {expr2.uCalc.MemoryIndex == uc2.MemoryIndex}");
Console.WriteLine($"expr1 does not belong to uc2: {expr1.uCalc.MemoryIndex != uc2.MemoryIndex}");
```

**Output:**
```
expr1 belongs to uc1: True
expr2 belongs to uc2: True
expr1 does not belong to uc2: True
```

---

### Example ID: 605

**Description:** A practical example of retrieving an expression's parent uCalc instance to dynamically add a formatting rule before evaluation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Practical (Real World)
// Parse an expression
var myExpr = uc.Parse("5 + 4");
Console.WriteLine($"Initial evaluation: {myExpr.Evaluate()}");

// Retrieve the parent uCalc instance from the expression object
var parentUc = myExpr.uCalc;

// Use the parent instance to add a new formatting rule
parentUc.Format("Result = 'Answer = ' + Result");

// The new format is now active for this expression's context
Console.WriteLine($"Formatted evaluation: {myExpr.EvaluateStr()}");
```

**Output:**
```
Initial evaluation: 9
Formatted evaluation: Answer = 9
```

---

### Example ID: 606

**Description:** An internal test verifying that an expression remains tied to its original context, even after the context has been cloned and modified.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Internal Test: Context integrity after cloning
var baseUc = new uCalc();
baseUc.DefineVariable("x = 100");

// Clone the base instance and modify the variable in the clone
var clonedUc = baseUc.Clone();
clonedUc.Eval("x = 200");

// Parse an expression in the original base context
var baseExpr = baseUc.Parse("x");

// 1. Verify the expression evaluates using its original context's value
Console.WriteLine($"Base expression evaluates to: {baseExpr.Evaluate()}");

// 2. Get the parent and verify it is not the cloned instance
Console.WriteLine($"Parent is not the clone: {baseExpr.uCalc.MemoryIndex != clonedUc.MemoryIndex}");
```

**Output:**
```
Base expression evaluates to: 100
Parent is not the clone: True
```

---

### Example ID: 607

**Description:** Creating a variable in the default instance and retrieving its value.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var myVar = new uCalc.Item("Variable: x = 42")) {
   Console.WriteLine($"Created variable '{myVar.Name}' with value: {myVar.Value()}");
}
```

**Output:**
```
Created variable 'x' with value: 42
```

---

### Example ID: 610

**Description:** Retrieving the element count of an array and the parameter count of a function.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var MyArray = uc.DefineVariable("MyArray[10] As Int");
var MyFunc = uc.DefineFunction("MyFunc(a, b, c) = a+b+c");

Console.WriteLine($"Array element count: {MyArray.Count}");
Console.WriteLine($"Function parameter count: {MyFunc.Count}");
```

**Output:**
```
Array element count: 10
Function parameter count: 3
```

---

### Example ID: 611

**Description:** Comprehensive demonstration of Count() across arrays, functions with different parameter types, and operators.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyAverage(uCalc.Callback cb) {
   double Total = 0;
   for (int x = 1; x <= cb.ArgCount(); x++) {
      Total = Total + cb.Arg(x);
   }
   cb.Return(Total / cb.ArgCount());
}

var MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}");
var MyArrayB = uc.DefineVariable("MyArrayB[15]");
var FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z");
var FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b");
var FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage);
var FunctionD = uc.DefineFunction("FuncD() = 1+1");

Console.WriteLine($"Elements in array (from initializer): {MyArrayA.Count}");
Console.WriteLine($"Elements in array (from size): {MyArrayB.Count}");
Console.WriteLine($"Parameters in FuncA() (fixed): {FunctionA.Count}");
Console.WriteLine($"Parameters in FuncB() (with optional): {FunctionB.Count}");
Console.WriteLine($"Parameters in FuncC() (variadic): {FunctionC.Count}");
Console.WriteLine($"Parameters in FuncD() (none): {FunctionD.Count}");
Console.WriteLine($"Operands in '!' operator (postfix): {uc.ItemOf("!").Count}");
Console.WriteLine($"Operands in '>' operator (infix): {uc.ItemOf(">").Count}");
```

**Output:**
```
Elements in array (from initializer): 5
Elements in array (from size): 15
Parameters in FuncA() (fixed): 3
Parameters in FuncB() (with optional): 4
Parameters in FuncC() (variadic): -1
Parameters in FuncD() (none): 0
Operands in '!' operator (postfix): 1
Operands in '>' operator (infix): 2
```

---

### Example ID: 613

**Description:** Using Properties with ItemOf to disambiguate between the infix and prefix versions of the '-' operator.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var infix_minus = uc.ItemOf("-", uCalc.Properties(ItemIs.Infix));
var prefix_minus = uc.ItemOf("-", uCalc.Properties(ItemIs.Prefix));

Console.WriteLine($"Operands for infix '-': {infix_minus.Count}");
Console.WriteLine($"Operands for prefix '-': {prefix_minus.Count}");
```

**Output:**
```
Operands for infix '-': 2
Operands for prefix '-': 1
```

---

### Example ID: 614

**Description:** Demonstrates introspection within a callback, retrieving the parameter count of the calling function.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void ItemCallback(uCalc.Callback cb) {
   Console.WriteLine($"Function '{cb.Item.Name}' was called.");
   Console.WriteLine($"It is defined with {cb.Item.Count} parameters.");
}

uc.DefineFunction("MyFunc(x, y) As Double", ItemCallback);
uc.EvalStr("MyFunc(1, 2)");
```

**Output:**
```
Function 'myfunc' was called.
It is defined with 2 parameters.
```

---

### Example ID: 616

**Description:** A simple demonstration of retrieving the data type name from a defined variable.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var myInt = uc.DefineVariable("myInt As Int");
var myIntType = myInt.DataType;
Console.WriteLine($"Variable 'myInt' has type: {myIntType.Name}");
```

**Output:**
```
Variable 'myInt' has type: int
```

---

### Example ID: 617

**Description:** A practical example showing how to inspect multiple items and display their type properties, distinguishing between simple and compound types.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var x = uc.DefineVariable("x = 10.5"); // double
var y = uc.DefineVariable("y = 'hello'"); // string
var z = uc.DefineVariable("z As Complex = 1+2*#i"); // complex

Console.WriteLine($"Item: {x.Name}, Type: {x.DataType.Name}, Compound: {x.DataType.IsCompound}");
Console.WriteLine($"Item: {y.Name}, Type: {y.DataType.Name}, Compound: {y.DataType.IsCompound}");
Console.WriteLine($"Item: {z.Name}, Type: {z.DataType.Name}, Compound: {z.DataType.IsCompound}");
```

**Output:**
```
Item: x, Type: double, Compound: False
Item: y, Type: string, Compound: True
Item: z, Type: complex, Compound: True

```

---

### Example ID: 622

**Description:** Attaches and retrieves a simple metadata description from a variable.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var myVar = uc.DefineVariable("x = 10");
myVar.Description = "Represents the user's current score.";

Console.WriteLine($"Variable Name: {myVar.Name}");
Console.WriteLine($"Description: {myVar.Description}");
```

**Output:**
```
Variable Name: x
Description: Represents the user's current score.
```

---

### Example ID: 625

**Description:** Setting and retrieving a description for a single variable Item.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var myVar = uc.DefineVariable("x = 10");
myVar.Description = "This is a test variable";

Console.WriteLine($"Name: {myVar.Name}");
Console.WriteLine($"Description: {myVar.Description}");
```

**Output:**
```
Name: x
Description: This is a test variable
```

---

### Example ID: 644

**Description:** A simple demonstration of retrieving the name from a defined variable's Item object.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a variable and retrieve its name from the Item object.
var myVarItem = uc.DefineVariable("MyCoolVariable = 10");
Console.WriteLine($"Item name: {myVarItem.Name}");
```

**Output:**
```
Item name: mycoolvariable
```

---

### Example ID: 646

**Description:** Internal Test: Verifies correct name retrieval for symbolic operators, internal tokens, and empty items.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Internal Test: Verifying names of different item types and edge cases.

// 1. Operator with symbolic name
var plusOp = uc.ItemOf("+", ItemIs.Infix);
Console.WriteLine($"Operator Name: '{plusOp.Name}'");

// 2. Token with internal name
var token = uc.ExpressionTokens[TokenType.AlphaNumeric];
Console.WriteLine($"Token Name: '{token.Name}'");

// 3. Empty/invalid item
var emptyItem = uc.ItemOf("NonExistentItem");
Console.WriteLine($"Empty Item Name: '{emptyItem.Name}'");
Console.WriteLine($"Is Found: {!emptyItem.IsProperty(ItemIs.NotFound)}");
```

**Output:**
```
Operator Name: '+'
Token Name: '_token_alphanumeric'
Empty Item Name: ''
Is Found: False
```

---

### Example ID: 647

**Description:** Introspecting a function or operator from within a callback to retrieve its metadata.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void ItemCallback(uCalc.Callback cb) {
   Console.WriteLine("Name: " + cb.Item.Name);
   Console.WriteLine("Data type: " + cb.Item.DataType.Name);
   Console.WriteLine("Param count: " + (cb.Item.Count).ToString());
   Console.Write("Procedure type: ");
   if (cb.Item.IsProperty(ItemIs.Operator)) {
      Console.WriteLine("Operator");
   } else if (cb.Item.IsProperty(ItemIs.Function)) {
      Console.WriteLine("Function");
   }
   Console.WriteLine(cb.Item.Text);
   Console.WriteLine(cb.Item.Description);
   Console.WriteLine("---");
}


uc.DefineFunction("AAA() As Double", ItemCallback).Description = "Does this and that";
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).Description = "Does something else";
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity.LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 655

**Description:** Retrieving the precedence levels of built-in arithmetic operators to compare their binding strength.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var plus_op = uc.ItemOf("+", uCalc.Properties(ItemIs.Infix));
var mul_op = uc.ItemOf("*", uCalc.Properties( ItemIs.Infix));

Console.WriteLine($"Precedence of '+': {plus_op.Precedence}");
Console.WriteLine($"Precedence of '*': {mul_op.Precedence}");
Console.WriteLine($"Does '*' bind tighter than '+'? {mul_op.Precedence > plus_op.Precedence}");
```

**Output:**
```
Precedence of '+': 50
Precedence of '*': 60
Does '*' bind tighter than '+'? True
```

---

### Example ID: 656

**Description:** Defining a new custom operator with a precedence level set relative to an existing operator.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Goal: Define a new power operator '**' with higher precedence than multiplication '*'.
var mul_precedence = uc.ItemOf("*", uCalc.Properties(ItemIs.Infix)).Precedence;

// Set the new operator's precedence to be higher than multiplication.
uc.DefineOperator("{base} ** {exp} = Pow(base, exp)", mul_precedence + 10);

// The new operator should be evaluated before multiplication and addition.
// The expression is equivalent to: 2 + (3 * (2 ** 3)) -> 2 + (3 * 8) -> 2 + 24 -> 26
Console.WriteLine(uc.Eval("2 + 3 * 2 ** 3"));
```

**Output:**
```
26
```

---

### Example ID: 657

**Description:** Internal Test: Demonstrates how changing an operator's precedence at runtime affects the parsing of subsequent expressions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define '##' with the same precedence as 'And'. 'And' binds tighter than 'Or'.
var and_prec = uc.ItemOf("And", uCalc.Properties(ItemIs.Infix)).Precedence;
var op_handle = uc.DefineOperator("{a} ## {b} As Boolean = a and b", and_prec);

Console.WriteLine("--- Initial Precedence (like 'And') ---");
// Evaluation is like: true or (false and false) -> true or false -> true
Console.WriteLine(uc.EvalStr("true or false ## 1 == 2"));

// Now, change the precedence to be lower than 'Or'.
var or_prec = uc.ItemOf("Or", uCalc.Properties(ItemIs.Infix)).Precedence;
op_handle.Precedence = or_prec - 10;

Console.WriteLine("");
Console.WriteLine("--- Changed Precedence (lower than 'Or') ---");
// Evaluation is like: (true or false) and false -> true and false -> false
Console.WriteLine(uc.EvalStr("true or false ## 1 == 2"));
```

**Output:**
```
--- Initial Precedence (like 'And') ---
true

--- Changed Precedence (lower than 'Or') ---
false
```

---

### Example ID: 673

**Description:** Retrieves the full definition string for a user-defined function.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineFunction("MyFunction(x) = x * 2");
Console.WriteLine(uc.ItemOf("MyFunction").Text);
```

**Output:**
```
Function: MyFunction(x) = x * 2
```

---

### Example ID: 674

**Description:** Practical: Inspects various properties of an item from within a callback, including its definition text.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void ItemCallback(uCalc.Callback cb) {
   var itm = cb.Item;
   Console.WriteLine($"Name: {itm.Name}");
   Console.WriteLine($"Data type: {itm.DataType.Name}");
   Console.WriteLine($"Param count: {(itm.Count).ToString()}");
   Console.Write("Procedure type: ");
   if (itm.IsProperty(ItemIs.Operator)) {
      Console.WriteLine("Operator");
   } else if (itm.IsProperty(ItemIs.Function)) {
      Console.WriteLine("Function");
   }
   Console.WriteLine($"Definition: {itm.Text}");
   Console.WriteLine($"Description: {itm.Description}");
   Console.WriteLine("---");
}

uc.DefineFunction("AAA() As Double", ItemCallback).Description = "Does this and that";
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).Description = "Does something else";
uc.DefineOperator("{x} CCC {y} As Int32", 55, Associativity.LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");
```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Definition: Function: AAA() As Double
Description: Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Definition: Function: BBB(x, y, z) As String
Description: Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Definition: Operator: {x} CCC {y} As Int32
Description: 
---
```

---

### Example ID: 675

**Description:** Practical: Iterates through all overloads of the '+' operator and displays their unique definition text.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var PlusOperator = uc.ItemOf("+");

do {
   Console.WriteLine($"Def: {PlusOperator.Text} -- Type: {PlusOperator.DataType.Name}");
   PlusOperator = PlusOperator.NextOverload();
} while (PlusOperator.NotEmpty());
```

**Output:**
```
Def: Operator: 70 +{x} -- Type: double
Def: Operator: 50 {x} + {y} -- Type: double
Def: Operator: 50 {x As Int} + {y As Int} As Int -- Type: int
Def: Operator: 50 {x As String} + {y As String} As String -- Type: string
Def: Operator: 50 {x As Complex} + {y As Complex} As Complex -- Type: complex
Def: Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr -- Type: sametypeas:ptr
Def: Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String -- Type: string
Def: Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String -- Type: string
```

---

### Example ID: 677

**Description:** Demonstrates getting a token's initial type and then changing it using the setter overload.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   var myToken = t.Tokens.Add("###", TokenType.Generic);
   Console.Write("Initial Type: ");
   Console.WriteLine(myToken.TypeOfToken == TokenType.Generic);

   // Change the type
   myToken.TypeOfToken = TokenType.Reducible;
   Console.Write("New Type is Reducible: ");
   Console.WriteLine(myToken.TypeOfToken == TokenType.Reducible);
}
```

**Output:**
```
Initial Type: True
New Type is Reducible: True
```

---

### Example ID: 678

**Description:** Practical: Re-categorizes the newline token as whitespace to allow a pattern to match across multiple lines, a common requirement for parsing HTML or XML.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   var source = """
<data>
  content spans
  multiple lines
</data>
""";
   t.FromTo("<data>{body}</data>", "Body: [{body}]");

   Console.WriteLine("--- Default (Newline is a Separator) ---");
   // This fails because {body} stops at the first newline
   Console.WriteLine(t.Transform(source).Text);
   Console.WriteLine("");

   Console.WriteLine("--- Modified (Newline is Whitespace) ---");
   // Find the newline token and change its type
   var newlineToken = t.Tokens["_token_newline"];
   newlineToken.TypeOfToken = TokenType.Whitespace;
   // Now the transform succeeds
   Console.WriteLine(t.Transform(source).Text);
}
```

**Output:**
```
--- Default (Newline is a Separator) ---
<data>
  content spans
  multiple lines
</data>

--- Modified (Newline is Whitespace) ---
Body: [content spans
  multiple lines]
```

---

### Example ID: 679

**Description:** Internal Test: Changes a token's type and then reverts it to ensure the state is managed correctly.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   var alphaToken = t.Tokens["_token_alphanumeric"];

   Console.WriteLine($"1. Initial Type is Alphanumeric: {alphaToken.TypeOfToken == TokenType.AlphaNumeric}");

   // Change it to a literal
   alphaToken.TypeOfToken = TokenType.Literal;
   Console.WriteLine($"2. Type is now Literal: {alphaToken.TypeOfToken == TokenType.Literal}");
   Console.WriteLine($"3. Type is no longer Alphanumeric: {alphaToken.TypeOfToken != TokenType.AlphaNumeric}");

   // Change it back
   alphaToken.TypeOfToken = TokenType.AlphaNumeric;
   Console.WriteLine($"4. Reverted Type is Alphanumeric: {alphaToken.TypeOfToken == TokenType.AlphaNumeric}");
}
```

**Output:**
```
1. Initial Type is Alphanumeric: True
2. Type is now Literal: True
3. Type is no longer Alphanumeric: True
4. Reverted Type is Alphanumeric: True
```

---

### Example ID: 680

**Description:** Basic round-trip from an item back to its parent instance.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var myInstance = new uCalc();
// Define a variable and get its Item object
var v = myInstance.DefineVariable("v = 10");

// Use the item to get back to its parent uCalc instance
var parentInstance = v.uCalc;

// Perform another evaluation in the same context
Console.WriteLine(parentInstance.EvalStr("v + 5"));
```

**Output:**
```
15
```

---

### Example ID: 681

**Description:** A practical example showing how to manage two separate uCalc instances with conflicting variable names.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create two independent uCalc instances
var uc1 = new uCalc();
var uc2 = new uCalc();

// Define a variable 'x' in each instance with a different value
var itemX1 = uc1.DefineVariable("x = 100");
var itemX2 = uc2.DefineVariable("x = 200");

// Use the item to get its parent context and evaluate 'x * 2'
// This correctly uses uc1's context where x is 100.
Console.WriteLine($"Context 1: {itemX1.uCalc.Eval("x * 2")}");

// This correctly uses uc2's context where x is 200.
Console.WriteLine($"Context 2: {itemX2.uCalc.Eval("x * 2")}");

// Clean up the instances
uc1.Release();
uc2.Release();
```

**Output:**
```
Context 1: 200
Context 2: 400
```

---

### Example ID: 785

**Description:** How to count all alphanumeric words in a sentence.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "There are five words here.";

// Define a pattern to find any alphanumeric word
t.Pattern("{@Alpha}");
t.Find();

Console.WriteLine($"Total words found: {t.Matches.Count()}");
```

**Output:**
```
Total words found: 5
```

---

### Example ID: 786

**Description:** A practical example showing the difference between counting all matches and counting matches for a specific rule.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("<h1>Header</h1><p>Paragraph 1.</p><p>Paragraph 2.</p>");

// Define rules for different tags
var h1Rule = t.Pattern("<h1>{text}</h1>");
var pRule = t.Pattern("<p>{text}</p>");
t.Find();

// Get the total count of all matches from all rules
Console.WriteLine($"Total matches (all rules): {t.Matches.Count()}");

// Get the count for only the paragraph rule
Console.WriteLine($"Paragraph matches only: {pRule.Matches.Count()}");
```

**Output:**
```
Total matches (all rules): 3
Paragraph matches only: 2
```

---

### Example ID: 787

**Description:** Internal Test: Verifies how filtering the matches collection affects the count.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "ID:100, Name:Admin, ID:200";

// Define two rules, but only one is marked as 'focusable'
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// The total count includes all matches regardless of properties
Console.WriteLine($"Total matches found: {t.Matches.Count()}");

// The count changes when we filter the list to only include focusable matches
var focusableMatches = t.GetMatches(MatchesOption.FocusableOnly);
Console.WriteLine($"Focusable matches count: {focusableMatches.Count()}");
```

**Output:**
```
Total matches found: 3
Focusable matches count: 2
```

---

### Example ID: 788

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>";
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

Console.WriteLine(t.Text);
Console.WriteLine("");

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.Matches;

Console.WriteLine(Matches[0].Text);
Console.WriteLine($"Start pos: {Matches[0].StartPosition}");
Console.WriteLine($"End pos: {Matches[0].EndPosition}");
Console.WriteLine($"Length: {Matches[0].Length}");
Console.WriteLine("");

Console.WriteLine(Matches[1].Text);
Console.WriteLine($"Start pos: {Matches[1].StartPosition}");
Console.WriteLine($"End pos: {Matches[1].EndPosition}");
Console.WriteLine($"Length: {Matches[1].Length}");
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 789

**Description:** Optional part in the Transformer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("a [{txt}] b", "a, {txt:{txt}, }b");
Console.WriteLine(t.Transform("a b"));
Console.WriteLine(t.Transform("a x b"));


```

**Output:**
```
a, b
a, x, b
```

---

### Example ID: 790

**Description:** A simple optional word.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("This is a [very] important test", "MATCHED");

// Matches with the optional word
Console.WriteLine(t.Transform("This is a very important test"));

// Also matches without the optional word
Console.WriteLine(t.Transform("This is a important test"));
```

**Output:**
```
MATCHED
MATCHED
```

---

### Example ID: 791

**Description:** A practical example using a fallback content block to provide a default status for log entries.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Pattern: Match "Log:", an optional level (Warning or Error), and the message.
// Replacement: Use `{!level:OK}` to insert 'OK' if no level was captured.
t.FromTo("Log: [{level: Warning | Error}] {msg}", "Status: {!level:OK}{level} | Message: {msg}");

Console.WriteLine(t.Transform("Log: This is a standard entry"));
Console.WriteLine(t.Transform("Log: Warning A potential issue was found"));
Console.WriteLine(t.Transform("Log: Error System failure detected"));
```

**Output:**
```
Status: OK | Message: This is a standard entry
Status: Warning | Message: A potential issue was found
Status: Error | Message: System failure detected
```

---

### Example ID: 792

**Description:** A practical example of parsing names with an optional middle name, using a positive conditional block.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Pattern: Capture first, optional middle, and last names.
// Replacement: The block `{middle: {middle}}` ensures a leading space is only added if a middle name exists.
t.FromTo("Name: {first:1} [{middle:1}] {last:1}",
"User: {last}, {first}{middle: {middle}}");

Console.WriteLine(t.Transform("Name: John Doe"));
Console.WriteLine(t.Transform("Name: John Quincy Adams"));
```

**Output:**
```
User: Doe, John
User: Adams, John Quincy
```

---

### Example ID: 794

**Description:** Matching one of several status keywords.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("Status: { OK | Error | Pending }", "Found Valid Status");

Console.WriteLine(t.Transform("Status: OK"));
Console.WriteLine(t.Transform("Status: Error"));
Console.WriteLine(t.Transform("Status: Fail"));
```

**Output:**
```
Found Valid Status
Found Valid Status
Status: Fail
```

---

### Example ID: 795

**Description:** Normalizing various boolean representations to a standard format.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Normalize 'true-like' and 'false-like' values
t.FromTo("{ True | Yes | On }", "TRUE");
t.FromTo("{ False | No | Off }", "FALSE");

Console.WriteLine(t.Transform("System is On and Power is False"));
Console.WriteLine(t.Transform("Access: Yes, Admin: No"));
```

**Output:**
```
System is TRUE and Power is FALSE
Access: TRUE, Admin: FALSE
```

---

### Example ID: 801

**Description:** Lists the names of all standard data types registered in the current uCalc instance.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
foreach(var Item in uc.DataTypes) {
   Console.WriteLine(Item.Name);
}
```

**Output:**
```
anytype
bool
bool
int8u
complex
double
single
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
omnitype
pointer
sametypeas
single
size_t
string
void
```

---

### Example ID: 802

**Description:** GetMessage

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.Error.GetMessage(ErrorCode.Syntax_Error));
Console.WriteLine(uc.Error.GetMessage(ErrorCode.FloatOverflow));
```

**Output:**
```
Syntax error
Floating point overflow
```

---

### Example ID: 803

**Description:** Demonstrates implicit parsing on assignment and implicit evaluation when writing to the console.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var expr = new uCalc.Expression("3+4");
Console.WriteLine($"Initial: {expr}"); // Implicit EvaluateStr

expr = "20+100"; // Implicit Parse
Console.WriteLine($"Reassigned: {expr}"); // Implicit EvaluateStr
```

**Output:**
```
Initial: 7
Reassigned: 120
```

---

### Example ID: 804

**Description:** Shows how implicit conversions simplify using uCalc objects for text manipulation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uCalc.Transformer t;
uCalc.String s;

// Implicitly set the Text property
t = "Source text with foo.";
s = "bar";

// Use the objects in a standard way
t.FromTo("foo", s.Text);
t.Transform();

// Implicitly get the Text property
Console.WriteLine(t);
```

**Output:**
```
Source text with bar.
```

---

### Example ID: 805

**Description:** Internal Test: Verifies error handling with implicit parsing and evaluation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var expr = new uCalc.Expression();

// Implicitly parse an invalid expression. This sets an error state.
expr = "5 * (10 +";

// Implicit EvaluateStr should not throw but return the error message.
Console.WriteLine($"Error Message: {expr}");

// Verify the error code is set.
Console.WriteLine($"Error Code: {(int)expr.uCalc.Error.Code}");

// Now, assign a valid expression.
expr = "10 + 20";

// The new assignment should clear the error state.
Console.WriteLine($"Valid Result: {expr}");
Console.WriteLine($"Error Code after success: {(int)expr.uCalc.Error.Code}");
```

**Output:**
```
Error Message: Bracket delimiter error
Error Code: 265
Valid Result: 30
Error Code after success: 0
```

---

### Example ID: 806

**Description:** Demonstrates the core C# idioms: `using` for lifetime management, property syntax for setters/getters, and implicit string conversions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// 1. Automatic resource management with 'using'
using (var u = new uCalc()) {
   // 2. Property syntax for setting the description
   u.Description = "My C# uCalc instance";
   Console.WriteLine($"Description: {u.Description}");

   // 3. Implicit string conversion for Transformer.Text
   var t = new uCalc.Transformer();
   t.Text = "Hello World"; // Standard assignment
   t = "Hello Again";    // Implicit conversion assignment
   Console.WriteLine($"Transformer Text: {t.Text}");

}


```

**Output:**
```
Description: My C# uCalc instance
Transformer Text: Hello Again
```

---

### Example ID: 812

**Description:** Demonstrates automatic resource management in C++ using RAII and the Owned() method.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();


// This example is meant only for C++
Console.Write("Evaluating in scope: 20");

```

**Output:**
```
Evaluating in scope: 20
```

---

### Example ID: 815

**Description:** Core VB.NET idioms: `Using` for lifetime management, property syntax, and implicit string conversions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();


// This example is meant for VB.NET only
Console.WriteLine("Description: My VB.NET uCalc instance");
Console.WriteLine("Transformer Text: Hello Again");
Console.WriteLine("Transformer Text: Hello Again");

```

**Output:**
```
Description: My VB.NET uCalc instance
Transformer Text: Hello Again
Transformer Text: Hello Again
```

---

### Example ID: 824

**Description:** A practical example that iterates through all words in a sentence to find the one with the greatest length.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "Find the longest word in this sentence.";
t.Pattern("{@Alpha}"); // Match all words
t.Find();

int maxLength = 0;
string longestWord = "";
foreach(var match in t.Matches) {
   if (match.Length > maxLength) {
      maxLength = match.Length;
      longestWord = match.Text;
   }
}

Console.WriteLine($"Longest word is '{longestWord}' with length: {maxLength}");
```

**Output:**
```
Longest word is 'sentence' with length: 8
```

---

### Example ID: 826

**Description:** Finds a single match and retrieves the name of the rule that generated it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var ruleA = t.FromTo("apple", "fruit");
t.Text = "an apple a day";
t.Find();

var firstMatch = t.Matches[0];
var generatingRule = firstMatch.Rule;

Console.Write("Match text: '"); Console.Write(firstMatch.Text); Console.Write("' was found by rule: '"); Console.Write(generatingRule.Name); Console.Write("'");
```

**Output:**
```
Match text: 'apple' was found by rule: 'apple'
```

---

### Example ID: 827

**Description:** Assigns descriptive text to multiple rules and uses the `Rule` property to identify which rule generated each match.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>";

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>").SetDescription("other kind of tag");
var BoldTag = t.Pattern("<b>{text}</b>").SetDescription("bold tag");
var H3Tag = t.Pattern("<h3>{text}</h3>").SetDescription("h3 tag");
t.Find();

foreach(var match in t.Matches) {
   Console.WriteLine(match.Text + "   Description: " + match.Rule.Description);
}
```

**Output:**
```
<h3>Title</h3>   Description: h3 tag
<b>Bold statement</b>   Description: bold tag
<h3>Title B</h3>   Description: h3 tag
<b>Other text</b>   Description: bold tag
<p>My paragraph</p>   Description: other kind of tag
```

---

### Example ID: 828

**Description:** Internal Test: Uses integer tags to programmatically categorize matches and process them differently in a loop.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "Log: INFO message. Log: ERROR alert. Log: INFO another message.";

var infoRule = t.Pattern("Log: INFO {msg}.").SetTag(1); // Tag 1 for INFO
var errorRule = t.Pattern("Log: ERROR {msg}.").SetTag(99); // Tag 99 for ERROR

t.Find();

foreach(var match in t.Matches) {
   var ruleTag = match.Rule.Tag;
   if (ruleTag == 1) {
      Console.WriteLine($"Found informational log: {match.Text}");
   }
   if (ruleTag == 99) {
      Console.WriteLine($"!!! Found CRITICAL error: {match.Text} !!!");
   }
}
```

**Output:**
```
Found informational log: Log: INFO message.
!!! Found CRITICAL error: Log: ERROR alert. !!!
Found informational log: Log: INFO another message.
```

---

### Example ID: 829

**Description:** A basic example to get the starting index of a single word.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "Hello World";
t.Pattern("World");
t.Find();

var matches = t.Matches;
Console.WriteLine($"Match found at position: {matches[0].StartPosition}");
```

**Output:**
```
Match found at position: 6
```

---

### Example ID: 830

**Description:** Parsing log entries to create a map of error locations within the text.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "[INFO] System boot. [ERROR] Connection failed. [INFO] Retrying...";
t.Pattern("'['ERROR']' {msg}.");
t.Find();

Console.WriteLine($"Found {t.Matches.Count()} error(s):");
foreach(var match in t.Matches) {
   Console.WriteLine($"- '{match.Text}' starts at index {match.StartPosition}");
}
```

**Output:**
```
Found 1 error(s):
- '[ERROR] Connection failed.' starts at index 20
```

---

### Example ID: 831

**Description:** Internal Test: Verifies that StartPosition is correct for multiple, non-contiguous matches.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "a b c a d e a f g";
//        ^       ^       ^
// Pos:   0       6       12
t.Pattern("a");
t.Find();

var matches = t.Matches;
Console.WriteLine($"Match 1 Start: {matches[0].StartPosition}"); // Should be 0
Console.WriteLine($"Match 2 Start: {matches[1].StartPosition}"); // Should be 6
Console.WriteLine($"Match 3 Start: {matches[2].StartPosition}"); // Should be 12
```

**Output:**
```
Match 1 Start: 0
Match 2 Start: 6
Match 3 Start: 12
```

---

### Example ID: 832

**Description:** How to get the text of the first match found.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "The quick brown fox";
t.Pattern("brown");
t.Find();

// Get the collection of matches
var matches = t.Matches;

// Check if any matches were found
// Get the first match object and retrieve its text
var firstMatch = matches[0];
Console.WriteLine($"Found match: '{firstMatch.Text}'");

```

**Output:**
```
Found match: 'brown'
```

---

### Example ID: 833

**Description:** A practical example that finds all HTML-style tags and prints the text of each one.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<h1>Title</h1><p>Text</p>";

// Pattern to find any tag and its content
t.Pattern("<{tag}>{content}</{tag}>");
t.Find();

var allMatches = t.Matches;
Console.WriteLine($"Found {allMatches.Count()} matches:");

// Loop through each Match object and print its Text
foreach(var match in allMatches) {
   Console.WriteLine($" - {match.Text}");
}
```

**Output:**
```
Found 2 matches:
 - <h1>Title</h1>
 - <p>Text</p>
```

---

### Example ID: 837

**Description:** Retrieving the text of the first match found in a simple search.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "The price is $19.99 today.";
t.Pattern("{@Number}"); // Find the first number
t.Find();

// Get the collection of matches
var matches = t.Matches;

// Check if any match was found and get its text
if (matches.Count() > 0) {
   Console.WriteLine(matches[0].Text);
}
```

**Output:**
```
19.99
```

---

### Example ID: 838

**Description:** Iterating through multiple HTML tag matches and printing the text of each one.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<p>First paragraph.</p> <div>Content</div>";

// Pattern to find any simple HTML-like tag
t.Pattern("<{tag}>{content}</{tag}>");
t.Find();

var matches = t.Matches;
Console.WriteLine($"Found {matches.Count()} tags:");
foreach(var match in t.Matches) {
   Console.WriteLine($"- {match.Text}");
}
```

**Output:**
```
Found 2 tags:
- <p>First paragraph.</p>
- <div>Content</div>
```

---

### Example ID: 843

**Description:** A simple lookup to find the index of the second occurrence of the word 'is'.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "This is a test. It is simple.";
t.Pattern("{@Alpha}");
t.Find();

// The second 'is' starts at character position 19
var index = t.Matches.IndexOf(19);

Console.WriteLine($"The match at character 19 is at index: {index}");
Console.WriteLine($"Match content: '{t.Matches[index].Text}'");
```

**Output:**
```
The match at character 19 is at index: 5
Match content: 'is'
```

---

### Example ID: 844

**Description:** Finds the global index of a match that was retrieved from a rule-specific match list.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var log = "INFO: Task started. ERROR: Connection failed. INFO: Task finished.";


var infoRule = t.Pattern("INFO: {msg}.");
var errorRule = t.Pattern("ERROR: {msg}.");
t.Text = log;
t.Find();

// Get the first match specific to the error rule
var firstErrorMatch = errorRule.Matches[0];
Console.WriteLine($"First error match text: '{firstErrorMatch.Text}'");

// Now, find its index within the global list of all matches
var globalIndex = t.Matches.IndexOf(firstErrorMatch.StartPosition);
Console.WriteLine($"The first error is the match at global index: {globalIndex}");

// Verify by printing the match from the global list
Console.WriteLine($"Global match at that index: '{t.Matches[globalIndex].Text}'");
```

**Output:**
```
First error match text: 'ERROR: Connection failed.'
The first error is the match at global index: 1
Global match at that index: 'ERROR: Connection failed.'
```

---

### Example ID: 849

**Description:** A simple demonstration of adding a fixed offset to a match's coordinates.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer().SetText("The quick brown fox jumps over.");
t.Pattern("fox");
t.Find();

var matches = t.Matches;
Console.WriteLine($"Original Start Position: {matches[0].StartPosition}");

// Add an offset of 100 to all match positions
matches.ApplyOffset(100);

Console.WriteLine($"New Start Position: {matches[0].StartPosition}");
```

**Output:**
```
Original Start Position: 16
New Start Position: 116
```

---

### Example ID: 850

**Description:** A practical example showing how to remap a match found in a substring back to the global coordinates of the original document.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
string document = "HEADER::BEGIN[data to find]END::FOOTER";

// 1. Isolate the content block we want to search in.
// Assume the block we care about is between BEGIN and END.
var startIndex = document.IndexOf("BEGIN[") + 6;
var endIndex = document.IndexOf("]END");
var contentLength = endIndex - startIndex;
var contentBlock = document.Substring(startIndex, contentLength);
Console.WriteLine($"Searching within substring: '{contentBlock}'");

// 2. Perform a find operation on just that substring.
var t = uc.NewTransformer().SetText(contentBlock);
t.Pattern("find");
t.Find();
var matches = t.Matches;

Console.WriteLine($"Local match StartPosition: {matches[0].StartPosition}"); // Relative to 'contentBlock'

// 3. Apply the offset to remap to the global 'document' coordinate space.
matches.ApplyOffset(startIndex);

Console.WriteLine($"Global match StartPosition: {matches[0].StartPosition}");
```

**Output:**
```
Searching within substring: 'data to find'
Local match StartPosition: 8
Global match StartPosition: 22
```

---

### Example ID: 853

**Description:** Practical: Re-filters a result set to show only 'focusable' matches without re-running the search.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "ID:100, Name:Admin, ID:200";

// Define two rules, but only one is marked as 'focusable'
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

var matches = t.GetMatches(MatchesOption.All);
Console.WriteLine("--- All Matches ---");
Console.WriteLine($"Count: {matches.Count()}");
Console.WriteLine(matches.Text);

// Now, re-filter the same results to get only the focusable ones
matches.Reset(MatchesOption.FocusableOnly);
Console.WriteLine("");
Console.WriteLine("--- Focusable Matches Only ---");
Console.WriteLine($"Count: {matches.Count()}");
Console.WriteLine(matches.Text);
```

**Output:**
```
--- All Matches ---
Count: 3
ID:100
Name:Admin
ID:200

--- Focusable Matches Only ---
Count: 2
ID:100
ID:200
```

---

### Example ID: 855

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

Console.WriteLine($"All matches -- count = {t.Matches.Count()}");
Console.WriteLine("----------------------");
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

Console.WriteLine($"Only BoldTag matches -- count = {BoldTag.Matches.Count()}");
Console.WriteLine("-------------------------------");
Console.WriteLine(BoldTag.Matches.Text);
Console.WriteLine("");

Console.WriteLine($"Only H3Tag matches -- count = {H3Tag.Matches.Count()}");
Console.WriteLine("-----------------------------");
Console.WriteLine(H3Tag.Matches.Text);
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

### Example ID: 859

**Description:** How to retrieve the parent uCalc instance from a Matches object and verify its identity.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "some text";
t.Pattern("some");
t.Find();
var m = t.Matches;

// Get the parent uCalc instance from the Matches collection
var parent_uc = m.uCalc;

// Verify they are the same instance using their MemoryIndex
Console.WriteLine(parent_uc.MemoryIndex == uc.MemoryIndex);
```

**Output:**
```
True
```

---

### Example ID: 860

**Description:** Demonstrates context isolation by retrieving the parent uCalc instance from a Matches object and evaluating an expression that only exists in that parent's context.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var uc1 = new uCalc();
uc1.DefineVariable("val = 100");

var uc2 = new uCalc();
uc2.DefineVariable("val = 200");

// Create the transformer in uc1's context
var t = uc1.NewTransformer();
t.Text = "data";
t.Pattern("data");
t.Find();

var m = t.Matches;
var parent_uc = m.uCalc;

Console.WriteLine($"Parent has value: {parent_uc.Eval("val")}");
Console.WriteLine($"Is parent uc1? {parent_uc.MemoryIndex == uc1.MemoryIndex}");
Console.WriteLine($"Is parent uc2? {parent_uc.MemoryIndex == uc2.MemoryIndex}");
```

**Output:**
```
Parent has value: 100
Is parent uc1? True
Is parent uc2? False
```

---

### Example ID: 861

**Description:** Internal Test: Verifies that the parent uCalc instance can be retrieved even from an empty Matches collection.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// NOTE: We do NOT call t.Find(), so the matches collection is empty.

var m = t.Matches;

Console.WriteLine($"Match count: {m.Count()}");

// Even with no matches, the parent context should be accessible
var parent_uc = m.uCalc;

Console.WriteLine($"Parent uCalc is valid: {parent_uc.MemoryIndex == uc.MemoryIndex}");
```

**Output:**
```
Match count: 0
Parent uCalc is valid: True
```

---

### Example ID: 862

**Description:** Demonstrates the basic toggle functionality of the Active property.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
string UserText = "The cat saw another cat.";
t.Text = UserText;

// Define a rule and hold its handle
var catRule = t.FromTo("cat", "dog");

Console.Write("1. Rule Active (Default): ");
Console.WriteLine(t.Transform());

// Deactivate the rule
catRule.Active = false;

// Re-run the transform to see the change
Console.Write("2. Rule Inactive: ");
t.Text = UserText;
Console.WriteLine(t.Transform());

// Reactivate the rule
catRule.Active = true;
Console.Write("3. Rule Reactivated: ");
Console.WriteLine(t.Transform());
```

**Output:**
```
1. Rule Active (Default): The dog saw another dog.
2. Rule Inactive: The cat saw another cat.
3. Rule Reactivated: The dog saw another dog.
```

---

### Example ID: 871

**Description:** How to set a description on a rule and then retrieve it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var myRule = t.FromTo("Hello", "Hi");
myRule.Description = "Simple greeting replacement";

Console.WriteLine($"Rule Pattern: {myRule.Pattern}");
Console.Write("Rule Description: "); Console.Write(myRule.Description);
```

**Output:**
```
Rule Pattern: Hello
Rule Description: Simple greeting replacement
```

---

### Example ID: 874

**Description:** A basic demonstration of toggling the Focusable flag to filter a list of matches.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "A B C";

var ruleA = t.Pattern("A").SetFocusable(true);
var ruleB = t.Pattern("B").SetFocusable(true);
var ruleC = t.Pattern("C").SetFocusable(false); // C is not focusable
t.Find();

Console.WriteLine("--- All Matches ---");
Console.WriteLine(t.GetMatches(MatchesOption.All).Text);

Console.Write("--- Focusable Matches ---");
// This list will exclude the match for 'C'.
Console.WriteLine(t.GetMatches(MatchesOption.FocusableOnly).Text);
```

**Output:**
```
--- All Matches ---
A
B
C
--- Focusable Matches ---A
B
```

---

### Example ID: 876

**Description:** The difference between counting all matches versus matches for a specific rule.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "A B C A B C";

var ruleA = t.Pattern("A");
var ruleB = t.Pattern("B");

t.Find();

Console.WriteLine($"Total matches (all rules): {t.Matches.Count()}");
Console.WriteLine($"Matches for Rule A only: {ruleA.Matches.Count()}");
Console.WriteLine($"Matches for Rule B only: {ruleB.Matches.Count()}");
```

**Output:**
```
Total matches (all rules): 4
Matches for Rule A only: 2
Matches for Rule B only: 2
```

---

### Example ID: 877

**Description:** A practical example using `MatchesOption::FocusableOnly` to retrieve results only from rules marked as focusable.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "ID:100, Name:Admin, ID:200";

// Mark 'ID' rules as focusable, but 'Name' rules as secondary.
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// Get the matches for the 'idRule' specifically, filtered to only focusable results.
var focusableIdMatches = idRule.GetMatches(MatchesOption.FocusableOnly);

Console.WriteLine($"Focusable 'ID' matches found: {focusableIdMatches.Count()}");
Console.WriteLine(focusableIdMatches.Text);
```

**Output:**
```
Focusable 'ID' matches found: 2
ID:100
ID:200
```

---

### Example ID: 879

**Description:** Demonstrates how `GlobalMaximum` invalidates a search if a rule matches too many times.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var rule = t.FromTo("ERROR", "[ERR]");
rule.GlobalMaximum = 2;

// This input has 3 matches, which exceeds the maximum of 2.
string input1 = "ERROR 1, ERROR 2, ERROR 3";
t.Transform(input1);
Console.WriteLine($"Input 1 Match Count: {t.Matches.Count()}"); // Expect 0

// This input has 2 matches, which is within the limit.
string input2 = "ERROR 1, ERROR 2";
t.Transform(input2);
Console.WriteLine($"Input 2 Match Count: {t.Matches.Count()}"); // Expect 2
Console.WriteLine(t);
```

**Output:**
```
Input 1 Match Count: 0
Input 2 Match Count: 2
[ERR] 1, [ERR] 2
```

---

### Example ID: 881

**Description:** Internal Test: Compares the behavior of `Maximum` and `GlobalMaximum` at different thresholds to validate their distinct scopes of invalidation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var FruitsXML =
"""

<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
</Fruits>

""";

var t = new uCalc.Transformer();
var fruitsTagRule = t.FromTo("<Fruits>", "List of fruits");
var fruitRule = t.FromTo("CommonName={@string:name}", "- {name}");

Console.WriteLine("--- Using Maximum (Rule-Level) ---");
fruitRule.Maximum = 3; // Rule fails if more than 3 fruits are found.
t.Filter(FruitsXML);
Console.WriteLine($"Match count when fruit rule fails: {t.Matches.Count()}"); // The 'fruitsTagRule' still matches.
Console.WriteLine(t.Matches.Text);

Console.WriteLine("");
Console.WriteLine("--- Using GlobalMaximum (Transformer-Level) ---");
fruitRule.Maximum = -1; // Reset local maximum
fruitRule.GlobalMaximum = 3; // Transformer fails if more than 3 fruits are found.
t.Filter(FruitsXML);
Console.WriteLine($"Match count when global rule fails: {t.Matches.Count()}"); // All matches are invalidated.
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
--- Using Maximum (Rule-Level) ---
Match count when fruit rule fails: 1
List of fruits

--- Using GlobalMaximum (Transformer-Level) ---
Match count when global rule fails: 0

```

---

### Example ID: 882

**Description:** Demonstrates the pass/fail behavior of GlobalMinimum. If the rule doesn't find at least 3 'a's, the entire transform fails.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");
var ruleB = t.FromTo("b", "B");
ruleA.GlobalMinimum = 3;

// Case 1: Fails (only 2 'a's)
Console.WriteLine("--- Case 1: Fails ---");
t.Text = "a b a b";
t.Transform();
Console.WriteLine($"Matches Found: {t.Matches.Count()}"); // Should be 0
Console.WriteLine($"Result: {t}");

// Case 2: Succeeds (3 'a's)
Console.WriteLine("");
Console.WriteLine("--- Case 2: Succeeds ---");
t.Text = "a b a b a";
t.Transform();
Console.WriteLine($"Matches Found: {t.Matches.Count()}"); // Should be 5 (3 'A's and 2 'B's)
Console.WriteLine($"Result: {t}");
```

**Output:**
```
--- Case 1: Fails ---
Matches Found: 0
Result: a b a b

--- Case 2: Succeeds ---
Matches Found: 5
Result: A B A B A
```

---

### Example ID: 885

**Description:** Toggling a rule on and off.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var r = t.FromTo("Hello", "Hi");

// Disable
r.Active = false;
Console.WriteLine(t.Transform("Hello").Text); // Output: Hello (No change)

// Enable
r.Active = true;
Console.WriteLine(t.Transform("Hello").Text); // Output: Hi
```

**Output:**
```
Hello
Hi
```

---

### Example ID: 886

**Description:** Simple arithmetic matching.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Match "Number + Number"
t.FromTo("{@Number} + {@Number}", "Math Operation");

Console.WriteLine(t.Transform("10 + 20")); // Output: Math Operation
Console.WriteLine(t.Transform("A + B"));   // No Match (A/B are Alpha, not Number)
```

**Output:**
```
Math Operation
A + B
```

---

### Example ID: 887

**Description:** Parsing Key-Value pairs where values can be numbers or strings.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Use {@Literal} to match either numbers or strings
t.FromTo("{@Alpha:key} = {@Literal:val}", "Set {key} to {val}");

Console.WriteLine(t.Transform("Timeout = 100"));      // Output: Set Timeout to 100
Console.WriteLine(t.Transform("Name = 'Admin'"));     // Output: Set Name to 'Admin'
```

**Output:**
```
Set Timeout to 100
Set Name to 'Admin'
```

---

### Example ID: 888

**Description:** Converting single-quoted strings to double-quoted ones by targeting the delimiters.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@sq}", """
"
""");

Console.WriteLine(t.Transform("print 'Hello'"));
```

**Output:**
```
print "Hello"
```

---

### Example ID: 889

**Description:** Replacing all horizontal whitespace with a visible underscore for debugging.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Whitespace}", "_");

Console.WriteLine(t.Transform("x = 10 + y"));
```

**Output:**
```
x_=_10_+_y
```

---

### Example ID: 894

**Description:** Demonstrating the difference between the `(0)` and `(1)` index.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Capture the string and show both versions in the replacement
t.FromTo("{@String:txt}", "With: {txt(0)}, Without: {txt(1)}, Default: {txt}");

Console.WriteLine(t.Transform("'uCalc'"));
```

**Output:**
```
With: 'uCalc', Without: uCalc, Default: uCalc
```

---

### Example ID: 895

**Description:** Converting quoted strings into XML-style elements by stripping the original quotes.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Use {s(1)} to get just the text inside the quotes
t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>");

string input = """
msg = "Welcome to uCalc!"
""";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
<message>Welcome to uCalc!</message>
```

---

### Example ID: 896

**Description:** (Real World: Sensitive Data Redaction) Masking the content of all string literals in a log or script, while preserving the non-string code structure.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Replace every string literal with a placeholder
t.FromTo("{@String}", """
"[REDACTED]"
""");

string log = """
UserLogin(id: 101, pass: 'secret123', name: "Admin")
""";
Console.WriteLine(t.Transform(log));
```

**Output:**
```
UserLogin(id: 101, pass: "[REDACTED]", name: "[REDACTED]")
```

---

### Example ID: 898

**Description:** Identifying any statement separator and replacing it with a standardized tag.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@StatementSeparator}", " [END_STMT]");

Console.WriteLine(t.Transform("x = 10; y = 20"));
```

**Output:**
```
x = 10 [END_STMT] y = 20
```

---

### Example ID: 900

**Description:** Internal Test (Configurability) Verifying that `{@StatementSeparator}` respects the engine's definition (e.g., checking if it correctly ignores a comma used as a parameter separator).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@StatementSeparator}", "STMT");

// Comma is not a StatementSeparator, so it should be ignored.
Console.WriteLine(t.Transform("func(a, b); next();"));
```

**Output:**
```
func(a, b)STMT next()STMT
```

---

### Example ID: 901

**Description:** (Real World: SQL-style Escaping) Doubling up single quotes to escape them for a SQL query.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@sq}", "''");

string input = "It's a trap";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
It''s a trap
```

---

### Example ID: 902

**Description:** (Mixed Delimiter Check) Verifying that `{@sq}` captures only single quotes (ignoring double quotes).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@sq}", "$");

// Only the single quote should be replaced
Console.WriteLine(t.Transform("""
"Hello" and 'World'
"""));
```

**Output:**
```
"Hello" and $World$
```

---

### Example ID: 903

**Description:** Identifying any operator sequence (single or multi-character) and labeling it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Reducible:op}", "[OP:{op}]");
Console.WriteLine(t.Transform("a + b <= c"));
```

**Output:**
```
a [OP:+] b [OP:<=] c
```

---

### Example ID: 906

**Description:** Identifying any quote character and replacing it with a visible tag.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@QuoteChar}", "[Q]");

Console.WriteLine(t.Transform("""
"Double" and 'Single'
"""));
```

**Output:**
```
[Q]Double[Q] and [Q]Single[Q]
```

---

### Example ID: 907

**Description:** (Real World: Quote Normalizer) Converting all string literals to use double quotes, regardless of whether they were originally single or double quoted.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Convert any quote character found to a double quote
t.FromTo("{@QuoteChar}", """
"
""");

string input = """
msg = 'Hello'; val = "World";
""";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
msg = "Hello"; val = "World";
```

---

### Example ID: 908

**Description:** (Non-delimiter characters) Verifying that `{@QuoteChar}` does not match characters that are not defined as string delimiters in the engine.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@QuoteChar}", "MATCH");

// Backticks (`) are usually not delimiters by default
Console.WriteLine(t.Transform("`Backtick`"));
```

**Output:**
```
`Backtick`
```

---

### Example ID: 909

**Description:** Identifying all numbers in an expression and wrapping them in a "Num" tag.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Number:n}", "Num({n})");

Console.WriteLine(t.Transform("price = 50 + 5.50"));
```

**Output:**
```
price = Num(50) + Num(5.50)
```

---

### Example ID: 910

**Description:** Verifying that `{@Number}` correctly ignores digits that are part of other tokens (like strings or identifiers).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Number}", "FOUND");

// The '2' in 'var2' and the '100' in the string should NOT match
Console.WriteLine(t.Transform("""
var2 = "count is 100" + 50
"""));
```

**Output:**
```
var2 = "count is 100" + FOUND
```

---

### Example ID: 911

**Description:** Replacing all platform-specific newlines with a generic visible tag.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Newline}", "[BR]");

string input = "Line 1\nLine 2\r\nLine 3";

Console.WriteLine(t.Transform(input));
```

**Output:**
```
Line 1[BR]Line 2[BR]Line 3
```

---

### Example ID: 912

**Description:** Identifying and removing redundant empty lines (consecutive newlines).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Match two newlines in a row and replace with one
t.FromTo("{@nl} {@nl}", "{@nl}"); // {@nl} same as {@NewLine}

string text = "First\n\nSecond\n\nThird";

Console.WriteLine(t.Transform(text));
```

**Output:**
```
First
Second
Third
```

---

### Example ID: 914

**Description:** Identifying all literal values in an expression and tagging them.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Literal:val}", "VAL({val})");

Console.WriteLine(t.Transform("""
x = 10 + "abc"
"""));
```

**Output:**
```
x = VAL(10) + VAL("abc")
```

---

### Example ID: 915

**Description:** (Real World: Value Masking)

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Creating a "Clean View" of a log or configuration file by replacing all
// actual data values with a placeholder, leaving only the structural identifiers.
var t = new uCalc.Transformer();
// Replace every literal with a generic placeholder
t.FromTo("{@Literal}", "?");

string input = """
setting_a = 500; setting_b = "active";
""";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
setting_a = ?; setting_b = ?;
```

---

### Example ID: 920

**Description:** Replacing double quotes with single quotes.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@dq}", "'");

Console.WriteLine(t.Transform("""
print "Hello"
"""));
```

**Output:**
```
print 'Hello'
```

---

### Example ID: 921

**Description:** (Real World: Escaping Helper) Finding double quotes to manually insert an escape backslash before them.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@dq}", """
\"
""");

string input = """
He said "Hello"
""";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
He said \"Hello\"
```

---

### Example ID: 923

**Description:** (Default Matching) Identifying any brackets and normalizing them to a standard parentheses.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Bracket}", "(");
t.FromTo("{@CloseBracket}", ")");

Console.WriteLine(t.Transform("{a, b, c} f(x, y) [1, 2, 3];"));
```

**Output:**
```
(a, b, c) f(x, y) (1, 2, 3);
```

---

### Example ID: 929

**Description:** Normalizing mixed input by replacing any opening bracket style with a standard parenthesis.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Bracket}", "(");

Console.WriteLine(t.Transform("{ x + [ y ] }"));
```

**Output:**
```
( x + ( y ] }
```

---

### Example ID: 930

**Description:** (Real World: Structure Identification) Labeling the start of complex data structures in a mixed text stream.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Bracket}", "[START_SCOPE]");

string input = "func { data [ 1, 2 ] }";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
func [START_SCOPE] data [START_SCOPE] 1, 2 ] }
```

---

### Example ID: 931

**Description:** (Negative Match) Ensuring that `{@Bracket}` does not match common "bracket-like" characters that are not in its definition (like angle brackets).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Bracket}", "FOUND");

// Angle brackets are not included in {@Bracket} by default
Console.WriteLine(t.Transform("vector <int>"));
```

**Output:**
```
vector <int>
```

---

### Example ID: 937

**Description:** Basic distinction between a root rule and a child rule.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var rootRule = t.Pattern("root");
var localTransformer = rootRule.LocalTransformer;
var childRule = localTransformer.Pattern("child");

Console.WriteLine($"Is 'rootRule' a child? {rootRule.IsChildRule}");
Console.WriteLine($"Is 'childRule' a child? {childRule.IsChildRule}");
```

**Output:**
```
Is 'rootRule' a child? False
Is 'childRule' a child? True
```

---

### Example ID: 938

**Description:** Internal Test: Verifies that any rule not on the root transformer is considered a child, regardless of nesting depth.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var grandParentRule = t.Pattern("grandparent");

// Create a child
var parentTransformer = grandParentRule.LocalTransformer;
var parentRule = parentTransformer.Pattern("parent");

// Create a grandchild
var childTransformer = parentRule.LocalTransformer;
var childRule = childTransformer.Pattern("child");

Console.WriteLine($"Grandparent is child: {grandParentRule.IsChildRule}");
Console.WriteLine($"Parent is child: {parentRule.IsChildRule}");
Console.WriteLine($"Child (grandchild) is child: {childRule.IsChildRule}");
```

**Output:**
```
Grandparent is child: False
Parent is child: True
Child (grandchild) is child: True
```

---

### Example ID: 939

**Description:** A simple example showing how to extract a value from a nested configuration block.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "Config { setting = 123; }";

// 1. Define the parent rule to capture the content inside the braces.
var parentRule = t.Pattern("Config '{' {body} '}'").SetStatementSensitive(false);

// 2. Get the local transformer for the parent rule.
var local_t = parentRule.LocalTransformer;

// 3. Define a rule that operates ONLY on the text captured by '{body}'.
local_t.FromTo("setting = {val}", "Found Value: {val}");

// 4. Perform the transformation.
// The local rule will run on the text " setting = 123; ".
t.Transform();

Console.WriteLine(t.Text);
```

**Output:**
```
Config { Found Value: 123; }
```

---

### Example ID: 940

**Description:** A practical example of parsing a specific HTML section and applying transformations only to the elements within it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Note the change in section/div/h2
var t = uc.NewTransformer();

// The parent rule will find the <section> block and make its content available to a local transformer.
// StatementSensitive(false) is needed so the multiline content is captured.
var parentRule = t.Pattern("<section>{body}</section>");
parentRule.StatementSensitive = false;

// Get the local transformer for the <section> block.
var section_t = parentRule.LocalTransformer;

// These rules will ONLY run on the content inside the <section> tag.
section_t.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>");
section_t.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>");

var sourceHtml =
"""

<div>
  <h2>Article One</h2>
  <p>This is NOT in the section.</p>
</div>

<section>
  <div>
    <h2>Article Two</h2>
    <p>This one IS inside the section.</p>
  </div>
</section>

""";

t.Text = sourceHtml;
t.Transform();
Console.WriteLine(t.Text);
```

**Output:**
```
<div>
  <h2>Article One</h2>
  <p>This is NOT in the section.</p>
</div>

<section>
  <div>
    <h1>====> ARTICLE TWO <====</h1>
    <p>SELECTED: This one IS inside the section.</p>
  </div>
</section>
```

---

### Example ID: 941

**Description:** Internal Test: Verifies the filtering of nested matches using RootLevelOnly and InnermostOnly options.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.Text = txt;

// Parent rule matches the <p> tag. Its local transformer then extracts the 'id' attribute.
var parentRule = t.Pattern("<p {etc}>");
parentRule.LocalTransformer.FromTo("id={@string:id}", "{id}");
t.Filter();

Console.WriteLine("--- All Matches (Parent and Child) ---");
Console.WriteLine(t.GetMatches(MatchesOption.All).Text);
Console.WriteLine("");

Console.WriteLine("--- RootLevelOnly (Parent Matches) ---");
Console.WriteLine(t.GetMatches(MatchesOption.RootLevelOnly).Text);
Console.WriteLine("");

Console.WriteLine("--- InnermostOnly (Child Matches) ---");
Console.WriteLine(t.GetMatches(MatchesOption.InnermostOnly).Text);
```

**Output:**
```
--- All Matches (Parent and Child) ---
<p aa>
aa
<p bb>
bb
<p cc>
cc

--- RootLevelOnly (Parent Matches) ---
<p aa>
<p bb>
<p cc>

--- InnermostOnly (Child Matches) ---
aa
bb
cc
```

---

### Example ID: 945

**Description:** A basic demonstration of how the Maximum threshold invalidates a rule's matches.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");

// Case 1: Limit is 2, but 3 'a's are present. The rule is invalidated.
t.Transform("a b a c a");
ruleA.Maximum = 2;
Console.WriteLine("--- Maximum = 2 (Rule Fails) ---");
Console.Write("Result: ");
Console.WriteLine(t.Transform("a b a c a"));

// Case 2: Limit is 3. The rule passes and matches are kept.
ruleA.Maximum = 3;
Console.WriteLine("");
Console.WriteLine("--- Maximum = 3 (Rule Succeeds) ---");
Console.Write("Result: ");
Console.WriteLine(t.Transform("a b a c a"));
```

**Output:**
```
--- Maximum = 2 (Rule Fails) ---
Result: a b a c a

--- Maximum = 3 (Rule Succeeds) ---
Result: A b A c A
```

---

### Example ID: 946

**Description:** Practical: Validating log file entries. If more than 2 'WARNING' entries exist, they are ignored, but 'ERROR' entries are still processed.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var log = "WARNING: low disk. ERROR: service down. WARNING: high CPU. WARNING: queue full.";

var warningRule = t.FromTo("WARNING: {msg}.", "[WARN] {msg}.");
var errorRule = t.FromTo("ERROR: {msg}.", "[ERR] {msg}.");

// Set a rule-specific limit for warnings.
warningRule.Maximum = 2;

t.Filter(log);
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
[ERR] service down.
```

---

### Example ID: 947

**Description:** Internal Test: Compares the behavior of Maximum (rule-level) and GlobalMaximum (transformer-level) invalidation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var FruitsXML =
"""

<Fruits>
  <Fruit CommonName='Apple' />
  <Fruit CommonName='Banana' />
  <Fruit CommonName='Orange' />
  <Fruit CommonName='Grapes' />
</Fruits>

""";

var t = new uCalc.Transformer();
var fruitsTagRule = t.FromTo("<Fruits>", "List of fruits");
var fruitRule = t.FromTo("CommonName={@string:name}", "- {name}");

Console.WriteLine("--- Using Maximum (Rule-Level Invalidation) ---");
// The fruitRule will fail because there are 4 fruits, exceeding the max of 3.
fruitRule.Maximum = 3;
t.Filter(FruitsXML);
Console.WriteLine($"Match count: {t.Matches.Count()}"); // The 'fruitsTagRule' still matches and is counted.
Console.WriteLine(t.Matches.Text);

Console.WriteLine("");
Console.WriteLine("--- Using GlobalMaximum (Transformer-Level Invalidation) ---");
fruitRule.Maximum = -1; // Reset local maximum to default (unlimited).
fruitRule.GlobalMaximum = 3; // The entire transformer will fail if more than 3 fruits are found.
t.Filter(FruitsXML);
Console.WriteLine($"Match count: {t.Matches.Count()}"); // All matches (including fruitsTagRule) are invalidated.
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
--- Using Maximum (Rule-Level Invalidation) ---
Match count: 1
List of fruits

--- Using GlobalMaximum (Transformer-Level Invalidation) ---
Match count: 0

```

---

### Example ID: 948

**Description:** How a rule fails if it doesn't meet the minimum match count.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");
ruleA.Minimum = 3;

Console.WriteLine("--- Case 1: Fails (only 2 'a's) ---");
t.Transform("a b a b c");
Console.WriteLine($"Result: {t}");
Console.WriteLine($"Matches Found: {t.Matches.Count()}");

Console.WriteLine("");
Console.WriteLine("--- Case 2: Succeeds (3 'a's) ---");
t.Transform("a b a b a c");
Console.WriteLine($"Result: {t}");
Console.WriteLine($"Matches Found: {t.Matches.Count()}");
```

**Output:**
```
--- Case 1: Fails (only 2 'a's) ---
Result: a b a b c
Matches Found: 0

--- Case 2: Succeeds (3 'a's) ---
Result: A b A b A c
Matches Found: 3
```

---

### Example ID: 949

**Description:** A practical example where a 'data' rule is invalidated if it appears too few times, while a 'header' rule is unaffected.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var document = """

Header: Section 1
Data: A
Data: B
Header: Section 2
Data: C

""";
t.Text = document;

var dataRule = t.Pattern("Data: {val}");
var headerRule = t.Pattern("Header: {val}");

dataRule.Minimum = 2;
Console.WriteLine("--- Find with Minimum(2) ---");
t.Find();
Console.WriteLine($"Total Matches: {t.Matches.Count()}");
Console.WriteLine($"Data Matches: {dataRule.Matches.Count()}");
Console.WriteLine($"Header Matches: {headerRule.Matches.Count()}");

dataRule.Minimum = 4;
Console.WriteLine("");
Console.WriteLine("--- Find with Minimum(4) ---");
t.Find();
Console.WriteLine($"Total Matches: {t.Matches.Count()}");
Console.WriteLine($"Data Matches: {dataRule.Matches.Count()}");
Console.WriteLine($"Header Matches: {headerRule.Matches.Count()}");
```

**Output:**
```
--- Find with Minimum(2) ---
Total Matches: 5
Data Matches: 3
Header Matches: 2

--- Find with Minimum(4) ---
Total Matches: 2
Data Matches: 0
Header Matches: 2
```

---

### Example ID: 950

**Description:** Internal Test: Clearly contrasts the rule-level invalidation of `Minimum` with the transformer-level invalidation of `GlobalMinimum`.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var FruitsXML =
"""

<Fruits>
  <Fruit CommonName='Apple' />
  <Fruit CommonName='Banana' />
  <Fruit CommonName='Orange' />
</Fruits>

""";

var t = new uCalc.Transformer();
t.Text = FruitsXML;
var fruitsTagRule = t.Pattern("<Fruits>");
var fruitRule = t.Pattern("CommonName={@string:name}");

Console.WriteLine("--- Using Minimum (Rule-Level Invalidation) ---");
fruitRule.Minimum = 4; // Rule fails if fewer than 4 fruits are found.
t.Find();
Console.WriteLine($"Match count when fruit rule fails: {t.Matches.Count()}");
Console.WriteLine("Matches found:");
foreach(var m in t.Matches) {
   Console.WriteLine($"  {m.Text}");
};

Console.WriteLine("");
Console.WriteLine("--- Using GlobalMinimum (Transformer-Level Invalidation) ---");
fruitRule.Minimum = 0; // Reset local minimum
fruitRule.GlobalMinimum = 4; // Transformer fails if fewer than 4 fruits are found.
t.Find();
Console.WriteLine($"Match count when global rule fails: {t.Matches.Count()}");
Console.WriteLine("Matches found:");
foreach(var m in t.Matches) {
   Console.WriteLine($"  {m.Text}");
};
```

**Output:**
```
--- Using Minimum (Rule-Level Invalidation) ---
Match count when fruit rule fails: 1
Matches found:
  <Fruits>

--- Using GlobalMinimum (Transformer-Level Invalidation) ---
Match count when global rule fails: 0
Matches found:
```

---

### Example ID: 951

**Description:** A simple demonstration of how a rule's name is derived from the first token in its pattern.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

var rule1 = t.FromTo("Hello {name}", "Hi {name}");
var rule2 = t.Pattern("<h1>{title}</h1>");

Console.WriteLine($"Rule 1 Name: '{rule1.Name}'");
Console.WriteLine($"Rule 2 Name: '{rule2.Name}'");
```

**Output:**
```
Rule 1 Name: 'hello'
Rule 2 Name: '<'
```

---

### Example ID: 952

**Description:** A practical example showing how to iterate through all matches and print the name of the rule that generated each one for debugging.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "Log: INFO, Data: 123, Log: WARN";

// Define two rules with different starting anchors
t.Pattern("Log: {@Alpha}");
t.Pattern("Data: {@Number}");
t.Find();

Console.WriteLine("--- Match Analysis ---");
foreach(var match in t.Matches) {
   Console.WriteLine($"Match '{match.Text}' was found by rule '{match.Rule.Name}'");
}
```

**Output:**
```
--- Match Analysis ---
Match 'Log: INFO' was found by rule 'log'
Match 'Data: 123' was found by rule 'data'
Match 'Log: WARN' was found by rule 'log'
```

---

### Example ID: 954

**Description:** Demonstrates the basic LIFO (Last-In, First-Out) behavior of NextOverload with two simple rules.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "This is a test.";

// Rule 1 (defined first, lower priority)
var rule1 = t.FromTo("is", "[IS_1]");

// Rule 2 (defined second, higher priority)
var rule2 = t.FromTo("is", "[IS_2]");

Console.WriteLine("--- Applying transform (Rule 2 has precedence) ---");
Console.WriteLine(t.Transform());
Console.WriteLine("");

Console.WriteLine("--- Using NextOverload ---");
// Get the rule that comes after rule2
var nextRule = rule2.NextOverload();

Console.WriteLine($"Rule 2 pattern: {rule2.Pattern}");
Console.WriteLine($"Next rule's pattern: {nextRule.Pattern}");

// Verify that the next rule is indeed rule1
Console.WriteLine($"Next rule is rule1: {nextRule.Handle() == rule1.Handle()}");
```

**Output:**
```
--- Applying transform (Rule 2 has precedence) ---
This [IS_2] a test.

--- Using NextOverload ---
Rule 2 pattern: is
Next rule's pattern: is
Next rule is rule1: True
```

---

### Example ID: 955

**Description:** Iterates through a chain of rules with the same anchor to inspect their different replacement patterns.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// Define multiple rules with the same anchor ("Log:")
t.FromTo("Log: {msg}", "DEFAULT: {msg}");
t.FromTo("Log: ERROR {msg}", "CRITICAL: {msg}");
var lastRule = t.FromTo("Log: INFO {msg}", "INFO: {msg}"); // This has the highest priority

Console.WriteLine("--- Overload Chain for 'Log:' anchor ---");
var currentRule = lastRule;
do {
   Console.WriteLine($"Pattern: '{currentRule.Pattern}' -> Replacement: '{currentRule.Replacement}'");
   currentRule = currentRule.NextOverload();
} while (currentRule.NotEmpty());
```

**Output:**
```
--- Overload Chain for 'Log:' anchor ---
Pattern: 'Log: INFO {msg}' -> Replacement: 'INFO: {msg}'
Pattern: 'Log: ERROR {msg}' -> Replacement: 'CRITICAL: {msg}'
Pattern: 'Log: {msg}' -> Replacement: 'DEFAULT: {msg}'
```

---

### Example ID: 956

**Description:** Internal Test: Verifies precedence and traversal of rules with different patterns but the same starting anchor ('Testing').

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "Testing (a b c) Testing x y z! Testing 1 2 3.";

var Pattern1 = t.Pattern("Testing {etc}.").SetTag(111);
var Pattern2 = t.Pattern("Testing {etc}!").SetTag(222);
var Pattern3 = t.Pattern("Testing ({etc})").SetTag(333);

t.Find();
Console.WriteLine("--- Matches ---");
Console.WriteLine(t.Matches.Text);
Console.WriteLine("--- Patterns ---");
Console.WriteLine(Pattern1.Pattern);
Console.WriteLine(Pattern2.Pattern);
Console.WriteLine(Pattern3.Pattern);
Console.WriteLine("---- Tags ----");
Console.WriteLine(Pattern1.Tag);
Console.WriteLine(Pattern2.Tag);
Console.WriteLine(Pattern3.Tag);
Console.WriteLine("-- Overload Tags --");
// Note that most recently defined patterns come first
Console.WriteLine(Pattern3.NextOverload().Tag);
Console.WriteLine(Pattern2.NextOverload().Tag);
Console.WriteLine(Pattern1.NextOverload().Tag);
```

**Output:**
```
--- Matches ---
Testing (a b c)
Testing x y z!
Testing 1 2 3.
--- Patterns ---
Testing {etc}.
Testing {etc}!
Testing ({etc})
---- Tags ----
111
222
333
-- Overload Tags --
222
111
0
```

---

### Example ID: 960

**Description:** Verifies the direct parent-child relationship between a Transformer and its Rule.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var myRule = t.FromTo("A", "B");

// Get the parent from the rule
var parent = myRule.ParentTransformer;

// Check if the parent is the original transformer using its unique memory index
Console.WriteLine(parent.MemoryIndex == t.MemoryIndex);
```

**Output:**
```
True
```

---

### Example ID: 961

**Description:** Iterates through matches, retrieves the rule for each, and uses ParentTransformer to get the transformer's description for context.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Description = "My Main Transformer";
t.Text = "apple banana apple";

var appleRule = t.FromTo("apple", "APPLE");
var bananaRule = t.FromTo("banana", "BANANA");

t.Find();

foreach(var match in t.Matches) {
   var rule = match.Rule;
   var parent = rule.ParentTransformer;
   Console.WriteLine($"Match '{match.Text}' found by rule '{rule.Name}' in transformer '{parent.Description}'");
}
```

**Output:**
```
Match 'apple' found by rule 'apple' in transformer 'My Main Transformer'
Match 'banana' found by rule 'banana' in transformer 'My Main Transformer'
Match 'apple' found by rule 'apple' in transformer 'My Main Transformer'
```

---

### Example ID: 962

**Description:** Internal Test: Verifies that the correct parent is returned when using a nested LocalTransformer, confirming hierarchical integrity.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var main_t = new uCalc.Transformer();
main_t.Description = "Main Transformer";

// Create an outer rule in the main transformer
var outerRule = main_t.Pattern("OUTER({body})");

// Get a local transformer for the outer rule
var local_t = outerRule.LocalTransformer;
local_t.Description = "Local Transformer";

// Create an inner rule inside the local transformer
var innerRule = local_t.FromTo("INNER", "inner_match");

// Verify the parent of the outer rule is the main transformer
Console.WriteLine($"Outer rule's parent: {outerRule.ParentTransformer.Description}");

// Verify the parent of the inner rule is the local transformer
Console.WriteLine($"Inner rule's parent: {innerRule.ParentTransformer.Description}");
```

**Output:**
```
Outer rule's parent: Main Transformer
Inner rule's parent: Local Transformer
```

---

### Example ID: 963

**Description:** How to retrieve the pattern string from a defined rule.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var rule = t.FromTo("Hello {name}", "Greetings, {name}!");

Console.WriteLine($"Rule pattern is: '{rule.Pattern}'");
```

**Output:**
```
Rule pattern is: 'Hello {name}'
```

---

### Example ID: 964

**Description:** A practical debugging example that identifies which pattern string generated each match.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "An apple and a car.";

// Define two separate rules
t.FromTo("apple", "[FRUIT]");
t.FromTo("car", "[VEHICLE]");

t.Find();

var matches = t.Matches;
Console.WriteLine($"Found {matches.Count()} matches:");
foreach(var match in matches) {
   var rule = match.Rule;
   Console.WriteLine($"- Matched '{match.Text}' using pattern: '{rule.Pattern}'");
}
```

**Output:**
```
Found 2 matches:
- Matched 'apple' using pattern: 'apple'
- Matched 'car' using pattern: 'car'
```

---

### Example ID: 965

**Description:** Internal Test: Verifies that the correct pattern string is returned for rules created with both FromTo() and Pattern(), including complex syntax.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Rule created with FromTo
var rule1 = t.FromTo("Key: {@Number:val}", "{val}");

// Rule created with Pattern
var rule2 = t.Pattern("<{tag}>{content}</{tag}>");

Console.WriteLine($"Rule 1 Pattern: {rule1.Pattern}");
Console.WriteLine($"Rule 2 Pattern: {rule2.Pattern}");
```

**Output:**
```
Rule 1 Pattern: Key: {@Number:val}
Rule 2 Pattern: <{tag}>{content}</{tag}>
```

---

### Example ID: 970

**Description:** Demonstrates the default `QuoteSensitive(true)` behavior, where a pattern match is ignored inside a string literal.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("fox", "CAT");

// The 'fox' inside the quotes is not replaced.
Console.WriteLine(t.Transform("The quick brown fox jumps over the 'lazy fox'."));
```

**Output:**
```
The quick brown CAT jumps over the 'lazy fox'.
```

---

### Example ID: 971

**Description:** Practical: Creates a custom code block parser. `@QuoteSensitive(false)` is essential to allow the capture of content that contains its own quotes.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var source = """
Some text... [code]print("Hello, World!") // Quoted with "
var x = 'test';[/code] ...more text.
""";

// This rule must disable QuoteSensitive and StatementSensitive to correctly
// capture the multi-line block containing single and double quotes.
var rule = t.FromTo("'['code']'{content}'['/code']'", """
```
{content}
```
""");
rule.QuoteSensitive = false;
rule.StatementSensitive = false;

Console.WriteLine(t.Transform(source));
```

**Output:**
```
Some text... ```
print("Hello, World!") // Quoted with "
var x = 'test';
``` ...more text.
```

---

### Example ID: 975

**Description:** Internal Test: Verifies that releasing a rule correctly 'un-shadows' a previously defined rule with the same pattern.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "The quick brown fox.";

// 1. Define the original rule
var ruleV1 = t.FromTo("brown", "BROWN_V1");
Console.WriteLine($"Initial transform: {t.Transform()}");

// 2. Define a new rule with the same pattern, shadowing the original
t.Text = "The quick brown fox.";
var ruleV2 = t.FromTo("brown", "BROWN_V2");
Console.WriteLine($"After shadowing: {t.Transform()}");

// 3. Release the new rule. The original rule should become active again.
t.Text = "The quick brown fox.";
ruleV2.Release();
Console.WriteLine($"After release (reverted): {t.Transform()}");
```

**Output:**
```
Initial transform: The quick BROWN_V1 fox.
After shadowing: The quick BROWN_V2 fox.
After release (reverted): The quick BROWN_V1 fox.
```

---

### Example ID: 979

**Description:** The cascading effect of enabling `RewindOnChange`.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Rule 1: Replace 'A' with 'B'. Rewind is off by default.
t.FromTo("A", "B");
// Rule 2: Replace 'B' with 'C'.
t.FromTo("B", "C");

Console.WriteLine("--- Rewind Disabled ---");
// The 'A' becomes 'B', but the scan continues *after* the 'B', so rule 2 is not triggered.
Console.WriteLine(t.Transform("Start A End"));
t.Reset();

// Now, enable rewind on the first rule.
t.FromTo("A", "B").RewindOnChange = true;
t.FromTo("B", "C");

Console.WriteLine("");
Console.WriteLine("--- Rewind Enabled ---");
// The 'A' becomes 'B', rewind occurs, the 'B' is re-scanned and becomes 'C'.
Console.WriteLine(t.Transform("Start A End"));
```

**Output:**
```
--- Rewind Disabled ---
Start B End

--- Rewind Enabled ---
Start C End
```

---

### Example ID: 980

**Description:** Demonstrates using `RewindOnChange` to create a recursive `AddUp` function within the expression transformer.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.ExpressionTransformer;  // Transformer used for Eval() and Evaluate()

var p1 = t.FromTo("AddUp({x})", "{x}"); // Base case
var p2 = t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").SetRewindOnChange(true); // Recursive step

Console.WriteLine($"p1 RewindOnChange: {p1.RewindOnChange}");
Console.WriteLine($"p2 RewindOnChange: {p2.RewindOnChange}");

Console.WriteLine("");
Console.WriteLine($"Input: AddUp(1,2,3,4)");
Console.WriteLine($"Transform: {t.Transform("AddUp(1,2,3,4)")}");
Console.WriteLine($"Eval: {uc.Eval("AddUp(1,2,3,4)")}");
```

**Output:**
```
p1 RewindOnChange: False
p2 RewindOnChange: True

Input: AddUp(1,2,3,4)
Transform: (1 + (2 + (3 + 4)))
Eval: 10
```

---

### Example ID: 981

**Description:** Applies `RewindOnChange` to a default rule set to enable complex, multi-rule transformations for a custom `Average` function.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.ExpressionTransformer;

// Enable rewind for all subsequent rules in this transformer.
t.DefaultRuleSet.SetRewindOnChange(true);

// Define the recursive rules.
t.FromTo("AddUp({x})", "{x}");
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

t.FromTo("ArgCount({x})", "1");
t.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

// The main rule that combines the others.
t.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var expression = "Average(1, 2, 3, 4)";
Console.WriteLine($"Input: {expression}");
Console.WriteLine($"Transform: {t.Transform(expression)}");
Console.WriteLine($"Eval: {uc.Eval(expression)}");
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

### Example ID: 985

**Description:** Finding all occurrences of a letter except for the first one.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "a b c a d e a f g";
var ruleA = t.FromTo("a", "[MATCH]");

// Skip the first 'a' that is found
ruleA.StartAfter = 1;

Console.WriteLine(t.Transform());
```

**Output:**
```
a b c [MATCH] d e [MATCH] f g
```

---

### Example ID: 986

**Description:** A practical example that processes a list of tasks but skips the first two high-priority items.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var taskList = "Task:1 Task:2 Task:3 Task:4 Task:5";
t.Text = taskList;

var taskRule = t.FromTo("Task:{@Number:id}", "Processed Task {id}");

// Skip the first two tasks in the list
taskRule.StartAfter = 2;

Console.WriteLine(t.Transform());
```

**Output:**
```
Task:1 Task:2 Processed Task 3 Processed Task 4 Processed Task 5
```

---

### Example ID: 988

**Description:** Demonstrates the difference in variable capture behavior when StatementSensitive is enabled versus disabled.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
string txt = "start one; two end";

// Default behavior is StatementSensitive(true), so {body} stops at the semicolon
// and the 'end' anchor is never found. The transform fails.
var rule = t.FromTo("start {body} end", "[{body}]");
Console.WriteLine($"Sensitive (default): {t.Transform(txt)}");

rule.StatementSensitive = false;
// With StatementSensitive(false), {body} captures across the semicolon.
Console.WriteLine($"Insensitive: {t.Transform(txt)}");
```

**Output:**
```
Sensitive (default): start one; two end
Insensitive: [one; two]
```

---

### Example ID: 989

**Description:** Practical: Shows how disabling statement sensitivity is essential for parsing multi-line HTML/XML blocks.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var source = """
<data>
  content spans
  multiple lines
</data>
""";

// This rule must disable StatementSensitive to capture the multi-line body,
// otherwise the first newline would terminate the {body} variable.
var rule = t.FromTo("<data>{body}</data>", "Body: [{body}]");
rule.StatementSensitive = false;

Console.WriteLine(t.Transform(source));
```

**Output:**
```
Body: [
  content spans
  multiple lines
]
```

---

### Example ID: 991

**Description:** Finds and transforms only the first three occurrences of a pattern, ignoring any subsequent ones.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "a b c a d e a f g a h i";
var ruleA = t.FromTo("a", "[A]");

// Only find and transform the first 3 occurrences of 'a'.
ruleA.StopAfter = 3;

Console.WriteLine(t.Transform());
```

**Output:**
```
[A] b c [A] d e [A] f g a h i
```

---

### Example ID: 992

**Description:** Processes a log file but stops after finding the first error message to focus on the initial problem.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var logText = "ERROR: Fail 1. INFO: OK. ERROR: Fail 2. ERROR: Fail 3.";
t.Text = logText;

var errorRule = t.Pattern("ERROR: {msg}.");
// Stop after finding the first error to focus on the initial problem.
errorRule.StopAfter = 1;
t.Find();

Console.WriteLine($"First error found: {t.Matches.Text}");
```

**Output:**
```
First error found: ERROR: Fail 1.
```

---

### Example ID: 993

**Description:** Internal Test: Combines `@StartAfter` and `@StopAfter` to retrieve a specific 'page' of results (matches 3 through 7).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "1 2 3 4 5 6 7 8 9 10 11 12";
var rule = t.Pattern("{@Number}");

// Get a "page" of results: matches 3 through 7.
// The engine will stop finding numbers after the 7th match is found.
// Then, it will skip the first 2 matches from that set.
rule.StartAfter = 2; // Skip first 2
rule.StopAfter = 7;  // Find up to 7

t.Find();

Console.WriteLine("Matches found:");
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
Matches found:
3
4
5
6
7
```

---

### Example ID: 994

**Description:** How to set and get tags for different rules.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var ruleA = t.Pattern("A").SetTag(10);
var ruleB = t.Pattern("B").SetTag(20);

Console.WriteLine($"Tag for Rule A: {ruleA.Tag}");
Console.WriteLine($"Tag for Rule B: {ruleB.Tag}");
```

**Output:**
```
Tag for Rule A: 10
Tag for Rule B: 20
```

---

### Example ID: 995

**Description:** A practical example using tags to build a simple syntax highlighter that categorizes matches.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Practical: Basic Syntax Highlighter
var t = new uCalc.Transformer();

// Define categories with integer tags
var TAG_KEYWORD = 1;
var TAG_STRING = 2;
var TAG_COMMENT = 3;

// Define rules and tag them
t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
t.Pattern("{@String}").SetTag(TAG_STRING);
t.Pattern("// {text}").SetTag(TAG_COMMENT);

t.Text = """
for (i=0; i<10; i++) { s = "hello"; // comment }
""";
t.Find();

foreach(var match in t.Matches) {
   var tag = match.Rule.Tag;
   if (tag == TAG_KEYWORD) {
      Console.WriteLine($"TAG_KEYWORD: {match.Text}");
   } else if (tag == TAG_STRING) {
      Console.WriteLine($"TAG_STRING: {match.Text}");
   } else if (tag == TAG_COMMENT) {
      Console.WriteLine($"TAG_COMMENT: {match.Text}");
   }
}
```

**Output:**
```
TAG_KEYWORD: for
TAG_STRING: "hello"
TAG_COMMENT: // comment 
```

---

### Example ID: 996

**Description:** Internal Test: Verifies rule precedence and tag retrieval by traversing the overload chain with NextOverload.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Internal Test: Verifies precedence and tag retrieval via NextOverload
var t = new uCalc.Transformer();
t.Text = "Testing (a b c) Testing x y z! Testing 1 2 3.";

// Rules defined last have higher precedence for the same anchor ("Testing")
var p1 = t.Pattern("Testing {etc}.").SetTag(111);
var p2 = t.Pattern("Testing {etc}!").SetTag(222);
var p3 = t.Pattern("Testing ({etc})").SetTag(333);

// Get the highest precedence rule via Pattern's return value
var highestPriorityRule = p3;
Console.WriteLine($"Highest priority rule tag: {highestPriorityRule.Tag}");

// Walk the overload chain
var midPriorityRule = highestPriorityRule.NextOverload();
Console.WriteLine($"Mid priority rule tag: {midPriorityRule.Tag}");

var lowPriorityRule = midPriorityRule.NextOverload();
Console.WriteLine($"Low priority rule tag: {lowPriorityRule.Tag}");

// The end of the chain should have a tag of 0 (default)
var endOfChain = lowPriorityRule.NextOverload();
Console.WriteLine($"End of chain tag: {endOfChain.Tag}");
```

**Output:**
```
Highest priority rule tag: 333
Mid priority rule tag: 222
Low priority rule tag: 111
End of chain tag: 0
```

---

### Example ID: 997

**Description:** How to retrieve a rule's parent uCalc instance and verify its identity.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var myRule = t.FromTo("A", "B");

// Get the parent uCalc from the rule
var parent_uc = myRule.uCalc;

// Verify they are the same instance using their MemoryIndex
Console.WriteLine(parent_uc.MemoryIndex == uc.MemoryIndex);
```

**Output:**
```
True
```

---

### Example ID: 998

**Description:** A practical example that uses a rule's parent context to define and evaluate an expression.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// The transformer 't' belongs to the main 'uc' instance.
var t = new uCalc.Transformer(uc);

// Define a variable in the transformer's parent context.
t.uCalc.DefineVariable("VarX = 123");

// This rule is created within 't' and will need to access VarX.
var myRule = t.FromTo("x", "{@Eval: VarX}");

// Get the rule's parent uCalc instance...
var parent_uc = myRule.uCalc;

// ...and use it to evaluate an expression to prove we have the right context.
Console.WriteLine($"Value of VarX in parent context: {parent_uc.Eval("VarX")}");

// Now, run the transformation. The {@Eval} in the rule
// correctly finds 'VarX' in its parent uCalc context.
Console.WriteLine(t.Transform("The value is: x"));
```

**Output:**
```
Value of VarX in parent context: 123
The value is: 123
```

---

### Example ID: 999

**Description:** Internal Test: Verifies that a rule defined in a nested LocalTransformer correctly resolves its parent to the root uCalc instance.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var root_uc = new uCalc();
root_uc.Description = "Root uCalc Instance";

var main_t = new uCalc.Transformer(root_uc);

// Create a rule in the main transformer
var outerRule = main_t.Pattern("OUTER({body})");

// Get a local transformer for the outer rule
var local_t = outerRule.LocalTransformer;
local_t.Description = "Local Transformer";

// Create an inner rule inside the local transformer
var innerRule = local_t.FromTo("INNER", "inner_match");

// Verify both rules resolve to the same root uCalc instance
var outerParent = outerRule.uCalc;
var innerParent = innerRule.uCalc;

Console.WriteLine($"Outer rule's parent: {outerParent.Description}");
Console.WriteLine($"Inner rule's parent: {innerParent.Description}");
Console.WriteLine($"Both rules share the same root uCalc instance: {outerParent.Handle() == innerParent.Handle()}");
```

**Output:**
```
Outer rule's parent: Root uCalc Instance
Inner rule's parent: Root uCalc Instance
Both rules share the same root uCalc instance: True
```

---

### Example ID: 1003

**Description:** A simple demonstration of defining a token in one transformer and reusing it in another.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t1 = new uCalc.Transformer();
var t2 = new uCalc.Transformer();

// Define a custom token in the first transformer
var customToken = t1.Tokens.Add("###", TokenType.Generic);

// Import the token definition into the second transformer
t2.Tokens.Add(customToken);
t2.FromTo("###", "MATCH");

Console.WriteLine($"t2 can now find '###': {t2.Transform("Test ### Test")}");
```

**Output:**
```
t2 can now find '###': Test MATCH Test
```

---

### Example ID: 1004

**Description:** Shows how importing a comment token definition can prevent find-and-replace rules from incorrectly modifying text inside comments.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create a transformer with a custom comment token definition
var t_source = new uCalc.Transformer();
var commentToken = t_source.Tokens.Add("""
/\*([\s\S]*?)\*/
""", TokenType.Whitespace);
commentToken.Description = "C-style block comment";

// Create a second transformer that will do replacements
var t_replacer = new uCalc.Transformer();
t_replacer.FromTo("secret", "REDACTED");

var sourceText = "a secret /* contains another secret */ value";

Console.WriteLine("--- Before Importing Comment Token ---");
// Without knowing about comments, t_replacer incorrectly modifies the text inside the comment.
Console.WriteLine(t_replacer.Transform(sourceText));
Console.WriteLine("");

Console.WriteLine("--- After Importing Comment Token ---");
// Import the comment token definition. Now, the comment block is treated as a single whitespace token.
t_replacer.Tokens.Add(commentToken);
// The transformer must be reset with the original text for the new token to apply.
t_replacer.Text = sourceText;
Console.WriteLine(t_replacer.Transform());
```

**Output:**
```
--- Before Importing Comment Token ---
a REDACTED /* contains another REDACTED */ value

--- After Importing Comment Token ---
a REDACTED /* contains another secret */ value
```

---

### Example ID: 1006

**Description:** Defines a C-style line comment token (`//...`) and categorizes it as whitespace so it is ignored by the parser.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// By default, a comment would cause a syntax error.
Console.Write("Before: ");
Console.WriteLine(uc.EvalStr("10 + 5 // Add 5"));

// Add a new token definition for C-style comments.
// The regex `//.*` matches from '//' to the end of the line.
// We classify it as Whitespace so the parser skips it.
uc.ExpressionTokens.Add("//.*", TokenType.Whitespace);

Console.Write("After:  ");
Console.WriteLine(uc.EvalStr("10 + 5 // Add 5"));
```

**Output:**
```
Before: Undefined identifier
After:  15
```

---

### Example ID: 1008

**Description:** Internal Test: Verifies that the `subMatchGroup` parameter correctly extracts a capture group's content and that `ItemIs::QuotedText` works as expected.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Define a custom string literal using pipe characters `|...|`.
// The regex `\|([^\|]*)\|` captures the inner content in group 1.
// We set `subMatchGroup` to 1 to use this group as the token's value.
var pipeStringToken = t.Tokens.Add("""
\|([^\|]*)\|
""", TokenType.Literal, "", 1);

// Complete the definition by setting the data type and QuotedText property.
pipeStringToken.DataType = uc.DataTypeOf("String");
pipeStringToken.IsProperty(ItemIs.QuotedText, true);

// Define a simple rule to prove the token works.
t.FromTo("Test: {@String:s}", "Found: {s(0)} | Content: {s(1)}");

// The transformer now recognizes |...| as a string literal.
Console.WriteLine(t.Transform("Test: |hello|"));
```

**Output:**
```
Found: |hello| | Content: hello
```

---

### Example ID: 1009

**Description:** How to define a custom token in one transformer and reuse it in another.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create a source transformer and define a custom token.
var t_source = new uCalc.Transformer();
var customToken = t_source.Tokens.Add("###", TokenType.Generic);

// Create a destination transformer.
var t_dest = new uCalc.Transformer();

// Import all token definitions from the source.
t_dest.Tokens.Add(t_source.Tokens);
t_dest.FromTo("###", "MATCH");

Console.WriteLine($"t_dest can now find '###': {t_dest.Transform("Test ### Test")}");
```

**Output:**
```
t_dest can now find '###': Test MATCH Test
```

---

### Example ID: 1012

**Description:** Retrieves a built-in token by its name and inspects its regex pattern.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var tokens = uc.ExpressionTokens;
var alphaToken = tokens.ByName("_token_alphanumeric");
Console.WriteLine($"Alphanumeric Regex: {alphaToken.Regex}");
```

**Output:**
```
Alphanumeric Regex: [a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 1013

**Description:** Dynamically re-categorizes the newline token to treat it as whitespace, allowing a pattern to match across multiple lines.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var source = """
<data>
  content spans
  multiple lines
</data>
""";
t.FromTo("<data>{body}</data>", "Body: [{body}]");

Console.WriteLine("--- Before: Newline is a Separator ---");
Console.WriteLine(t.Transform(source));

// Use ByName to find the newline token and change its type.
t.Tokens.ByName("_token_newline", TokenType.Whitespace);

Console.WriteLine("");
Console.WriteLine("--- After: Newline is Whitespace ---");
Console.WriteLine(t.Transform(source));
```

**Output:**
```
--- Before: Newline is a Separator ---
<data>
  content spans
  multiple lines
</data>

--- After: Newline is Whitespace ---
Body: [content spans
  multiple lines]
```

---

### Example ID: 1018

**Description:** Retrieves the primary alphanumeric token definition using `ByType`.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var tokens = uc.ExpressionTokens;
var alphaToken = tokens.ByType(TokenType.AlphaNumeric);

Console.WriteLine($"Name: {alphaToken.Name}");
Console.WriteLine($"Regex: {alphaToken.Regex}");
```

**Output:**
```
Name: _token_alphanumeric
Regex: [a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 1019

**Description:** Practical: Iterates through all tokens categorized as 'Literal' to display their definitions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var tokens = uc.ExpressionTokens;
int i = 0;
var literalToken = new uCalc.Item();

Console.WriteLine("--- All Literal Tokens ---");
do {
   literalToken = tokens.ByType(TokenType.Literal, i);
   if (literalToken.NotEmpty()) {
      Console.WriteLine($"{i}: {literalToken.Name} - {literalToken.Regex}");
   }
   i = i + 1;
} while (literalToken.NotEmpty());
```

**Output:**
```
--- All Literal Tokens ---
0: _token_string_singlequoted - '([^']*(?:''[^']*)*)'
1: _token_string_doublequoted - "([^"]*(?:""[^"]*)*)"
2: _token_string_tripledoublequoted - """([\s\S]*?)"""
3: _token_floatnumber - [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
4: _token_imaginaryunit - #i
```

---

### Example ID: 1020

**Description:** Internal Test: Verifies that requesting an out-of-bounds index for a token type returns an empty item.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var tokens = uc.ExpressionTokens;

// There is only one Alphanumeric token, so index 1 is out of bounds.
var outOfBoundsToken = tokens.ByType(TokenType.AlphaNumeric, 1);

Console.WriteLine($"Is token empty? {outOfBoundsToken.IsEmpty()}");
Console.WriteLine($"Was token found? {! outOfBoundsToken.IsProperty(ItemIs.NotFound)}");
```

**Output:**
```
Is token empty? True
Was token found? False
```

---

### Example ID: 1021

**Description:** Demonstrates the basic functionality of clearing default tokens and adding a single new one.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.FromTo("is", "<IS>");

Console.WriteLine("--- With Default Tokens ---");
// By default, 'is' is a whole word (token)
Console.WriteLine(t.Transform("This is a test"));

// Clear all default token definitions
t.Tokens.Clear();

// Add a new, simple token that matches any single character
t.Tokens.Add(".");

Console.WriteLine("");
Console.WriteLine("--- After Clearing and Adding '.' Token ---");
// Now, 'i' and 's' are matched as separate characters
t.FromTo("is", "<IS>"); // The rule must be redefined
Console.WriteLine(t.Transform("This is a test"));
```

**Output:**
```
--- With Default Tokens ---
This <IS> a test

--- After Clearing and Adding '.' Token ---
Th<IS> <IS> a test
```

---

### Example ID: 1027

**Description:** Using a context switch to prevent transformations inside a designated `[RAW]` block.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
string text = "Replace config, but not the one inside [RAW]this config is raw[/RAW].";

// Create a token set for the raw block that only tokenizes single characters.
var rawTransformer = new uCalc.Transformer();
var rawTokens = rawTransformer.Tokens;
rawTokens.Clear();
rawTokens.Add("."); // Match any single character

// Switch to rawTokens when [RAW] is found, and switch back at [/RAW].
t.Tokens.ContextSwitch(rawTokens, """
\[RAW\]
""", """
\[/RAW\]
""");

t.FromTo("config", "SETTING");

Console.WriteLine(t.Transform(text));
```

**Output:**
```
Replace SETTING, but not the one inside [RAW]this config is raw[/RAW].
```

---

### Example ID: 1030

**Description:** How to get the count of default token definitions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var tokenCount = uc.ExpressionTokens.Count;
Console.WriteLine($"Default expression parser has {tokenCount} token definitions.");
```

**Output:**
```
Default expression parser has 30 token definitions.
```

---

### Example ID: 1031

**Description:** A practical example of iterating through all token definitions in a collection using Count as the loop boundary.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

var tokens = t.Tokens;
Console.WriteLine($"Total token definitions: {tokens.Count}");
Console.WriteLine("--- Token List ---");

var i = 0;

for ( i = 0; i <= tokens.Count - 1; i++) {
   var tokenItem = tokens.At(i);
   Console.WriteLine($"{i}: {tokenItem.Name}");
}
```

**Output:**
```
Total token definitions: 27
--- Token List ---
0: _token_line
1: _token_catchall
2: _token_catchall_utf8_other
3: _token_punctuation
4: _token_quotechar
5: _token_quotechar_single
6: _token_quotechar_double
7: _token_quotechar_tripledouble
8: _token_memberaccess
9: _token_variableargs
10: _token_reducible2
11: _token_parenthesis
12: _token_parenthesis_close
13: _token_curlybrace
14: _token_curlybrace_close
15: _token_squarebracket
16: _token_squarebracket_close
17: _token_argseparator
18: _token_newline
19: _token_semicolon
20: _token_string_singlequoted
21: _token_string_doublequoted
22: _token_string_tripledoublequoted
23: _token_whitespace
24: _token_reducible
25: _token_floatnumber
26: _token_alphanumeric
```

---

### Example ID: 1032

**Description:** Internal Test: Verifies that the count updates correctly after Add() and Clear() operations, demonstrating the dynamic nature of the collection.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var tokens = t.Tokens;

var initialCount = tokens.Count;
Console.WriteLine($"1. Initial count: {initialCount}");

// Add a new token
tokens.Add("custom_token");
Console.WriteLine($"2. Count after Add: {tokens.Count}");

// Clear all tokens
tokens.Clear();
Console.WriteLine($"3. Count after Clear: {tokens.Count}");

// Add one token back
tokens.Add(".");
Console.WriteLine($"4. Count after adding one back: {tokens.Count}");
```

**Output:**
```
1. Initial count: 27
2. Count after Add: 28
3. Count after Clear: 0
4. Count after adding one back: 1
```

---

### Example ID: 1033

**Description:** Demonstrates the basic getter and setter functionality of the Description property.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var tokens = t.Tokens;

// Set a description
tokens.Description = "Default token set for general purpose parsing.";

// Get the description
Console.WriteLine(tokens.Description);
```

**Output:**
```
Default token set for general purpose parsing.
```

---

### Example ID: 1034

**Description:** Uses descriptions to identify and differentiate between two separate token configurations at runtime.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create two transformers with different token configurations
var strict_t = new uCalc.Transformer();
strict_t.Tokens.Description = "Strict Mode: only 'is' as a whole word.";

var flexible_t = new uCalc.Transformer();
flexible_t.Tokens.Description = "Flexible Mode: matches 'is' inside other words.";
flexible_t.Tokens.Clear();
flexible_t.Tokens.Add("."); // Match by character

string text = "This island is nice.";

strict_t.FromTo("is", "[MATCH]");
flexible_t.FromTo("is", "[MATCH]");

Console.WriteLine(strict_t.Tokens.Description);
Console.WriteLine($"Result: {strict_t.Transform(text)}");
Console.WriteLine("");
Console.WriteLine(flexible_t.Tokens.Description);
Console.WriteLine($"Result: {flexible_t.Transform(text)}");
```

**Output:**
```
Strict Mode: only 'is' as a whole word.
Result: This island [MATCH] nice.

Flexible Mode: matches 'is' inside other words.
Result: Th[MATCH] [MATCH]land [MATCH] nice.
```

---

### Example ID: 1035

**Description:** Internal Test: Verifies that descriptions are copied when token sets are imported, but remain independent afterward.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t1 = new uCalc.Transformer();
t1.Tokens.Description = "Original Description";

// Create a new transformer and import tokens from t1
var t2 = new uCalc.Transformer();
t2.Tokens.Add(t1.Tokens);

Console.WriteLine($"t2's initial description (copied from t1): {t2.Tokens.Description}");

// Modify t2's description
t2.Tokens.Description = "Modified Description";

Console.WriteLine($"t2's new description: {t2.Tokens.Description}");
Console.WriteLine($"t1's description remains unchanged: {t1.Tokens.Description}");
```

**Output:**
```
t2's initial description (copied from t1): Original Description
t2's new description: Modified Description
t1's description remains unchanged: Original Description
```

---

### Example ID: 1036

**Description:** How adding tokens affects their index and, therefore, their precedence.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var tokens = t.Tokens;
tokens.Clear();
tokens.Add("."); // Add a fallback token at index 0

// The order of definition determines the index (precedence)
var tokenA = tokens.Add("A");
var tokenB = tokens.Add("B");

Console.WriteLine($"Index of A: {tokens.IndexOf(tokenA)}"); // Will have a lower index
Console.WriteLine($"Index of B: {tokens.IndexOf(tokenB)}"); // Will have a higher index, thus higher precedence
```

**Output:**
```
Index of A: 1
Index of B: 2
```

---

### Example ID: 1037

**Description:** Internal Test: Verifies the LIFO precedence order and the return value for a token not present in the collection.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var tokens = t.Tokens;
tokens.Clear();
tokens.Add("."); // Fallback

var tokenPlus = tokens.Add("[+]");
var tokenStar = tokens.Add("[*]");
var tokenCaret = tokens.Add("^");

// LIFO order means precedence is: '^' > '*' > '+'
Console.WriteLine("Precedence Check:");
Console.WriteLine($"Caret (^) > Star (*): {tokens.IndexOf(tokenCaret) > tokens.IndexOf(tokenStar)}");
Console.WriteLine($"Star (*) > Plus (+): {tokens.IndexOf(tokenStar) > tokens.IndexOf(tokenPlus)}");

// Test for a token not in this collection
var t2 = new uCalc.Transformer();
var unaddedToken = t2.Tokens.Add("unrelated");
Console.WriteLine($"Index of un-added token: {tokens.IndexOf(unaddedToken)}");
```

**Output:**
```
Precedence Check:
Caret (^) > Star (*): True
Star (*) > Plus (+): True
Index of un-added token: -1
```

---

### Example ID: 1046

**Description:** Practical: Demonstrates how removing the token for single-quoted strings causes the parser to treat the quote and its contents as individual generic tokens.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// This example removes the single-quoted string token.
var t = new uCalc.Transformer();
string txt = "This is a test, 'This is a test'";
t.FromTo("{token:1}", "<{@Self}>");

Console.WriteLine("--- Before Removing Token ---");
// Initially, 'This is a test' is treated as a single token.
Console.WriteLine(t.Transform(txt).Text);

// Now, find and remove the token definition for single-quoted strings.
var singleQuoteToken = t.Tokens.ByName("_token_string_singlequoted");
t.Tokens.Remove(singleQuoteToken);

// Re-run the transform. The text must be set again to be re-tokenized.
t.Text = txt;
Console.WriteLine("");
Console.WriteLine("--- After Removing Token ---");
// Now, the single quote is a generic token, as are the words inside it.
Console.WriteLine(t.Transform().Text);
```

**Output:**
```
--- Before Removing Token ---
<This> <is> <a> <test><,> <'This is a test'>

--- After Removing Token ---
<This> <is> <a> <test><,> <'><This> <is> <a> <test><'>
```

---

### Example ID: 1047

**Description:** Internal Test: Removes the core alphanumeric token to verify that the tokenizer falls back to character-by-character tokenization.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
string text = "word game";
t.FromTo("{token:1}", "[{@Self}]");

Console.WriteLine("--- Before Remove ---");
// By default, 'word' is a single alphanumeric token.
Console.WriteLine(t.Transform(text));

// Remove the alphanumeric token definition.
var alphaToken = t.Tokens.ByName("_token_alphanumeric");
t.Tokens.Remove(alphaToken);

// The transformer must be reset with the original text for the change to apply.
t.Text = text;

Console.WriteLine("");
Console.WriteLine("--- After Remove ---");
// Now, 'word' is no longer a single token. The fallback '.' token
// matches each character individually.
Console.WriteLine(t.Transform());
```

**Output:**
```
--- Before Remove ---
[word] [game]

--- After Remove ---
[w][o][r][d] [g][a][m][e]
```

---

### Example ID: 1048

**Description:** Retrieves a Tokens collection's parent uCalc instance and verifies its identity by reading a description.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.uCalc.Description = "My Parent uCalc";
var tokens = t.Tokens;

// Get the parent from the Tokens object
var parent_uc = tokens.uCalc;

// Verify we got the correct parent
Console.WriteLine(parent_uc.Description);
```

**Output:**
```
My Parent uCalc
```

---

### Example ID: 1049

**Description:** Uses the parent uCalc context from a Tokens object to define a variable that is then used by a transformer rule.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var tokens = t.Tokens;

// Use the parent uCalc instance to define a variable
tokens.uCalc.DefineVariable("replacement = 'REPLACED'");

t.FromTo("original", "{@Eval: replacement}");

Console.WriteLine(t.Transform("Test of original value."));
```

**Output:**
```
Test of REPLACED value.
```

---

### Example ID: 1050

**Description:** Internal Test: Verifies instance isolation by ensuring Tokens collections from different uCalc instances correctly resolve to their respective parents.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var uc1 = new uCalc();
var uc2 = new uCalc();

var t1 = new uCalc.Transformer(uc1);
var t2 = new uCalc.Transformer(uc2);

var tokens1 = t1.Tokens;
var tokens2 = t2.Tokens;

var parent1 = tokens1.uCalc;
var parent2 = tokens2.uCalc;

Console.WriteLine($"tokens1 belongs to uc1: {parent1.Handle() == uc1.Handle()}");
Console.WriteLine($"tokens2 belongs to uc2: {parent2.Handle() == uc2.Handle()}");
Console.WriteLine($"tokens1 does not belong to uc2: {parent1.Handle() != uc2.Handle()}");
```

**Output:**
```
tokens1 belongs to uc1: True
tokens2 belongs to uc2: True
tokens1 does not belong to uc2: True
```

---

### Example ID: 1054

**Description:** Demonstrating that a clone is independent and that modifying it does not affect the original.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Create and configure the original transformer
var t1 = new uCalc.Transformer();
t1.FromTo("A", "B");
Console.WriteLine($"Original Transform: {t1.Transform("A C A")}");

// 2. Clone it
var t2 = t1.Clone();

// 3. Modify the clone. This does not affect the original.
t2.FromTo("C", "D");
Console.WriteLine($"Cloned Transform:   {t2.Transform("A C A")}");

// 4. Verify original is unchanged by re-running its transform
Console.WriteLine($"Original is Unchanged: {t1.Transform("A C A")}");
t2.Release();
t1.Release();
```

**Output:**
```
Original Transform: B C B
Cloned Transform:   B D B
Original is Unchanged: B C B
```

---

### Example ID: 1055

**Description:** A practical example using Clone() to create a specialized parser from a base template, demonstrating rule inheritance.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Create a "base" HTML transformer template
var baseHtmlParser = new uCalc.Transformer();
baseHtmlParser.Description = "Base HTML Parser";
// Rule to skip over comments
baseHtmlParser.SkipOver("<!--{body}->");
// Rule to find any tag
baseHtmlParser.Pattern("<{tag}>");
baseHtmlParser.DefaultRuleSet.SetStatementSensitive(false);

// 2. Create a specialized clone to find only image tags
var imageParser = baseHtmlParser.Clone();
imageParser.Description = "Image Tag Finder";
imageParser.FromTo("<img {attribs} />", "FOUND_IMG_TAG");

string html = " <body> <img src='a.jpg' /> <!-- <img src='b.jpg' /> --> </body> ";

// The clone inherits the SkipOver rule from the base, so the commented img tag is ignored.
Console.WriteLine(imageParser.Transform(html));

imageParser.Release();
baseHtmlParser.Release();
```

**Output:**
```
 <body> FOUND_IMG_TAG <!-- <img src='b.jpg' /> --> </body> 
```

---

### Example ID: 1062

**Description:** A basic example demonstrating how to set and get a description for a Transformer.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Description = "My First Transformer";
Console.WriteLine($"Transformer Description: {t.Description}");
```

**Output:**
```
Transformer Description: My First Transformer
```

---

### Example ID: 1063

**Description:** Uses descriptions to differentiate between two transformers used for different environments, such as a verbose 'debug' transformer and a silent 'production' one.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var text = "The value is x";

// 1. Setup Debug Transformer
var t_debug = new uCalc.Transformer();
t_debug.Description = "Debug Transformer (Verbose)";
t_debug.FromTo("x", "100 // debug value");

// 2. Setup Production Transformer
var t_prod = new uCalc.Transformer();
t_prod.Description = "Production Transformer (Clean)";
t_prod.FromTo("x", "100");

Console.WriteLine($"{t_debug.Description}: {t_debug.Transform(text)}");
Console.WriteLine($"{t_prod.Description}: {t_prod.Transform(text)}");
```

**Output:**
```
Debug Transformer (Verbose): The value is 100 // debug value
Production Transformer (Clean): The value is 100
```

---

### Example ID: 1064

**Description:** Internal Test: Verifies that the description property is correctly copied when a Transformer is cloned.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t_original = new uCalc.Transformer();
t_original.Description = "Original Transformer";

// Clone the transformer
var t_cloned = t_original.Clone();

Console.WriteLine($"Original Description: {t_original.Description}");
Console.WriteLine($"Cloned Description:   {t_cloned.Description}");

// Modify the clone's description to ensure they are independent
t_cloned.Description = "Cloned and Modified";

Console.WriteLine($"Original after mod: {t_original.Description}");
Console.WriteLine($"Cloned after mod:   {t_cloned.Description}");
```

**Output:**
```
Original Description: Original Transformer
Cloned Description:   Original Transformer
Original after mod: Original Transformer
Cloned after mod:   Cloned and Modified
```

---

### Example ID: 1065

**Description:** Finding all occurrences of a specific word.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "apple banana apple cherry apple";
t.Pattern("apple");
t.Find();
Console.WriteLine($"Found {t.Matches.Count()} occurrences of 'apple'.");
```

**Output:**
```
Found 3 occurrences of 'apple'.
```

---

### Example ID: 1066

**Description:** A practical example using multiple concurrent patterns to find and categorize log entries.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed.";
t.Text = logText;

// Define rules for different log levels
var errorRule = t.Pattern("ERROR: {msg}.");
var warnRule = t.Pattern("WARN: {msg}.");

t.Find();

Console.WriteLine($"Total issues found: {t.Matches.Count()}");
Console.WriteLine("--- Error Matches ---");
Console.WriteLine(errorRule.Matches.Text);
Console.WriteLine("--- Warning Matches ---");
Console.WriteLine(warnRule.Matches.Text);
```

**Output:**
```
Total issues found: 2
--- Error Matches ---
ERROR: DB connection failed.
--- Warning Matches ---
WARN: Low disk.
```

---

### Example ID: 1067

**Description:** Internal Test: Verifies correct precedence with overlapping patterns and confirms that re-running Find produces the same results.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "The apple is an apple.";

// Overlapping patterns. The longer one is defined last, so it gets precedence.
t.Pattern("apple");
t.Pattern("an apple");

Console.WriteLine("--- First Find ---");
t.Find();
// The first 'apple' matches the first rule.
// The 'an apple' matches the second (higher precedence) rule.
Console.WriteLine(t.Matches.Text);

// Re-running find should produce the exact same result
Console.WriteLine("--- Second Find (no change) ---");
t.Find();
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
--- First Find ---
apple
an apple
--- Second Find (no change) ---
apple
an apple
```

---

### Example ID: 1071

**Description:** A simple find-and-replace transformation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("Hello {name}", "Greetings, {name}!");
Console.WriteLine(t.Transform("Hello World"));
```

**Output:**
```
Greetings, World!
```

---

### Example ID: 1080

**Description:** Demonstrates the basic difference between getting all matches and filtering for only 'focusable' ones.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "ID:100, Name:Admin, ID:200";

// Define two rules, but only one is marked as 'focusable'
t.Pattern("ID:{@Number}").SetFocusable(true);
t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// Get all matches using the default option
var allMatches = t.GetMatches();
Console.WriteLine($"--- All Matches ({allMatches.Count()}) ---");
Console.WriteLine(allMatches.Text);

// Get only the focusable matches
var focusableMatches = t.GetMatches(MatchesOption.FocusableOnly);
Console.WriteLine("");
Console.WriteLine($"--- Focusable Matches Only ({focusableMatches.Count()}) ---");
Console.WriteLine(focusableMatches.Text);
```

**Output:**
```
--- All Matches (3) ---
ID:100
Name:Admin
ID:200

--- Focusable Matches Only (2) ---
ID:100
ID:200
```

---

### Example ID: 1081

**Description:** Parses a log file and uses the `FocusableOnly` option to quickly extract only the critical error entries.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var log = "INFO: Task started. ERROR: Connection failed. INFO: Task finished.";
t.Text = log;

// Rules for different log levels. Only errors are focusable.
t.Pattern("INFO: {msg}.").SetFocusable(false);
t.Pattern("ERROR: {msg}.").SetFocusable(true);
t.Find();

Console.WriteLine("All log entries:");
Console.WriteLine(t.GetMatches().Text);
Console.WriteLine("");

Console.WriteLine("Critical errors only:");
// Use the option to filter for only the important entries
var errorMatches = t.GetMatches(MatchesOption.FocusableOnly);
Console.WriteLine(errorMatches.Text);
```

**Output:**
```
All log entries:
INFO: Task started.
ERROR: Connection failed.
INFO: Task finished.

Critical errors only:
ERROR: Connection failed.
```

---

### Example ID: 1099

**Description:** A simple `Find()` followed by `@Matches().Count()` to count all occurrences of a word.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "apple banana apple cherry apple";

// Define a pattern to find any alphanumeric word
t.Pattern("apple");
t.Find();

Console.WriteLine($"Found {t.Matches.Count()} occurrences of 'apple'.");
```

**Output:**
```
Found 3 occurrences of 'apple'.
```

---

### Example ID: 1100

**Description:** Practical: Iterates through all matches and uses the `Match.Rule` property to identify which pattern generated each match, demonstrating a key introspection feature.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed.";
t.Text = logText;

// Define rules for different log levels
var errorRule = t.Pattern("ERROR: {msg}.");
var warnRule = t.Pattern("WARN: {msg}.");
var infoRule = t.Pattern("INFO: {msg}.");

t.Find();

Console.WriteLine("--- Analysis of All Matches ---");
foreach(var match in t.Matches) {
   // Use the match's Rule property to get the name of the rule that found it
   Console.WriteLine($"Found '{match.Text}' using rule: '{match.Rule.Name}'");
}
```

**Output:**
```
--- Analysis of All Matches ---
Found 'INFO: System start.' using rule: 'info'
Found 'WARN: Low disk.' using rule: 'warn'
Found 'ERROR: DB connection failed.' using rule: 'error'
```

---

### Example ID: 1105

**Description:** A simple two-pass transformation where the output of the first pass becomes the input for the second.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "A";

// Pass 0 will change 'A' to 'B'
var pass0 = t.Pass(0);
pass0.FromTo("A", "B");

// Pass 1 will receive 'B' and change it to 'C'
var pass1 = t.Pass(1);
pass1.FromTo("B", "C");

t.Transform();
Console.WriteLine(t); // The final output is 'C'
```

**Output:**
```
C
```

---

### Example ID: 1118

**Description:** Shows how a full reset clears all rules and input, allowing a transformer object to be reconfigured from a clean slate.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var txt = "a b c d e";

t.Text = txt;
t.FromTo("a", "aaa");
t.FromTo("c", "xyz");

Console.WriteLine($"Input: {t}");
Console.WriteLine($"Transformed: {t.Transform()}");

Console.WriteLine("");
Console.WriteLine("Resetting...");
t.Reset();

Console.WriteLine($"Input after reset: {t}(empty)");
t.Text = "a b c d e";
Console.WriteLine($"New input: {t.Text}");
Console.WriteLine($"Transform after reset: {t.Transform().Text} (no rules exist)");

Console.WriteLine("");
Console.WriteLine("Defining new rules...");
t.FromTo("b", "ABC");
t.FromTo("d", "DDD");
Console.WriteLine($"Final transformed: {t.Transform().Text}");
```

**Output:**
```
Input: a b c d e
Transformed: aaa b xyz d e

Resetting...
Input after reset: (empty)
New input: a b c d e
Transform after reset: a b c d e (no rules exist)

Defining new rules...
Final transformed: a ABC c DDD e
```

---

### Example ID: 1123

**Description:** How `SkipOver` creates 'dead zones' where other rules are not applied.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "transform this but (not this) and this";

// A rule to replace the word 'this'
t.FromTo("this", "THAT");

// A rule to ignore any content inside parentheses
t.SkipOver("({content})");

// The 'this' inside the parentheses is protected by the SkipOver rule
Console.WriteLine(t.Transform());
```

**Output:**
```
transform THAT but (not this) and THAT
```

---

### Example ID: 1124

**Description:** A practical, real-world example of using `SkipOver` to ignore HTML comments while transforming other parts of the document.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Disable statement sensitivity to handle multi-line content
t.DefaultRuleSet.StatementSensitive = false;

var htmlContent =
"""

<nav>
  <li><a href="#intro">Intro</a></li>
  <!-- <li><a href="#contact">Contact</a></li> -->
  <li><a href="#about">About</a></li>
</nav>

""";
t.Text = htmlContent;

// A rule to find all list items
t.Pattern("<li>{item}</li>");

// A rule to skip over HTML comments
t.SkipOver("<!-- {comment} -->");

t.Find();
Console.WriteLine("--- Found List Items ---");
Console.WriteLine(t.Matches.Text);
```

**Output:**
```
--- Found List Items ---
<li><a href="#intro">Intro</a></li>
<li><a href="#about">About</a></li>
```

---

### Example ID: 1132

**Description:** A basic example of setting the text, transforming it, and retrieving the result.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// 1. Set the initial text
t.Text = "The quick brown fox.";

// 2. Define a rule and transform
t.FromTo("brown", "red");
t.Transform();

// 3. Get the final text
Console.WriteLine(t.Text);
```

**Output:**
```
The quick red fox.
```

---

### Example ID: 1133

**Description:** Demonstrates using the Text property with implicit conversions (shortcuts) to parse a simple config string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// Implicitly set the Text property by assigning a string to the object
t = "user=admin; level=9; theme=dark;";

// Define a rule to extract the user value
t.FromTo("user={name};", "Username: {name}");
t.Transform();

// Implicitly get the Text property by using the object in a string context
string result = t;
Console.WriteLine(result);
```

**Output:**
```
Username: admin level=9; theme=dark;
```

---

### Example ID: 1135

**Description:** Adds a C-style single-line comment token and categorizes it as whitespace to be ignored by other rules.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("this", "THAT");

string text = "transform this but not // this in a comment";

Console.WriteLine("--- Before --- ");
// Initially, the comment is treated as regular text.
Console.WriteLine(t.Transform(text));

// Add a token for C-style comments and classify it as whitespace.
t.Tokens.Add("//.*", TokenType.Whitespace);

Console.WriteLine("");
Console.WriteLine("--- After --- ");
// Re-run the transform. The comment is now ignored.
Console.WriteLine(t.Transform(text));
```

**Output:**
```
--- Before --- 
transform THAT but not // THAT in a comment

--- After --- 
transform THAT but not // this in a comment
```

---

### Example ID: 1136

**Description:** Practical: Modifies the default alphanumeric token to include hyphens, allowing it to match hyphenated identifiers as single words.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@Alpha:word}", "[{word}]");
string text = "id-E123 is a special-identifier.";

Console.WriteLine("--- Before --- ");
// By default, 'id-123' is tokenized as three separate parts: 'id', '-', and '123'.
Console.WriteLine(t.Transform(text));

// Get the alphanumeric token item by its name and modify its regex.
var alphaToken = t.Tokens["_token_alphanumeric"];
alphaToken.Regex = "[a-zA-Z0-9-]+";

Console.WriteLine("");
Console.WriteLine("--- After --- ");
// Now, hyphenated words are matched as single alphanumeric tokens.
Console.WriteLine(t.Transform(text));
```

**Output:**
```
--- Before --- 
[id]-[E123] [is] [a] [special]-[identifier].

--- After --- 
[id-E123] [is] [a] [special-identifier].
```

---

### Example ID: 1138

**Description:** A simple cascading transformation (`A` -> `B` -> `C` -> `D`) shows the step-by-step output using ListSeparator()

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// RewindOnChange is necessary for cascading rules to be re-evaluated.
t.FromTo("A", "B").RewindOnChange = true;
t.FromTo("B", "C").RewindOnChange = true;
t.FromTo("C", "D").RewindOnChange = true;

// Trace the transformation of "A"
uCalc.String trace = t.TraceTransform("A");

// Format the output list with ' -> ' for readability
trace.ListSeparator(" -> ");

Console.WriteLine(trace);
```

**Output:**
```
A -> B -> C -> D
```

---

### Example ID: 1139

**Description:** Practical: Traces the recursive expansion of a custom `MySum` function, showing how it is broken down into a standard arithmetic expression.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.ExpressionTransformer;

// Assume these rules are pre-defined to create a recursive sum
t.FromTo("MySum({x})", "{x}");
t.FromTo("MySum({x}, {y})", "({x} + MySum({y}))").RewindOnChange = true;

uCalc.String trace = t.TraceTransform("MySum(1,2,3,4)");
trace.ListSeparator("\n");

Console.WriteLine(trace);
```

**Output:**
```
MySum(1,2,3,4)
(1 + MySum(2,3,4))
(1 + (2 + MySum(3,4)))
(1 + (2 + (3 + MySum(4))))
(1 + (2 + (3 + 4)))
```

---

### Example ID: 1140

**Description:** Internal Test: Verifies advanced formatting of the trace output using `ListFormat` to create a custom, detailed step-by-step log.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("A", "B").RewindOnChange = true;
t.FromTo("B", "C").RewindOnChange = true;
t.FromTo("C", "D").RewindOnChange = true;

uCalc.String trace = t.TraceTransform("A");

// Apply a custom format to each step in the list
trace.ListFormat("!", "(", ")", "$'{txt}->{n+1}/{c}'", "txt", "n", "c");

Console.WriteLine(trace);
```

**Output:**
```
(A->1/4!B->2/4!C->3/4!D->4/4)
```

---

### Example ID: 1141

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Define a simple replacement rule
t.FromTo("Hello", "Greetings");

// Execute the transformation on an input string
t.Text = "Hello World, and Hello again.";
Console.WriteLine(t.Transform());
```

**Output:**
```
Greetings World, and Greetings again.
```

---

### Example ID: 1142

**Description:** A practical example sanitizing user input by removing script tags and normalizing excess whitespace in a single pass.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Rule 1: Remove script tags and their content (case-insensitive, multi-line)
t.FromTo("<script>{content}</script>", "");
t.DefaultRuleSet.SetCaseSensitive(false).SetStatementSensitive(false);

// Rule 2: Normalize one or more whitespace characters to a single space
t.FromTo("{@Whitespace:ws}", " ");

// Transform the input in one go and print the result
t.Text = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ";
Console.WriteLine($"Sanitized: '{t.Transform()}'");
```

**Output:**
```
Sanitized: ' Welcome! Please enjoy. '
```

---

### Example ID: 1144

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // Define a simple replacement rule
   t.FromTo("Hello", "Greetings");

   // Execute the transformation on an input string
   Console.WriteLine(t.Transform("Hello World, and Hello again."));
}
```

**Output:**
```
Greetings World, and Greetings again.
```

---

### Example ID: 1145

**Description:** A practical example sanitizing user input by removing script tags and normalizing excess whitespace in a single pass.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // Rule 1: Remove script tags and their content (case-insensitive, multi-line)
   t.FromTo("<script>{content}</script>", "");
   t.DefaultRuleSet.SetCaseSensitive(false).SetStatementSensitive(false);

   // Rule 2: Normalize one or more whitespace characters to a single space
   t.FromTo("{@Whitespace:ws}", " ");

   string userInput = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ";

   // Transform the input in one go and print the result
   Console.WriteLine($"Sanitized: '{t.Transform(userInput)}'");
}
```

**Output:**
```
Sanitized: ' Welcome! Please enjoy. '
```

---

### Example ID: 1150

**Description:** Demonstrates the basic true/false state of the WasModified flag.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("a", "*a good*");

// Case 1: A match occurs, text is modified.
t.Text = "This is a test";
t.Transform();
Console.WriteLine($"Modified: {t.WasModified}");

// Case 2: No match occurs, text is unchanged.
t.Text = "This is another test";
t.Transform();
Console.WriteLine($"Modified: {t.WasModified}");
```

**Output:**
```
Modified: True
Modified: False
```

---

### Example ID: 1151

**Description:** Shows how to use WasModified to avoid an expensive operation, like saving to a file, if no changes were made during a data sanitization process.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var sanitizer = new uCalc.Transformer();
sanitizer.FromTo("error", "ERROR");

// Simulate processing multiple logs
string log1 = "status: ok";
string log2 = "status: error";

Console.WriteLine("--- Processing Log 1 ---");
sanitizer.Text = log1;
sanitizer.Transform();
if (sanitizer.WasModified) {
   Console.WriteLine("Change detected. Saving updated log...");
   // SaveToFile(sanitizer.GetText());
} else {
   Console.WriteLine("No changes. Skipping save.");
}

Console.WriteLine("");
Console.WriteLine("--- Processing Log 2 ---");
sanitizer.Text = log2;
sanitizer.Transform();
if (sanitizer.WasModified) {
   Console.WriteLine("Change detected. Saving updated log...");
   // SaveToFile(sanitizer.GetText());
   Console.WriteLine($"Updated log: {sanitizer.Text}");
} else {
   Console.WriteLine("No changes. Skipping save.");
}
```

**Output:**
```
--- Processing Log 1 ---
No changes. Skipping save.

--- Processing Log 2 ---
Change detected. Saving updated log...
Updated log: status: ERROR
```

---

### Example ID: 1156

**Description:** A simple find-and-replace operation using the fluent, chainable API.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("The quick brown fox.")) {
   
   // Replace returns the modified String object
   s.Replace("brown", "red");

   // Use implicit conversion to print the result
   Console.WriteLine(s);
}
```

**Output:**
```
The quick red fox.
```

---

### Example ID: 1159

**Description:** Demonstrates interoperability between `Transformer` and `String` objects, and chaining methods to create nested views.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create a transformer and perform a transformation
var t = uc.NewTransformer();
t.Text = "if (x > 3) y = x * 2; else if(x == 5) y = x - 1;";
t.FromTo("1", "100");
t.Transform();

// --- Interoperability and Chaining ---

var Pattern = "if ({cond})";

// 1. Create a uCalc.String from a Transformer.
// 2. Chain .After() to get a "live view" of the text after the pattern.
var s = new uCalc.String(t);
var after_first_if = s.After(Pattern);
Console.WriteLine(after_first_if.Text);

// 3. Chain another .After() on the child string.
var after_second_if = after_first_if.After(Pattern);
Console.WriteLine(after_second_if.Text);

// --- String to Transformer Conversion ---

// 4. Create a uCalc.String and assign it text.
var s2 = new uCalc.String();
s2 = "This is a test";

// 5. Create a Transformer from the uCalc.String to use transformer-specific methods.
var t2 = new uCalc.Transformer(s2);
Console.WriteLine(t2.Text);
```

**Output:**
```
y = x * 2; else if(x == 5) y = x - 100;
 y = x - 100;
This is a test
```

---

### Example ID: 1160

**Description:** Demonstrates the basic getter and setter syntax for a property

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// Set the description using the property setter syntax
t.Description = "My Transformer";

// Get the description using the property getter syntax
Console.WriteLine($"Description: {t.Description}");
```

**Output:**
```
Description: My Transformer
```

---

### Example ID: 1161

**Description:** A practical example using the fluent interface of `Set...` methods to configure multiple properties of a rule in a single chained statement.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var rule = t.FromTo("A", "B");

// Chain multiple Set... methods for a clean configuration
rule.SetCaseSensitive(true)
.SetWhitespaceSensitive(false)
.SetQuoteSensitive(false);

// Verify the properties were set using their corresponding getters
Console.WriteLine($"Case Sensitive: {rule.CaseSensitive}");
Console.WriteLine($"Whitespace Sensitive: {rule.WhitespaceSensitive}");
Console.WriteLine($"Quote Sensitive: {rule.QuoteSensitive}");
```

**Output:**
```
Case Sensitive: True
Whitespace Sensitive: False
Quote Sensitive: False
```

---

### Example ID: 1163

**Description:** Extracting a value from a simple key-value pair.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("ID: 12345")) {
   
   // Get the text after the "ID: " prefix
   var value = s.After("ID: ");

   Console.WriteLine(value);
}
```

**Output:**
```
 12345
```

---

### Example ID: 1164

**Description:** A practical example demonstrating how to extract an error message from a log entry and then chain another operation to modify that section.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var log = new uCalc.String("INFO: Task complete. ERROR: File not found.")) {
   
   // Chain After() to isolate the error, then Replace() to modify it.
   var errorDetails = log.After("ERROR: ").Replace("File", "Resource");

   Console.WriteLine($"Original log: {log}");      // The original string is modified in-place
   Console.WriteLine($"Modified details:{errorDetails}"); // The view reflects the change
}
```

**Output:**
```
Original log: INFO: Task complete. ERROR: Resource not found.
Modified details: Resource not found.
```

---

### Example ID: 1165

**Description:** Internal Test: Verifies behavior for patterns at the end of the string and patterns that are not found.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("A B C")) {
   
   // Case 1: Pattern is at the end. Should return an empty string.
   Console.Write("After 'C': '");
   Console.Write(s.After("C"));
   Console.WriteLine("'");

   // Case 2: Pattern does not exist. Should return an empty string.
   Console.Write("After 'D': '");
   Console.Write(s.After("D"));
   Console.WriteLine("'");

   // Case 3: Get text after the first word.
   Console.Write("After 'A': '");
   Console.Write(s.After("A"));
   Console.WriteLine("'");
}
```

**Output:**
```
After 'C': ''
After 'D': ''
After 'A': ' B C'
```

---

### Example ID: 1172

**Description:** Demonstrates the power of token-awareness by safely renaming a variable while ignoring its name inside a string literal—a common failure point for character-based Regex.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// A snippet of code where 'rate' is both a variable and part of a string
var source_code = """
rate = 0.05; // Set default rate
print("Current rate is: " + rate);
""";

Console.WriteLine("Original Code:");
Console.WriteLine(source_code);
Console.WriteLine("");

// Define a rule to rename the VARIABLE 'rate' to 'annual_rate'
t.FromTo("rate", "annual_rate");
t.SkipOver("// {text}");

// Run the transformation. The 'rate' inside the string is untouched.
Console.WriteLine("Transformed Code:");
Console.WriteLine(t.Transform(source_code));
```

**Output:**
```
Original Code:
rate = 0.05; // Set default rate
print("Current rate is: " + rate);

Transformed Code:
annual_rate = 0.05; // Set default rate
print("Current rate is: " + annual_rate);
```

---

### Example ID: 1173

**Description:** Demonstrates how uCalc's token-aware Transformer safely renames a variable without corrupting a string literal, a common failure point for Regex.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// A rule to replace the alphanumeric token 'x' with 'value'
t.FromTo("x", "value");

// The input string where 'x' appears both as a variable and inside a string
var code = """
if (x > 10) print("Max value is x");
""";

// The transformation correctly ignores the 'x' inside the quoted string
Console.WriteLine(t.Transform(code));
```

**Output:**
```
if (value > 10) print("Max value is x");
```

---

### Example ID: 1175

**Description:** Illustrates lazy evaluation by creating a custom 'Repeat' function that executes a code block (passed with `ByExpr`) a specified number of times.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyRepeat(uCalc.Callback cb) {
   var count = cb.ArgInt32(1);
   var action = cb.ArgExpr(2);

   for (int i = 1; i <= count; i++) {
      action.Execute(); // Evaluate the passed-in expression
   }
}


// Define a variable that our action will modify
uc.DefineVariable("counter = 0");

// Define the function. The 'action' parameter is marked with ByExpr
// to ensure it's passed as an unevaluated expression object.
uc.DefineFunction("Repeat(count As Int, ByExpr action)", MyRepeat);

// Call the custom Repeat function. The expression 'counter++' is not
// evaluated here; it's passed to the callback to be executed in a loop.
uc.Eval("Repeat(5, counter++)");

// Verify the side effect
Console.WriteLine($"Final counter value: {uc.Eval("counter")}");
```

**Output:**
```
Final counter value: 5
```

---

### Example ID: 1176

**Description:** A 'Hello, World!' example demonstrating the creation and evaluation of an expression using the modern, simplified syntax.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Create a new Expression object with an initial formula.
// This uses the default uCalc instance for context.
var expr = new uCalc.Expression("1 + 1");

// Implicitly calls .EvaluateStr() when used in a string context
Console.WriteLine($"Initial value: {expr}");

// Reassign the expression to a new formula with a simple string assignment.
// This implicitly calls .Parse() behind the scenes.
expr = "10 * (5 + 3)";

// Retrieve the result. For numeric results, you can assign it
// directly to a double. This implicitly calls .Evaluate().
double result = expr;
Console.Write("New value: "); Console.Write(result);
```

**Output:**
```
Initial value: 2
New value: 80
```

---

### Example ID: 1177

**Description:** Evaluating a basic arithmetic expression with multiple operators.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.EvalStr("10 * 5 + 3"));
```

**Output:**
```
53
```

---

### Example ID: 1178

**Description:** Calculating a simple percentage for a real-world financial scenario.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Calculate a 15% discount on a price of $75
Console.Write("Discounted price: ");
Console.WriteLine(uc.EvalStr("75 * (1 - 0.15)"));
```

**Output:**
```
Discounted price: 63.75
```

---

### Example ID: 1179

**Description:** Internal Test: Verify correct order of operations with mixed operators and parentheses.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// This tests the precedence of power (^), multiplication (*), and addition (+).
// The correct evaluation is 5 + (2 * (3^2)) -> 5 + (2 * 9) -> 5 + 18 -> 23.
Console.WriteLine(uc.EvalStr("5 + 2 * 3^2"));
```

**Output:**
```
23
```

---

### Example ID: 1180

**Description:** A basic example of defining a variable and using it in an expression.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 10");
Console.WriteLine(uc.EvalStr("x * 5"));
```

**Output:**
```
50
```

---

### Example ID: 1181

**Description:** Calculates simple interest using pre-defined variables for a real-world scenario.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("principal = 5000");
uc.DefineVariable("rate = 0.05");
uc.DefineVariable("years = 4");
Console.WriteLine($"Interest: {uc.EvalStr("principal * rate * years")}");
```

**Output:**
```
Interest: 1000
```

---

### Example ID: 1182

**Description:** Internal Test: Tests programmatic updates to a variable from host code in a loop, a common high-performance pattern.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var myVar = uc.DefineVariable("x");
var expr = uc.Parse("x * 2");

var i = 0;
for ( i = 1; i <= 5; i++) {
   myVar.Value(i);
   Console.WriteLine($"When x is {i}, result is: {expr.Evaluate()}");
}
```

**Output:**
```
When x is 1, result is: 2
When x is 2, result is: 4
When x is 3, result is: 6
When x is 4, result is: 8
When x is 5, result is: 10
```

---

### Example ID: 1183

**Description:** A simple example demonstrating a few of the most common math, logic, and string functions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine($"Square root of 81 is: {uc.Eval("Sqrt(81)")}");
Console.WriteLine($"Is 10 greater than 5? {uc.EvalStr("IIf(10 > 5, 'Yes', 'No')")}");
Console.WriteLine($"String length: {uc.Eval("Length('uCalc rocks!')")}");
```

**Output:**
```
Square root of 81 is: 9
Is 10 greater than 5? Yes
String length: 12
```

---

### Example ID: 1185

**Description:** Internal Test: Verifies that a built-in function using `ByHandle` arguments can correctly modify the state of variables passed to it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("a = 10");
uc.DefineVariable("b = 20");

Console.WriteLine($"Before - a: {uc.Eval("a")}, b: {uc.Eval("b")}");

// The built-in Swap() function uses ByHandle to modify variables directly.
uc.Eval("Swap(a, b)");

Console.Write("After - a: "); Console.Write(uc.Eval("a")); Console.Write(", b: "); Console.Write(uc.Eval("b"));
```

**Output:**
```
Before - a: 10, b: 20
After - a: 20, b: 10
```

---

### Example ID: 1186

**Description:** A simple inline function to convert inches to centimeters.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineFunction("InToCm(inches) = inches * 2.54");
Console.WriteLine(uc.Eval("InToCm(10)"));
```

**Output:**
```
25.4
```

---

### Example ID: 1187

**Description:** Practical: A callback-based logging function that prints a message to the console.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void LogMessage(uCalc.Callback cb) {
   string msg = cb.ArgStr(1);
   // In a real app, this would write to a file or log service.
   Console.WriteLine("[LOG]: " + msg);
}

uc.DefineFunction("Log(message As String)", LogMessage);
uc.Eval("Log('System initialized')");
uc.Eval("Log('User logged in')");
```

**Output:**
```
[LOG]: System initialized
[LOG]: User logged in
```

---

### Example ID: 1188

**Description:** Internal Test: A custom `IIf` implementation using `ByExpr` to test lazy evaluation. The branches containing division by zero are never executed, preventing errors.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void CustomIIf(uCalc.Callback cb) {
   bool condition = cb.ArgBool(1);
   var truePart = cb.ArgExpr(2);
   var falsePart = cb.ArgExpr(3);

   if (condition) {
      cb.Return(truePart.Evaluate());
   } else {
      cb.Return(falsePart.Evaluate());
   }
}

uc.DefineFunction("MyIIf(condition As Bool, ByExpr thenExpr, ByExpr elseExpr)", CustomIIf);

// The 'else' branch contains a division by zero, but it should NOT be evaluated
// because the condition (1 < 2) is true.
var result = uc.Eval("MyIIf(1 < 2, 100, 1/0)");
Console.Write("Result 1: ");
Console.WriteLine(result);

// Now test the false branch. The 'then' branch with the error is skipped.
result = uc.Eval("MyIIf(1 > 2, 1/0, 200)");
Console.Write("Result 2: ");
Console.WriteLine(result);
```

**Output:**
```
Result 1: 100
Result 2: 200
```

---

### Example ID: 1189

**Description:** How to reactively check for an error after an operation fails, and how a subsequent successful operation clears the error state.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Trigger a syntax error
uc.EvalStr("1 +");

// Check the error state after the fact
if (uc.Error.Code != ErrorCode.None) {
   Console.WriteLine($"Error detected: {uc.Error.Message}");
} else {
   Console.WriteLine("Success!");
}

// Perform a successful operation, which clears the error state
uc.EvalStr("1 + 1");
if (uc.Error.Code == ErrorCode.None) {
   Console.WriteLine("Previous error was cleared by successful operation.");
}
```

**Output:**
```
Error detected: Syntax error
Previous error was cleared by successful operation.
```

---

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// This handler automatically defines variables when they are first used.
static void AutoDefineHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   // Check if the error is specifically an undefined identifier
   if (uc.Error.Code == ErrorCode.Undefined_Identifier) {
      Console.WriteLine($"Handler: '{uc.Error.Symbol}' is undefined. Defining it now.");
      uc.DefineVariable(uc.Error.Symbol);

      // Tell the engine to resume the operation
      uc.Error.Response = ErrorHandlerResponse.Resume;
   }
}


uc.Error.AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

Console.WriteLine($"Final result: {result}");
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

### Example ID: 1192

**Description:** A minimal example demonstrating the basic 'Parse once, Evaluate many' pattern.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Parse the expression string once to create a reusable object.
//var expr = uc.Parse("5 * 10");
using (var expr = new uCalc.Expression("5 * 10")) {
   
   // 2. Evaluate the pre-parsed object as many times as needed.
   Console.WriteLine(expr.Evaluate());
   Console.WriteLine(expr.Evaluate());

} // The expression object is automatically released here.
```

**Output:**
```
50
50
```

---

### Example ID: 1193

**Description:** A real-world example contrasting the inefficient loop with the high-performance 'Parse-Once' pattern using a changing variable.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var x_var = uc.DefineVariable("x");
var i = 0;

// --- Inefficient Way ---
Console.WriteLine("--- Inefficient: Eval() in a loop ---");
for ( i = 1; i <= 3; i++) {
   x_var.Value(i);
   Console.WriteLine(uc.Eval("x * x + 2"));
}

Console.WriteLine("");

// --- High-Performance Way ---
Console.WriteLine("--- Efficient: Parse() once, Evaluate() in a loop ---");
// Parse outside the loop
var expr = uc.Parse("x * x + 2");
for ( i = 1; i <= 3; i++) {
   x_var.Value(i);
   // Evaluate the pre-parsed object
   Console.WriteLine(expr.Evaluate());
}
```

**Output:**
```
--- Inefficient: Eval() in a loop ---
3
6
11

--- Efficient: Parse() once, Evaluate() in a loop ---
3
6
11
```

---

### Example ID: 1194

**Description:** Internal Test: Verifies correct results with multiple variables and a function call within a tight loop using a pre-parsed expression.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineFunction("Calc(a, b) = a * 2 - b");
var x_var = uc.DefineVariable("x");
var y_var = uc.DefineVariable("y");
var i = 0;

var expr = uc.Parse("Calc(x, y) + Sqrt(x)");
for ( i = 1; i <= 4; i++) {
   x_var.Value(i * i); // Use squared values for x
   y_var.Value(i);     // Use linear values for y
   Console.WriteLine(expr.Evaluate());
}
```

**Output:**
```
2
8
18
32
```

---

### Example ID: 1195

**Description:** A basic find-and-replace operation to change one word to another using a fluent, chainable syntax.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   
   // Define the rule and execute the transform in a single, chained statement.
   t.FromTo("Hello", "Greetings");
   Console.WriteLine(t.Transform("Hello World!"));

}
```

**Output:**
```
Greetings World!
```

---

### Example ID: 1196

**Description:** Safely renames a variable without corrupting a string literal, demonstrating the Transformer's token-awareness.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   
   // This rule replaces the ALPHANUMERIC token 'x', not just the character 'x'.
   t.FromTo("x", "value");

   var code = """
if (x > 10) print("Max value is x");
""";

   // The 'x' inside the string is ignored because QuoteSensitive is true by default.
   Console.WriteLine(t.Transform(code));

}
```

**Output:**
```
if (value > 10) print("Max value is x");
```

---

### Example ID: 1198

**Description:** Extracts a value from a simple key-value pair.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("ID: {value}", "Found value: {value}");
Console.WriteLine(t.Transform("Product ID: 12345"));
```

**Output:**
```
Product Found value: 12345
```

---

### Example ID: 1199

**Description:** Parses a structured log entry and reformats it for display using multiple variables.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Note the use of {@String} to capture the quoted text
t.FromTo("'['{level}']' Code: {code}, Msg: {@String:message}",
"[{level}] - {message} (Code {code})");

var log = "[ERROR] Code: 404, Msg: 'Not Found'";
Console.WriteLine(t.Transform(log));
```

**Output:**
```
[ERROR] - Not Found (Code 404)
```

---

### Example ID: 1201

**Description:** A simple example demonstrating how to find and wrap all numeric values in a string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Define a rule to find any number and wrap it in 'Num(...)'
t.FromTo("{@Number:n}", "Num({n})");

Console.WriteLine(t.Transform("var x = 10.5; var y = 20;"));
```

**Output:**
```
var x = Num(10.5); var y = Num(20);
```

---

### Example ID: 1204

**Description:** A basic pattern demonstrating how an optional word affects the match.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("Log [ERROR] entry", "MATCHED");

// This matches because the optional word is present
Console.WriteLine(t.Transform("Log ERROR entry found."));

// This also matches because the word is optional
Console.WriteLine(t.Transform("Log entry found."));
```

**Output:**
```
MATCHED found.
MATCHED found.
```

---

### Example ID: 1205

**Description:** Parses log entries to extract an optional error code, providing a default status when it's missing by using the `{!var:...}` fallback syntax.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Pattern: Match "Log:", an optional level, and the message.
// Replacement: Use `{!level:INFO}` to insert 'INFO' if {level} is empty.
t.FromTo("Log: [{level: ERROR | WARN}] {msg}",
"Status:{!level:INFO}{level} | Msg:{msg}");

// Case 1: Level is present
Console.WriteLine(t.Transform("Log: ERROR File not found"));

// Case 2: Level is missing, so the fallback is used
Console.WriteLine(t.Transform("Log: System started successfully"));
```

**Output:**
```
Status:ERROR | Msg:File not found
Status:INFO | Msg:System started successfully
```

---

### Example ID: 1207

**Description:** How to match one of several possible status keywords.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("Status: { OK | Error | Pending }", "Found Valid Status");

Console.WriteLine(t.Transform("Status: OK"));
Console.WriteLine(t.Transform("Status: Error"));
Console.WriteLine(t.Transform("Status: Fail"));
```

**Output:**
```
Found Valid Status
Found Valid Status
Status: Fail
```

---

### Example ID: 1210

**Description:** A basic example demonstrating how to ignore a block of text in parentheses, preventing other rules from matching inside it.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("word", "WORD"); // Rule to uppercase 'word'
t.SkipOver("({ignore})"); // Rule to ignore content in parentheses

var text = "transform this word, but (not this word)";
Console.WriteLine(t.Transform(text));
```

**Output:**
```
transform this WORD, but (not this word)
```

---

### Example ID: 1217

**Description:** Performing a simple unit conversion from inches to centimeters using `{@Eval}`.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// Capture a number followed by 'in' and convert it.
// Note: `len` is a string, so we must use Double(len) for the calculation.
t.FromTo("{@Number:len}in", "{@Eval: Double(len) * 2.54}cm");

Console.WriteLine(t.Transform("The board is 10in long."));
```

**Output:**
```
The board is 25.4cm long.
```

---

### Example ID: 1218

**Description:** A practical example that calculates line-item totals for a list of products by capturing quantity and price.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Rule to find quantity and price, then calculate total.
// Note the explicit Double() to convert the captured numerical
// values as text into double-precision numbers for {@Eval}.
t.FromTo("Qty: {@Number:qty}, Price: {@Number:price}",
"{@Self}, Total: {@Eval: Double(qty) * Double(price)}");

var invoice = """
Item: Book, Qty: 3, Price: 15.00
Item: Pen, Qty: 10, Price: 1.50
""";

Console.WriteLine(t.Transform(invoice));
```

**Output:**
```
Item: Book, Qty: 3, Price: 15.00, Total: 45
Item: Pen, Qty: 10, Price: 1.50, Total: 15
```

---

### Example ID: 1220

**Description:** Internal Test: Verifies that `{@@Eval}` can correctly parse and evaluate an expression that is itself captured from the text.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// The variable {formula} will capture the literal text "10 * (5-2)".
// {@@Eval} then executes that text as an expression.
t.FromTo("solve({formula})", "'{formula}' is {@@Eval: formula}.");

var text = "The answer to solve(10 * (5-2))";
Console.WriteLine(t.Transform(text));
```

**Output:**
```
The answer to '10 * (5-2)' is 30.
```

---

### Example ID: 1223

**Description:** Internal Test: Implements C-style hexadecimal literals (e.g., 0xFF) by adding a new token rule and a token transformation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Define the lexical rule.
// The regex matches '0x' followed by hex digits.
// The TokenType::TokenTransform tells the parser to pre-process this token.
uc.ExpressionTokens.Add("0x[0-9a-fA-F]+", TokenType.TokenTransform);

// 2. Define the transformation rule.
// This captures the hex digits and replaces the whole token with a call to BaseConvert.
uc.TokenTransformer.FromTo("{'0x'}{val:'[0-9a-fA-F]+'}", "BaseConvert('{val}', 16)");

// 3. Now, the new literal format can be used in expressions.
Console.WriteLine(uc.Eval("0xFF + 0xA")); // 255 + 10
Console.WriteLine(uc.EvalStr("Hex(0x100)")); // Hex(256)
```

**Output:**
```
265
100
```

---

### Example ID: 1224

**Description:** Defines a custom `sum_to` operator to calculate the sum of a numeric range, demonstrating a single-word operator.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define the variables that the operator's expression will use.
uc.DefineVariable("i");
uc.DefineVariable("total");

// Define a new 'sum_to' operator at runtime, with precedence level of 50.
// It uses the built-in ForLoop function to sum numbers into the 'total' variable.
uc.DefineOperator("{start} sum_to {end} = total = 0; ForLoop(i, start, end, 1, total = total + i)", 50);

// Use the new operator. The result is stored in the 'total' variable.
uc.Eval("1 sum_to 5");

Console.WriteLine($"The sum from 1 to 5 is: {uc.Eval("total")}");
```

**Output:**
```
The sum from 1 to 5 is: 15
```

---

### Example ID: 1225

**Description:** Creates a domain-specific currency conversion syntax using the ExpressionTransformer, the correct tool for multi-word patterns.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Use the ExpressionTransformer for multi-word syntax.
var t = uc.ExpressionTransformer;

// Note: Captured variables are passed to @Eval as text
// Double() converts the text to Double a precision value
uc.Format("Result = Format('{:.2f}', Double(Result))", uc.DataTypeOf("Double"));
t.FromTo("{@Number:amount} USD to EUR", "({@Eval: Double(amount) * 0.92})");
t.FromTo("{@Number:amount} EUR to USD", "({@Eval: Double(amount) / 0.92})");

Console.WriteLine($"100 USD is approx. {uc.EvalStr("100 USD to EUR")} EUR");
Console.WriteLine($"120 EUR is approx. {uc.EvalStr("120 EUR to USD")} USD");
```

**Output:**
```
100 USD is approx. 92.00 EUR
120 EUR is approx. 130.43 USD
```

---

### Example ID: 1226

**Description:** A simple demonstration of safely renaming a variable without corrupting a string literal, a common pitfall for Regex.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// This rule only targets the alphanumeric token 'x'.
t.FromTo("x", "value");
var code = """
x = 5; print("The value of x is...");
""";
Console.WriteLine(t.Transform(code));
```

**Output:**
```
value = 5; print("The value of x is...");
```

---

### Example ID: 1227

**Description:** A real-world refactoring task to rename a function, showing how uCalc correctly ignores matches inside comments and strings by default.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// This rule replaces the ALPHANUMERIC token 'get_data', not just the text.
t.FromTo("get_data", "fetch_records");

var code = """

// Note: 'get_data' is the old function name.
results = get_data(source);
print("The 'get_data' function was called.");

""";

// The default tokenizer recognizes the comment and string literal as separate tokens,
// so the rule to replace the function name doesn't affect them.
Console.WriteLine(t.Transform(code));
```

**Output:**
```
// Note: 'get_data' is the old function name.
results = fetch_records(source);
print("The 'get_data' function was called.");
```

---

### Example ID: 1228

**Description:** Internal Test: Contrasts a token-aware uCalc replacement with a character-aware regex replacement to highlight safety.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var code = """
rate = 0.05; print("rate"); // a rate
""";

Console.WriteLine("--- uCalc Transformer (Token-Aware & Correct) ---");
var t = new uCalc.Transformer();
t.Tokens.Add("//.*", TokenType.Whitespace);
// Rule targets only the alphanumeric token 'rate'
t.FromTo("rate", "annual_rate");
Console.WriteLine(t.Transform(code));

Console.WriteLine("");
Console.WriteLine("--- Simulated Regex (Character-Aware & Incorrect) ---");
// This simulates a simple find-and-replace for the word 'rate'
// which incorrectly changes the string literal and comment.
var incorrect_result = """
annual_rate = 0.05; print("annual_rate"); // a annual_rate
""";
Console.WriteLine(incorrect_result);
```

**Output:**
```
--- uCalc Transformer (Token-Aware & Correct) ---
annual_rate = 0.05; print("rate"); // a rate

--- Simulated Regex (Character-Aware & Incorrect) ---
annual_rate = 0.05; print("annual_rate"); // a annual_rate
```

---

### Example ID: 1229

**Description:** Creates a custom `IIf` function to demonstrate basic lazy evaluation. The division-by-zero error in the unevaluated branch is safely ignored.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyIIf(uCalc.Callback cb) {
   var condition = cb.ArgBool(1);
   var thenPart = cb.ArgExpr(2);
   var elsePart = cb.ArgExpr(3);

   if (condition) {
      cb.Return(thenPart.Evaluate());
   } else {
      cb.Return(elsePart.Evaluate());
   }
}

uc.DefineFunction("MyIIf(cond As Bool, ByExpr thenExpr, ByExpr elseExpr)", MyIIf);

// The 'else' branch contains 1/0, but since the condition is true,
// it is never evaluated.
Console.WriteLine(uc.Eval("MyIIf(10 > 5, 100, 1/0)"));

// The 'then' branch contains 1/0, but it is never evaluated.
Console.WriteLine(uc.Eval("MyIIf(10 < 5, 1/0, 200)"));
```

**Output:**
```
100
200
```

---

### Example ID: 1230

**Description:** Practical: Builds a custom `Repeat` loop control structure that executes an action a specified number of times.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyRepeat(uCalc.Callback cb) {
   var count = cb.ArgInt32(1);
   var action = cb.ArgExpr(2);
   var i = 0;
   for ( i = 1; i <= count; i++) {
      action.Execute(); // Evaluate the expression on each iteration
   }
}

// Define a counter variable in the engine
uc.DefineVariable("counter = 0");

// The action 'counter++' is passed as an unevaluated expression
uc.DefineFunction("Repeat(count As Int, ByExpr action)", MyRepeat);

// Execute the custom loop
uc.Eval("Repeat(5, counter++)");

Console.Write("Final counter value: ");
Console.WriteLine(uc.Eval("counter"));
```

**Output:**
```
Final counter value: 5
```

---

### Example ID: 1231

**Description:** Internal Test: Implements a `ShortCircuitOr` function to prove that the second argument is not evaluated if the first is true, using side effects (counters) for verification.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void ShortCircuitOr(uCalc.Callback cb) {
   var arg1 = cb.ArgExpr(1);
   var arg2 = cb.ArgExpr(2);

   // Evaluate the first argument
   var result1 = arg1.EvaluateBool();

   // If the first is true, return immediately without touching the second
   if (result1) {
      cb.ReturnBool(true);
   } else {
      // Otherwise, evaluate and return the second argument's result
      cb.ReturnBool(arg2.EvaluateBool());
   }
}

static void FuncA(uCalc.Callback cb) {
   cb.uCalc.Eval("countA = countA + 1");
   cb.ReturnBool(true);
}

static void FuncB(uCalc.Callback cb) {
   cb.uCalc.Eval("countB = countB + 1");
   cb.ReturnBool(true);
}


uc.DefineVariable("countA = 0");
uc.DefineVariable("countB = 0");

uc.DefineFunction("FuncA() As Bool", FuncA);
uc.DefineFunction("FuncB() As Bool", FuncB);

uc.DefineFunction("SC_Or(ByExpr a, ByExpr b) As Bool", ShortCircuitOr);

Console.WriteLine("Calling SC_Or(FuncA(), FuncB())...");
uc.Eval("SC_Or(FuncA(), FuncB())");

Console.WriteLine($"FuncA was called {uc.Eval("countA")} time(s).");
Console.WriteLine($"FuncB was called {uc.Eval("countB")} time(s)."); // Should be 0
```

**Output:**
```
Calling SC_Or(FuncA(), FuncB())...
FuncA was called 1 time(s).
FuncB was called 0 time(s).
```

---

### Example ID: 1236

**Description:** A simple `Describe` function that uses `ByHandle` to inspect an argument's name and data type.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void DescribeArg(uCalc.Callback cb) {
   // Retrieve the Item object for the first argument.
   var item = cb.ArgItem(1);

   // Inspect the item's metadata.
   var name = item.Name;
   if (name == "") {
      name = "(literal)";
   }

   Console.WriteLine($"  - Name: {name}, Type: {item.DataType.Name}");
}

uc.DefineFunction("Describe(ByHandle arg As AnyType)", DescribeArg);
uc.DefineVariable("my_var = 100");

Console.WriteLine("Inspecting a variable:");
uc.Eval("Describe(my_var)");

Console.WriteLine("Inspecting a literal value:");
uc.Eval("Describe(123.45)");

Console.WriteLine("Inspecting a string value:");
uc.EvalStr("Describe('abc xyz')");
```

**Output:**
```
Inspecting a variable:
  - Name: my_var, Type: double
Inspecting a literal value:
  - Name: (literal), Type: double
Inspecting a string value:
  - Name: (literal), Type: string
```

---

### Example ID: 1237

**Description:** A practical, generic `Print` function that can accept any number of arguments of any type and display them in a formatted string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void PrintGeneric(uCalc.Callback cb) {
   string output = "";
   var i = 0;
   for ( i = 1; i <= cb.ArgCount(); i++) {
      // Get the item and retrieve its value as a string.
      var item = cb.ArgItem(i);
      output = output + item.ValueStr();
      if (i < cb.ArgCount()) {
         output = output + ", ";
      }
   }
   Console.WriteLine(output);
}

// Define a variadic function that accepts any number of arguments ByHandle.
uc.DefineFunction("Print(ByHandle args As AnyType...)", PrintGeneric);

uc.Eval("Print('User:', 'Alice', 'ID:', 101, 'Status:', true)");
```

**Output:**
```
User:, Alice, ID:, 101, Status:, true
```

---

### Example ID: 1239

**Description:** A simple demonstration of finding a word but only inside a specific parenthetical block.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// 1. Parent rule finds content inside parentheses.
var parentRule = t.FromTo("({body})", "({body})");

// 2. Get the local transformer for the parent.
var local_t = parentRule.LocalTransformer;

// 3. Child rule runs only inside the parentheses.
local_t.FromTo("this", "THIS");

var text = "do not find this, but (find this) and not this";
Console.WriteLine(t.Transform(text));
```

**Output:**
```
do not find this, but (find THIS) and not this
```

---

### Example ID: 1240

**Description:** A practical example that extracts all `<a>` tags, but only from within a specific `<nav>` section of an HTML document.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Ignore multi-line formatting
t.DefaultRuleSet.StatementSensitive = false;

// 1. Parent rule captures the content of the <nav> block.
var navRule = t.Pattern("<nav>{content}</nav>");

// 2. Get the local transformer for the nav block.
var local_t = navRule.LocalTransformer;

// 3. This rule will only find `<a>` tags inside the <nav> block.
local_t.Pattern("<a href={url}>{text}</a>");

var html = """
<nav>
  <a href="/home">Home</a>
  <a href="/about">About</a>
</nav>
<main>
  <p>Some text with another <a href="/other">other link</a>.</p>
</main>
""";

t.Text = html;
t.Find();

Console.WriteLine("--- Found Links (Innermost Matches Only) ---");
// Use InnermostOnly to see only the results from the local transformer.
Console.WriteLine(t.GetMatches(MatchesOption.InnermostOnly).Text);
```

**Output:**
```
--- Found Links (Innermost Matches Only) ---
<a href="/home">Home</a>
<a href="/about">About</a>
```

---

### Example ID: 1242

**Description:** Defines a simple `Add` function that is implemented by a native callback to perform addition.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MyAdd(uCalc.Callback cb) {
   var x = cb.Arg(1);
   var y = cb.Arg(2);
   cb.Return(x + y);
}

// Link the uCalc function 'Add' to the native 'MyAdd' callback.
uc.DefineFunction("Add(x, y)", MyAdd);

// Now the native code can be called from an expression.
Console.WriteLine(uc.Eval("Add(10, 5)"));
```

**Output:**
```
15
```

---

### Example ID: 1243

**Description:** Demonstrates a practical callback that retrieves a 'host application setting', simulating I/O or access to native configuration.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void GetSetting(uCalc.Callback cb) {
   // Get the name of the setting to retrieve.
   var settingName = cb.ArgStr(1);

   // In a real app, this would read from a config file, database, or registry.
   // We simulate it by evaluating another variable in the parent uCalc context.
   var value = cb.uCalc.EvalStr(settingName);

   cb.ReturnStr(value);
}

// Simulate a host application's configuration store using uCalc variables.
uc.DefineVariable("AppName = 'uCalc Demo'");
uc.DefineVariable("Version = '1.2.3'");

// Define the function that provides a bridge to the 'host'.
uc.DefineFunction("GetHostSetting(name As String) As String", GetSetting);

// Use the custom function to build a string from the host settings.
Console.WriteLine(uc.EvalStr("GetHostSetting('AppName') + ' v' + GetHostSetting('Version')"));
```

**Output:**
```
uCalc Demo v1.2.3
```

---

### Example ID: 1244

**Description:** Internal Test: A variadic function that sums only the arguments matching a specific data type name, testing argument introspection capabilities.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void SumIfType(uCalc.Callback cb) {
   var typeName = cb.ArgStr(1);
   double total = 0;
   string totalStr = "";
   var i = 0;

   // Loop through all arguments starting from the second one.
   for ( i = 2; i <= cb.ArgCount(); i++) {
      var item = cb.ArgItem(i);
      // Check if the argument's data type name matches.
      if (item.DataType.Name == "double") {
         total = total + item.Value();
      } else if (item.DataType.Name == "string") {
         totalStr = totalStr + item.ValueStr();
      }
   }

   if (typeName == "double") {
      totalStr = total.ToString();
   }
   cb.ReturnStr(totalStr);
}

// Define the variadic function.
uc.DefineFunction("SumIfType(typeName As String, ByHandle other As AnyType ...) As String", SumIfType);

// This call will sum only the double values (5.0 and 10.123456), ignoring the integer.
Console.WriteLine(uc.EvalStr("SumIfType('double', 5.0, 'Hello ', 10.123456, 'world!')"));

// This call will concatinate only the string values.
Console.WriteLine(uc.EvalStr("SumIfType('string', 5.0, 'Hello ', 10.123456, 'world!')"));
```

**Output:**
```
15.123456
Hello world!
```

---

### Example ID: 1248

**Description:** A practical example of `ByRef` to create a classic `Swap` function that modifies its arguments in the caller's scope.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void SwapValues(uCalc.Callback cb) {
   // Get the item handles for the two variables passed by reference
   var item1 = cb.ArgItem(1);
   var item2 = cb.ArgItem(2);

   // Use the item's DataType object to perform a highly efficient, pointer-based swap
   item1.DataType.SwapScalarValues(item1.ValueAddr(), item2.ValueAddr());
}

// Define the Swap function with ByRef parameters
uc.DefineFunction("Swap(ByHandle a, ByHandle b)", SwapValues);

// Define the variables to be swapped
uc.DefineVariable("x = 100");
uc.DefineVariable("y = 200");

Console.WriteLine($"Before: x = {uc.Eval("x")}, y = {uc.Eval("y")}");

// Call the swap function
uc.Eval("Swap(x, y)");

Console.WriteLine($"After:  x = {uc.Eval("x")}, y = {uc.Eval("y")}");
```

**Output:**
```
Before: x = 100, y = 200
After:  x = 200, y = 100
```

---

### Example ID: 1249

**Description:** Demonstrates `ByExpr` to create a custom `Assert` function where the error message is only evaluated if the assertion fails, improving performance.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void Assert(uCalc.Callback cb) {
   var condition = cb.ArgBool(1);

   // If the condition is false, then we evaluate the message expression
   if (condition == false) {
      var errorMessage = cb.ArgExpr(2);
      Console.WriteLine($"Assertion failed: {errorMessage.EvaluateStr()}");
   }
}

uc.DefineVariable("x = 50");

// The message is passed as an unevaluated expression
uc.DefineFunction("Assert(condition As Bool, ByExpr message As String)", Assert);

// This will do nothing because the condition is true
uc.Eval("Assert(10 < 20, 'This will not be evaluated')");

// This will trigger the assertion and evaluate the message expression
uc.Eval("Assert(x > 100, 'x (' + Str(x) + ') is not greater than 100')");
```

**Output:**
```
Assertion failed: x (50) is not greater than 100
```

---

### Example ID: 1250

**Description:** A practical example of `ByHandle` to create a `TypeOf` function that introspects an argument and returns its data type name as a string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void GetTypeOf(uCalc.Callback cb) {
   // Get the Item object for the argument
   var item = cb.ArgItem(1);

   // Get the item's DataType, then its name, and return it as a string
   cb.ReturnStr(item.DataType.Name);
}

// The ByHandle modifier passes the argument's metadata (Item) instead of its value
uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", GetTypeOf);

uc.DefineVariable("myInt As Int = 10");
uc.DefineVariable("myStr As String = 'hello'");
uc.DefineVariable("myDbl = 3.14"); // Type is inferred as double

Console.WriteLine($"Type of myInt: {uc.EvalStr("TypeOf(myInt)")}");
Console.WriteLine($"Type of myStr: {uc.EvalStr("TypeOf(myStr)")}");
Console.WriteLine($"Type of myDbl: {uc.EvalStr("TypeOf(myDbl)")}");
```

**Output:**
```
Type of myInt: int
Type of myStr: string
Type of myDbl: double
```

---

### Example ID: 1255

**Description:** Shows the RAII pattern in C++ using a stack-allocated object and the `Owned()` method for automatic cleanup.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();


// This example demonstrates C++ specific RAII.
Console.WriteLine("Inside C++ scope: 100");
Console.WriteLine("Outside C++ scope, instance is released.");

```

**Output:**
```
Inside C++ scope: 100
Outside C++ scope, instance is released.
```

---

### Example ID: 1257

**Description:** A simple find-and-replace operation using the fluent, chainable API.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("The quick brown fox.")) {
   
   // Replace returns the modified String object, but also modifies it in-place
   s.Replace("brown", "red");

   // Use implicit conversion to print the result
   Console.WriteLine(s);
};
```

**Output:**
```
The quick red fox.
```

---

### Example ID: 1260

**Description:** A succinct example demonstrating a simple chain of two replacement actions on the root string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("A and C")) {
   
   // Each Replace() call returns the modified string object, allowing the next call.
   s.Replace("A", "B").Replace("C", "D");

   Console.Write("Result: ");
   Console.WriteLine(s);
};
```

**Output:**
```
Result: B and D
```

---

### Example ID: 1263

**Description:** A simple word replacement to demonstrate the basic find-and-replace capability.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   t.FromTo("red", "blue");
   Console.WriteLine(t.Transform("The red car and the red house."));
};
```

**Output:**
```
The blue car and the blue house.
```

---

### Example ID: 1264

**Description:** Demonstrates the Transformer's token-aware safety by correctly renaming a variable without corrupting a string literal or comment.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();

// Turn single-line comments into whitespace tokens (to be ignored)
t.Tokens.Add("//.*", TokenType.Whitespace);

// Define a rule to replace the alphanumeric token 'x' with 'value'
t.FromTo("x", "value");

var code = "x = 10; print('The max value is x.'); // x is 10 here";

// The Transformer correctly identifies that only the first 'x' is
// a token on its own. Imbedded occurrences of 'x' are left alone.
Console.WriteLine(t.Transform(code));
```

**Output:**
```
value = 10; print('The max value is x.'); // x is 10 here
```

---

### Example ID: 1265

**Description:** LIFO (Last-In, First-Out) precedence of rules with overlapping anchors.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   var text = "An apple, an apple pie, and an apple cider.";

   // Rule 1 (Lowest precedence for this anchor)
   t.FromTo("an apple", "[FRUIT]");

   // Rule 2 (Higher precedence)
   t.FromTo("an apple pie", "[DESSERT]");

   // The transformer will match "an apple pie" first because it was defined last.
   // For the remaining "an apple" occurrences, it will fall back to the first rule.
   Console.WriteLine(t.Transform(text));
};
```

**Output:**
```
[FRUIT], [DESSERT], and [FRUIT] cider.
```

---

### Example ID: 1266

**Description:** A simple calculation to convert a temperature from Celsius to Fahrenheit, demonstrating basic arithmetic and order of operations.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
Console.WriteLine(uc.EvalStr("(37) * (9 / 5) + 32"));
```

**Output:**
```
98.6
```

---

### Example ID: 1267

**Description:** Calculates a monthly loan payment by defining a custom function with the standard amortization formula, showcasing a practical, real-world use case.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define a function for the standard loan payment formula
uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100");

// Define variables for the calculation
uc.DefineVariable("monthly_rate = 0.05 / 12"); // 5% annual rate
uc.DefineVariable("periods = 30 * 12");      // 30 years
uc.DefineVariable("loan_amount = 200000");   // $200,000

Console.WriteLine(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)"));
```

**Output:**
```
1073.64
```

---

### Example ID: 1269

**Description:** Extracts the key from a simple key-value pair.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("user:admin")) {
   var key = s.Before(":");
   Console.WriteLine(key);
}
```

**Output:**
```
user
```

---

### Example ID: 1270

**Description:** Chains `Before` and `Replace` to modify only the scheme of a URL, demonstrating the live view concept.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var url = new uCalc.String("http://example.com")) {
   Console.WriteLine($"Original URL: {url}");
   // Get a view of the scheme part
   var schemeView = url.Before("://");
   // Modify the view
   schemeView.Replace("http", "https");
   // The original string is updated
   Console.WriteLine($"Modified URL: {url}");
}
```

**Output:**
```
Original URL: http://example.com
Modified URL: https://example.com
```

---

### Example ID: 1271

**Description:** Internal Test: Tests edge cases for patterns that are not found or are at the start of the string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("A B C")) {
   
   // Case 1: Pattern is at the start. Should return an empty string.
   Console.Write("Before 'A': '");
   Console.Write(s.Before("A"));
   Console.WriteLine("'");

   // Case 2: Pattern does not exist. Should return an empty string.
   Console.Write("Before 'D': '");
   Console.Write(s.Before("D"));
   Console.WriteLine("'");

   // Case 3: Get text before the last word.
   Console.Write("Before 'C': '");
   Console.Write(s.Before("C"));
   Console.WriteLine("'");
}
```

**Output:**
```
Before 'A': ''
Before 'D': ''
Before 'C': 'A B '
```

---

### Example ID: 1272

**Description:** How to extract text contained within a pair of parentheses.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("Data (important) more data")) {
   
   // Get the text between the opening and closing parenthesis
   var content = s.Between("(", ")");

   Console.WriteLine(content);
}
```

**Output:**
```
important
```

---

### Example ID: 1273

**Description:** A practical example of parsing a value from a simple key-value pair in a configuration string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("User: admin; Role: user; Department: Sales;")) {
   
   // Extract the text between 'Department: ' and the trailing semicolon
   var department = s.Between("Department: ", ";");

   Console.WriteLine($"Department is '{department}'");
}
```

**Output:**
```
Department is ' Sales'
```

---

### Example ID: 1275

**Description:** Extracting a parenthetical expression, including the parentheses.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("Calculate (10 * 5) and ignore this.")) {
   
   // Get the text from the opening parenthesis to the closing one.
   var expression = s.BetweenInclusive("(", ")");

   Console.WriteLine(expression);
}
```

**Output:**
```
(10 * 5)
```

---

### Example ID: 1276

**Description:** A practical example of extracting a complete HTML tag and its content from a string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("Some text <p>This is a paragraph.</p> more text.")) {
   
   // Extract the entire paragraph tag, including its start and end tags.
   var p_tag = s.BetweenInclusive("<p>", "</p>");

   Console.WriteLine(p_tag);
}
```

**Output:**
```
<p>This is a paragraph.</p>
```

---

### Example ID: 1277

**Description:** Internal Test: Verifies the 'live view' behavior by modifying an extracted block and showing the change reflected in the parent string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("root [child] end")) {
   
   // Get a live view of the block including the brackets
   var view = s.BetweenInclusive("'['", "']'");

   Console.WriteLine($"Initial parent string: {s}");
   Console.WriteLine($"Initial view: {view}");

   // Modify the view. The change will propagate to the parent.
   view.Replace("child", "MODIFIED");

   Console.WriteLine($"Final parent string: {s}");
}
```

**Output:**
```
Initial parent string: root [child] end
Initial view: [child]
Final parent string: root [MODIFIED] end
```

---

### Example ID: 1278

**Description:** A simple example extracting the latter part of a sentence starting from a specific word.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("This is just a test")) {
   
   // Returns a view from 'just' to the end
   var result = s.StartingFrom("just");

   Console.WriteLine(result);
}
```

**Output:**
```
just a test
```

---

### Example ID: 1279

**Description:** Extracts all log entries from the second 'ERROR' onwards, demonstrating how the `occurrence` parameter skips initial matches.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var log = new uCalc.String("INFO: OK. ERROR: Fail 1. INFO: OK. ERROR: Fail 2.")) {
   
   // Find the second occurrence of "ERROR" and get everything after it.
   var remainingLog = log.StartingFrom("ERROR", 2);

   Console.WriteLine(remainingLog);
}
```

**Output:**
```
ERROR: Fail 2.
```

---

### Example ID: 1296

**Description:** A quick start example showing defining a variable, a function, and evaluating an expression.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 10");
uc.DefineFunction("DoubleThis(n) = n * 2");

Console.WriteLine(uc.Eval("DoubleThis(x) + 5"));
```

**Output:**
```
25
```

---

### Example ID: 1312

**Description:** Finding all occurrences of a word, getting the total count, and displaying the text of the first match.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   t.Text = "apple banana apple cherry";
   t.Pattern("apple");
   t.Find();

   var m = t.Matches;
   Console.WriteLine($"Matches found: {m.Count()}");
   if (m.Count() > 0) {
      Console.WriteLine($"First match: {m[0].Text}");
   }
};
```

**Output:**
```
Matches found: 2
First match: apple
```

---

### Example ID: 1330

**Description:** A "Hello World" example showing how to define a single DSL command and process a one-line script.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Define the account balance variable
uc.DefineVariable("balance = 100.0");

// 2. Get the expression transformer and define a single rule
var t = uc.ExpressionTransformer;
t.FromTo("DEPOSIT {@Number:amount}", "balance = balance + {amount}");

// 3. Process a single-line script.
// This gets transformed to "balance = balance + 500" and executed.
uc.EvalStr("DEPOSIT 500");

// 4. Print the final balance
Console.WriteLine($"Final Balance: {uc.EvalStr("balance")}");
```

**Output:**
```
Final Balance: 600
```

---

### Example ID: 1331

**Description:** The complete financial DSL processing a multi-line script of deposits, withdrawals, and interest calculation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Initialize the account balance
uc.DefineVariable("balance = 0.0");

// 2. Define the DSL rules on the expression transformer
var t = uc.ExpressionTransformer;
t.FromTo("DEPOSIT {@Number:amount}", "balance = balance + {amount}");
t.FromTo("WITHDRAW {@Number:amount}", "balance = balance - {amount}");
t.FromTo("INTEREST {@Number:rate}", "balance = balance * (1 + {rate} / 100.0)");

// 3. Define the multi-line transaction script
var script = """

DEPOSIT 1000.00
WITHDRAW 50.75
INTEREST 0.5
WITHDRAW 200.00

""";

Console.WriteLine($"Initial Balance: {uc.Eval("balance")}");
Console.WriteLine("Processing script...");

// 4. Evaluate the entire script.
// Note: EvalStr returns the result of the LAST line.
// The intermediate lines modify the 'balance' variable.
uc.EvalStr(script);

// 5. Get the final balance
Console.WriteLine($"Final Balance: {uc.EvalStr("balance")}");
```

**Output:**
```
Initial Balance: 0
Processing script...
Final Balance: 753.99625
```

---

### Example ID: 1332

**Description:** Internal Test: An advanced example that adds logging to each transaction to trace the balance changes, showing how DSLs can be combined with custom functions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void LogBalance(uCalc.Callback cb) {
   // Get the message and the current balance to log
   var msg = cb.ArgStr(1);
   var bal = cb.uCalc.Eval("balance");
   Console.WriteLine($"[LOG] {msg} | New Balance: {bal}");
}


// 1. Initialize the balance and the logger function
uc.DefineVariable("balance = 0");
uc.DefineFunction("LOG(msg As String)", LogBalance);

// 2. Define DSL rules that also call the LOG function
var t = uc.ExpressionTransformer;

// Each rule now has a side effect: logging its action.
t.FromTo("DEPOSIT {@Number:amount}",
"balance = balance + {amount}; LOG('Deposited {amount}')");
t.FromTo("WITHDRAW {@Number:amount}",
"balance = balance - {amount}; LOG('Withdrew {amount}')");

// 3. A longer script to test the log
var script = """

DEPOSIT 500
WITHDRAW 100
DEPOSIT 250
WITHDRAW 75

""";

Console.WriteLine("--- Transaction Log ---");
uc.EvalStr(script);
Console.WriteLine("-----------------------");

Console.WriteLine($"Final Balance: {uc.Eval("balance")}");
```

**Output:**
```
--- Transaction Log ---
[LOG] Deposited 500 | New Balance: 500
[LOG] Withdrew 100 | New Balance: 400
[LOG] Deposited 250 | New Balance: 650
[LOG] Withdrew 75 | New Balance: 575
-----------------------
Final Balance: 575
```

---

### Example ID: 1335

**Description:** Demonstrates how a Transformer is created from a uCalc instance and used to apply Rules to text.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// 1. The uCalc instance (uc) is the factory

// 2. Create a Transformer from the instance
using (var t = new uCalc.Transformer(uc)) {
   // 3. Define a Rule on the transformer
   t.FromTo("apple", "FRUIT");

   // 4. Process text and get the result
   Console.WriteLine(t.Transform("An apple a day."));
};
```

**Output:**
```
An FRUIT a day.
```

---

### Example ID: 1336

**Description:** Shows the creation of a uCalc.String and its use of a fluent, token-aware API to modify text in-place.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Create a uCalc.String with a parent uCalc instance
using (var s = new uCalc.String(uc, "The user is <admin>.")) {
   // 2. Use the fluent, token-aware API
   s.After("is").Between("<", ">").ToUpper();

   // 3. The original string is modified in-place
   Console.WriteLine(s);
};
```

**Output:**
```
The user is <ADMIN>.
```

---

### Example ID: 1338

**Description:** Extracts all numbers from a string, demonstrating the simplicity of the `{@Number}` category matcher.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   t.FromTo("{@Number:n}", "[NUM:{n}]");

   var text = "Order 123 has 2 items for 49.95 total.";
   Console.WriteLine(t.Transform(text));
};
```

**Output:**
```
Order [NUM:123] has [NUM:2] items for [NUM:49.95] total.
```

---

### Example ID: 1341

**Description:** Checks for the existence of a required header in a string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   var text_ok = "Header: OK";
   var text_fail = "Header: ERROR";

   // This rule only matches if the status is "OK"
   t.Pattern("Header: OK");

   // Find() returns the transformer, so we can chain Matches().Count()
   if (t.SetText(text_ok).Find().Matches.Count() > 0) {
      Console.WriteLine("text_ok is valid.");
   }

   if (t.SetText(text_fail).Find().Matches.Count() == 0) {
      Console.WriteLine("text_fail is invalid.");
   }
}
```

**Output:**
```
text_ok is valid.
text_fail is invalid.
```

---

### Example ID: 1342

**Description:** Practical: Validates a configuration file format by enforcing the number of times specific keys must appear.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var validator = new uCalc.Transformer()) {
   
   // Rule 1: Must contain exactly one 'Host' setting.
   var hostRule = validator.Pattern("Host: {@Alpha}").SetMinimum(1).SetMaximum(1);

   // Rule 2: Must contain at least one 'Port' setting.
   var portRule = validator.Pattern("Port: {@Number}").SetMinimum(1);

   var configFile_OK = """

Host: server1
Port: 80
Port: 443

""";
   var configFile_FAIL = "Port: 80"; // Missing Host

   Console.WriteLine("--- Testing Valid Config ---");
   validator.SetText(configFile_OK).Find();
   if (hostRule.Matches.Count() > 0 && portRule.Matches.Count() > 0) {
      Console.WriteLine("Config file is valid.");
   } else {
      Console.WriteLine("Config file is invalid.");
   }
   Console.WriteLine();
   Console.WriteLine("--- Testing Invalid Config ---");
   validator.SetText(configFile_FAIL).Find();
   // The Minimum(1) on hostRule causes it to have 0 matches if none are found.
   if (hostRule.Matches.Count() > 0 && portRule.Matches.Count() > 0) {
      Console.WriteLine("Config file is valid.");
   } else {
      Console.WriteLine("Config file is invalid.");
      if (hostRule.Matches.Count() == 0) {
         Console.WriteLine($"- Reason: Host rule failed (found {hostRule.Matches.Count()}, expected 1).");
      }
   }
}
```

**Output:**
```
--- Testing Valid Config ---
Config file is valid.

--- Testing Invalid Config ---
Config file is invalid.
- Reason: Host rule failed (found 0, expected 1).
```

---

### Example ID: 1347

**Description:** A complete, single-pass transformer that converts headers, list items, bold, and italic Markdown syntax to HTML.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Setup the Transformer
using (var t = new uCalc.Transformer()) {
   t.DefaultRuleSet.RewindOnChange = true;

   // 2. Define Rules (General rules first, specific rules last for LIFO precedence)

   // -- Inline rules --
   // Italic is defined before Bold, giving Bold higher precedence.
   t.FromTo("*{text}*", "<i>{text}</i>");
   t.FromTo("**{text}**", "<b>{text}</b>");

   // -- Block-level rules --
   t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>");
   t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>");

   // 3. Define the input Markdown text
   var markdown = """

# Main Header

* First list item
* Second list item with **bold** text.
* Third list item with *italic* text.

Another paragraph with **bold** and *italic*.

""";

   // 4. Run the transformation and print the result
   Console.WriteLine(t.Transform(markdown));
}
```

**Output:**
```
<h1>Main Header</h1>

<li>First list item</li>
<li>Second list item with <b>bold</b> text.</li>
<li>Third list item with <i>italic</i> text.</li>

Another paragraph with <b>bold</b> and <i>italic</i>.
```

---

### Example ID: 1354

**Description:** A simple find-and-replace to convert inches to centimeters using a single ExpressionTransformer rule.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Get the transformer that pre-processes expressions.
var t = uc.ExpressionTransformer;

// Define a rule to find "X in to cm" and replace it with the calculated value.
// Note: 'val' is captured as text and must be converted to a number with Double().
t.FromTo("{@Number:val} in to cm", "({@Eval: Double(val) * 2.54})");

// Use the new syntax directly in an expression.
Console.WriteLine(uc.EvalStr("10 in to cm"));
```

**Output:**
```
25.4
```

---

### Example ID: 1355

**Description:** A generic conversion system that uses a single transformer rule and a callback to dynamically look up conversion factors stored in variables.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void ConvertUnits(uCalc.Callback cb) {
   var  value = cb.Arg(1);
   var fromUnit = cb.ArgStr(2);
   var toUnit = cb.ArgStr(3);

   // Construct the variable names for direct and inverse factors
   var factorName = fromUnit + "_to_" + toUnit;
   var inverseFactorName = toUnit + "_to_" + fromUnit;

   var uc_instance = cb.uCalc;

   // Try to find the direct conversion factor
   var factorItem = uc_instance.ItemOf(factorName);
   if (factorItem.NotEmpty()) {
      cb.Return(Math.Round(value * factorItem.Value(), 4));
      return;
   }

   // If not found, try to find the inverse factor and use its reciprocal
   var inverseFactorItem = uc_instance.ItemOf(inverseFactorName);
   if (inverseFactorItem.NotEmpty()) {
      cb.Return(value / inverseFactorItem.Value());
      return;
   }

   // If no factor is found, raise an error
   cb.Error.Raise("Conversion factor not found for " + fromUnit + " to " + toUnit);
}

// Define the conversion factors as variables
uc.DefineVariable("in_to_cm = 2.54");
uc.DefineVariable("km_to_miles = 0.621371");

// Define a custom function for temperature, since it's not a simple multiplication
uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0");

// Register our generic conversion callback
uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", ConvertUnits);

// Create generic rules in the expression transformer
var t = uc.ExpressionTransformer;
t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')");
// A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last)
t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})");

Console.WriteLine($"10 in to cm = {uc.Eval("10 in to cm")}");
Console.WriteLine($"100 km to miles = {uc.Eval("100 km to miles")}");

// Test the inverse conversion, which the callback handles automatically
Console.WriteLine($"254 cm to in = {uc.Eval("254 cm to in")}");
Console.WriteLine($"98.6 F to C = {uc.Eval("98.6 F to C")}");
```

**Output:**
```
10 in to cm = 25.4
100 km to miles = 62.1371
254 cm to in = 100
98.6 F to C = 37
```

---

### Example ID: 1357

**Description:** A complete, working command-line REPL that reads user input, evaluates it with uCalc, and prints the result or any error messages.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// This example simulates a full REPL session by iterating through a series of inputs.
Console.WriteLine("uCalc Interactive Shell (simulated session)");
Console.WriteLine("Type 'exit' or 'quit' to end.");
Console.WriteLine("");

string[] inputs = {
   "10 * (5 + 3)",
   "UCase('hello world')",
   "1 / 0",
   "1 +",
   "exit"
};

var index = 0;

do {
   Console.Write("> ");

   // Simulate reading from the console by assigning inputs sequentially.
   // In a real application, this would read the input interactively from the console.
   var input = inputs[index];

   Console.WriteLine(input);

   // 1. Check for an exit command
   if (input == "exit" || input == "quit") {
      Console.WriteLine("Exiting.");
      return ;
   }

   // 2. Evaluate the input and 3. Print the result
   Console.WriteLine(uc.EvalStr(input));
   Console.WriteLine("");

   index = index + 1;
} while (true);
```

**Output:**
```
uCalc Interactive Shell (simulated session)
Type 'exit' or 'quit' to end.

> 10 * (5 + 3)
80

> UCase('hello world')
HELLO WORLD

> 1 / 0
inf

> 1 +
Syntax error

> exit
Exiting.
```

---

### Example ID: 1358

**Description:** Three core SDK components performing their primary functions independently.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Expression Parser: Evaluate a simple math or string expression
Console.WriteLine($"Parser Result: {uc.Eval("(100 - 50) / 2")}");
Console.WriteLine($"Parser Result (string): {uc.EvalStr("'Hello ' + 'World'")}");

// 2. Transformer: Perform a basic find-and-replace
var t = new uCalc.Transformer();
t.FromTo("Hello", "Hi");
t.FromTo("World", "Planet");
t.SkipOver("/* {comment} */");
Console.WriteLine($"Transformer Result: {t.Transform("Hello World /* Was Hello World */")}");

// 3. String Library: Use a fluent, chainable operation
uCalc.String s = "The value is: important";
s.After(":").ToUpper();
Console.WriteLine($"String Library Result: {s}");


```

**Output:**
```
Parser Result: 25
Parser Result (string): Hello World
Transformer Result: Hi Planet /* Was Hello World */
String Library Result: The value is: IMPORTANT
```

---

### Example ID: 1359

**Description:** A practical, real-world example of integration: using the Transformer and Expression Parser together to create a simple template engine that replaces placeholders with evaluated data.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define the data context for our template
uc.DefineVariable("user = 'Alice'");
uc.DefineVariable("score = 95");

// Define the template with placeholders
var myTemplate = "User: {user}, Score: {score * 10}, Status: {IIf(score > 90, 'Excellent', 'Good')}";

var t = uc.NewTransformer();
// This single rule finds placeholders like {...}
// and uses the Expression Parser ({@@Eval}) to evaluate the content inside.
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");

Console.WriteLine(t.Transform(myTemplate));

```

**Output:**
```
User: Alice, Score: 950, Status: Excellent
```

---

### Example ID: 1361

**Description:** Translation of pseudocode to C++, C#, and VB for Gemini prompt

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Rosetta Stone
// Pseudocode translation to C++, C#, or VB

// This shows only in C#

//This shows in C# and VB, not C++

//This shows in C++ and C#, not Vb
//The c tag is the same as the NotVB tag
// Tags (c, cpp, cs, vb, NotCpp, NotCs, NotVb, etc.,) are not case-sensitive

Console.Write("w() prints text without ");
Console.Write("a new line at the end.");
Console.WriteLine(); // Moves to a new line
Console.WriteLine("wl() prints a line, ending with a newline.");
Console.WriteLine("Line 2");
Console.WriteLine("Line 3");
Console.WriteLine($"{123} multiple args for wl()");
Console.Write("multiple "); Console.Write("args "); Console.Write("for w() too");
Console.WriteLine("");

var t = uc.NewTransformer();
// Property setter syntax: @ followed by property name and value in parenthesis
t.Description = "Some description goes here";

// Property getter sytanx: @ followed by property name, and empty parenthesis
Console.WriteLine(t.Description);

// Each property has an alternative getter and setter function syntax
// with the Get or Set prefix like this:
t.SetDescription("A new description");
Console.WriteLine(t.GetDescription());

// Using the alternative function syntax for a property can be useful when chaining calls
// I use the c tag for the sake of VB that wants everything on the same line.
t.SetText("Some Text").SetDescription("Some description")
.FromTo("Text", "String").SetCaseSensitive(true).SetMinimum(1).SetMaximum(5)
.GetParentTransformer().Transform();
Console.WriteLine(t.Text);

// For compatibility across C++, C#, and VB, use the Verbatim tag for multi-line
// strings.  Do not use escapes or specialized double-quote syntax in a string.
var MyString = """
Here is some "quoted" text on one line
And some random text on another line
""";
Console.WriteLine(MyString);

// Use this syntax to define a variable with a uCalc-related type
// Either with or without an initial value
uCalc.String MyStringA;
uCalc.String MyStringB = "This is some text.";
MyStringA = MyStringB.Text + " Some more text";
Console.WriteLine(MyStringA.Text);

// For simple types not belonging to uCalc, use this C#-like notation instead:

var OtherString = "Some other string ";
var MyNumber = 12345;
Console.WriteLine($"{OtherString}{MyNumber}");

// Another way to define a new variable (with a uCalc type) is with the more
// flexible New.  Use this especially if you need to use arguments:

var MyVar = new uCalc.Item("Variable: x = 123");
var MyFunc = new uCalc.Item(uc, "Function: f(x) = x^2");
Console.WriteLine(uCalc.DefaultInstance.Eval("x"));
Console.WriteLine(uc.Eval("f(5)"));

// To define a uCalc object that gets released when the object goes out of scope, do:
using (var tr = new uCalc.Transformer()) {
   tr.FromTo("This", "That");
   Console.WriteLine(tr.Transform("This car").Text);
   // To accomodate other languages besides C#, you must explicitely end the using block
}

// Use the C++ style to_string to convert a value to a string
Console.WriteLine("Value: " + (100 + 25).ToString());

// Always use the C++ double colon, ::, for scope resolution
// (it gets translated to a dot, ., in C# and VB
var MyTokens = t.Tokens;
Console.WriteLine(uc.DataTypeOf(BuiltInType.Float_Double).Name);

// Other supported constructs
for (double x = 1; x <= 10; x++) {
   Console.WriteLine(x);
}

for (double x = 1; x <= 10; x = x + 2) {
   Console.WriteLine(x);
}

foreach(var dType in uc.DataTypes) {
   Console.WriteLine(dType.Name);
}

var count = 0;

while (count <= 5) {
   Console.WriteLine(count);
   count += 1;
}

do {
   Console.WriteLine(count);
   count = count + 1;
} while (count <= 10);

if (count < 100) {
   Console.WriteLine("count is less than 100");
}

if (count < 5) {
   // Some lines of code
   Console.WriteLine("count is less than 5");
} else if (count <= 50) {
   // . . .
   Console.WriteLine("count is less than or equal to 50");
} else {
   // More lines of code
   Console.WriteLine("count is greater than 50");
}

// Declare and initialize a string array
string[] items = {"Apple", "Banana", "Cherry"};

// Get the size of the array
count = items.Length;
Console.WriteLine($"Total items: {count}");

// Access and modify elements
Console.WriteLine($"First item: {items[0]}");
items[1] = "Blueberry";

// Iterate through the array
var i = 0;
do {
   Console.WriteLine(items[i]);
   i = i + 1;
} while (i < items.Length);

// For proper translation into the 3 supported languages, wrap Boolean values with
// bool.  When pseudocode contains the bool function, a helper function named tf is
// inserted towards to the top of the code

Console.WriteLine($"{uc.EvalStr("'Cos is a function? '")}{uc.ItemOf("Cos").IsProperty(ItemIs.Function)}");
Console.WriteLine($"{uc.EvalStr("'Cos is a variable? '")}{uc.ItemOf("Cos").IsProperty(ItemIs.Variable)}");
```

**Output:**
```
w() prints text without a new line at the end.
wl() prints a line, ending with a newline.
Line 2
Line 3
123 multiple args for wl()
multiple args for w() too
Some description goes here
A new description
Some String
Here is some "quoted" text on one line
And some random text on another line
This is some text. Some more text
Some other string 12345
123
25
That car
Value: 125
double
1
2
3
4
5
6
7
8
9
10
1
3
5
7
9
anytype
bool
bool
int8u
complex
double
single
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
omnitype
pointer
sametypeas
single
size_t
string
void
0
1
2
3
4
5
6
7
8
9
10
count is less than 100
count is less than or equal to 50
Total items: 3
First item: Apple
Apple
Blueberry
Cherry
Cos is a function? True
Cos is a variable? False
```

---

### Example ID: 1362

**Description:** How to define an error handler callback

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// The head, body, callback, and callback:u tags should only be used when the code contains a callback.
// There are two types of callbacks.  callback:u is for error handling, while callback is for expression
// functions and operators.  They both close with /callback.
static void MyErrorHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("An error has occurred!");
   Console.WriteLine($"Error #: {(int)uc.Error.Code}");
   Console.WriteLine($"Error Message: {uc.Error.Message}");
   Console.WriteLine($"Error Symbol: {uc.Error.Symbol}");
   Console.WriteLine($"Error Location: {uc.Error.Location}");
   Console.WriteLine($"Error Expression: {uc.Error.Expression}");
}


uc.Error.AddHandler(MyErrorHandler);
Console.WriteLine(uc.EvalStr("123+"));
Console.WriteLine("");

uc.Error.TrapOnDivideByZero = true;
Console.WriteLine(uc.EvalStr("5/0"));
// Note: The head and body tags do NOT come in pairs. Those tags separate sections of code.
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 1364

**Description:** Returns the default list of tokens (index, description, name, regex) in a transformer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
Console.WriteLine($"Token Count: {t.Tokens.Count}");
Console.WriteLine("");
Console.WriteLine("Index  Type  Name: regex");
Console.WriteLine("========================");

foreach(var token in t.Tokens) {
   Console.Write(t.Tokens.IndexOf(token));
   Console.WriteLine($"  {token.Description}  {token.Name}: {token.Regex}");
}
```

**Output:**
```
Token Count: 27

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 1365

**Description:** Simulates the core logic of a calculator, showing how user input is built into an expression string and evaluated.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
string display_text = "";

// Simulate user pressing buttons: 1, 2, 3, +, 4, 5, 6
display_text = display_text + "123";
Console.WriteLine($"Display: {display_text}");

display_text = display_text + "+";
Console.WriteLine($"Display: {display_text}");

display_text = display_text + "456";
Console.WriteLine($"Display: {display_text}");

// Simulate pressing '='. This is where uCalc does the work.
var result = uc.EvalStr(display_text);
display_text = result;
Console.WriteLine($"Result: {display_text}");

Console.WriteLine("");

// Simulate a new calculation with an error
display_text = "5 * / 3";
Console.WriteLine($"Display: {display_text}");
result = uc.EvalStr(display_text);
display_text = result;
Console.WriteLine($"Result: {display_text}");

Console.WriteLine("");

// Simulate clearing the display
display_text = "C"; // Let's say 'C' is a special command
if (display_text == "C") {
   display_text = "";
}
Console.WriteLine($"Display after clear: '{display_text}'");
```

**Output:**
```
Display: 123
Display: 123+
Display: 123+456
Result: 579

Display: 5 * / 3
Result: Syntax error

Display after clear: ''
```

---

### Example ID: 1368

**Description:** Simple variable replacement in a template.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Define the data
uc.DefineVariable("user_name = 'Alice'");

// Define the placeholder rule
// '{' is a special character and must be escaped
t.FromTo("'{' '{' {expr} '}' '}'", "{@@Eval: expr}");

// Process the template
Console.WriteLine(t.Transform("Hello, {{ user_name }}!"));
```

**Output:**
```
Hello, Alice!
```

---

### Example ID: 1370

**Description:** Basic data cleaning by trimming whitespace and changing the case of a single key-value pair.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Rule to find 'status', capture its value, trim whitespace, and convert to uppercase.
t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}");

var input = "status=  active  ";
Console.WriteLine(t.Transform(input));
```

**Output:**
```
Status: ACTIVE
```

---

### Example ID: 1371

**Description:** A complete data sanitization pipeline that processes multiple key-value pairs, using a native callback to perform custom email validation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void IsValidEmail(uCalc.Callback cb) {
   var email = cb.ArgStr(1);
   var uc = cb.uCalc;
   // Simple validation: check for '@' and '.'
   var isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')");
   if (isValid == "true") {
      cb.ReturnBool(true);
   } else {
      cb.ReturnBool(false);
   }
}


// 1. Define the custom validation function in the uCalc engine
uc.DefineFunction("IsValidEmail(email As String) As Bool", IsValidEmail);

// 2. Create and configure the transformer
using (var t = new uCalc.Transformer(uc)) {
   // 3. Define the sanitization and validation rules
   t.FromTo("user = {val};", "User: {val},");
   t.FromTo("age = {val};", "Age: {val},");
   t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}"); // Last rule, no trailing comma

   // The email rule uses the custom function for validation
   t.FromTo("email = {val};",
   "Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},");

   // 4. Define the messy input strings
   var input1 = "user= Alice  ; age  =30 ; email= alice@ucalc.com ; status=active";
   var input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive";

   // 5. Run the transformations
   Console.WriteLine(t.Transform(input1));
   Console.WriteLine(t.Transform(input2));
};
```

**Output:**
```
User: Alice, Age: 30, Email: alice@ucalc.com (Valid), Status: ACTIVE
User: Bob, Age: 45, Email: bob-at-ucalc (INVALID), Status: INACTIVE
```

---

### Example ID: 1376

**Description:** Converting a single line of legacy variable declaration syntax to a modern equivalent.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // Rule to convert legacy variable declaration
   t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");
   Console.WriteLine(t.Transform("LET X = 100"));
}
```

**Output:**
```
var X = 100;
```

---

### Example ID: 1377

**Description:** A practical example that transpiles a multi-line legacy script, including comments, variables, and a conditional statement with a nested action.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Rules must be defined in an order that allows for proper transformation.

// 1. Comment rule
t.FromTo("REM {comment}", "// {comment}");

// 2. Variable assignment rule
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");

// 3. Print statement rule
t.FromTo("PRINT {output}", "console.log({output});");

// 4. IF...THEN rule with RewindOnChange to handle nested statements
var ifRule = t.FromTo("IF {condition} THEN {action}", """
if ({condition}) {
  {action}
}
""");
ifRule.RewindOnChange = true;

// The legacy script to transpile
var legacyScript = """
REM Initialize variables
LET X = 10
LET Y = X * 2
IF Y > 15 THEN PRINT "Value is large"
""";

// Run the transformation
Console.WriteLine(t.Transform(legacyScript));
```

**Output:**
```
// Initialize variables
var X = 10;
var Y = X * 2;
if (Y > 15) {
  console.log("Value is large");
}
```

---

### Example ID: 1379

**Description:** Automatic recalculation when a source cell is changed.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define cells A1 and B1, where B1 depends on A1
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 5");

Console.WriteLine($"Initial B1 value: {uc.Eval("B1()")}"); // Expected: 50

// Now, change the value of A1. B1 will update automatically.
uc.Define("Overwrite ~~ Function: A1() = 20");

Console.WriteLine($"Updated B1 value: {uc.Eval("B1()")}"); // Expected: 100
```

**Output:**
```
Initial B1 value: 50
Updated B1 value: 100
```

---

### Example ID: 1380

**Description:** A practical example simulating a small spreadsheet with interdependent cells.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Define interdependent 'cells' using the Overwrite command.
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

Console.WriteLine($"Initial C1: {uc.Eval("C1()")}"); // Should be 10 + (10 * 2) = 30

// Now, overwrite the source cell A1. All dependent cells should automatically update.
uc.Define("Overwrite ~~ Function: A1() = 50");

Console.WriteLine($"Updated B1: {uc.Eval("B1()")}"); // Should now be 50 * 2 = 100
Console.WriteLine($"Updated C1: {uc.Eval("C1()")}"); // Should now be 50 + 100 = 150
```

**Output:**
```
Initial C1: 30
Updated B1: 100
Updated C1: 150
```

---

### Example ID: 1381

**Description:** Internal Test: Verifies a multi-level dependency cascade where a change to a root cell propagates through several levels of dependent cells.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Internal Test: Verifying a multi-level dependency cascade.
uc.Define("Overwrite ~~ Function: BaseValue() = 2");
uc.Define("Overwrite ~~ Function: Level1() = BaseValue() * 10"); // 20
uc.Define("Overwrite ~~ Function: Level2() = Level1() + 5");    // 25
uc.Define("Overwrite ~~ Function: Level3() = Level2() * 2");    // 50

Console.WriteLine($"Initial Level3 value: {uc.Eval("Level3()")}");

// Change the root value. All levels should recalculate.
uc.Define("Overwrite ~~ Function: BaseValue() = 3");

Console.WriteLine("--- After changing BaseValue to 3 ---");
Console.WriteLine($"Updated Level1: {uc.Eval("Level1()")}"); // 3 * 10 = 30
Console.WriteLine($"Updated Level2: {uc.Eval("Level2()")}"); // 30 + 5 = 35
Console.WriteLine($"Updated Level3: {uc.Eval("Level3()")}"); // 35 * 2 = 70
```

**Output:**
```
Initial Level3 value: 50
--- After changing BaseValue to 3 ---
Updated Level1: 30
Updated Level2: 35
Updated Level3: 70
```

---

### Example ID: 1382

**Description:** A complete JSON formatter that takes a minified string and pretty-prints it with proper indentation.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer(uc)) {
   // 1. Define state variable in the uCalc instance.
   uc.DefineVariable("indent = 0");

   // 2. Define the transformation rules.
   // Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals.

   // Rule for '{' and '[': Add newline, increment indent, add indent string.
   t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: '  ' * indent}");

   // Rule for '}' and ']': Add newline, decrement indent, add indent string.
   t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: '  ' * indent}{@Self}");

   // Rule for ',': Add newline and current indent string.
   t.FromTo(",", ",{@nl}{@Eval: '  ' * indent}");

   // Rule for ':': Add a space after it for readability.
   t.FromTo(":", ": ");

   // 3. Define the minified input string.
   var minifiedJson = """
{"id":123,"name":"Example","tags":["A","B"],"active":true}
""";

   // 4. Run the transformation and print the result.
   Console.WriteLine(t.Transform(minifiedJson));
}
```

**Output:**
```
{
  "id": 123,
  "name": "Example",
  "tags": [
    "A",
    "B"
  ],
  "active": true
}
```

---

### Example ID: 1383

**Description:** A complete JSON minifier that takes a formatted string and removes all non-essential whitespace.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // 1. Define rules to remove whitespace and newlines.
   // The engine's default QuoteSensitive=true ensures whitespace inside strings is protected.
   t.FromTo("{@Whitespace}", "");
   t.FromTo("{@Newline}", "");

   // 2. Define the formatted input string.
   var formattedJson = """
{
  "id": 123,
  "name": "Example, with spaces",
  "tags": [
    "A",
    "B"
  ]
}
""";

   // 3. Run the transformation and print the result.
   Console.WriteLine(t.Transform(formattedJson));
}
```

**Output:**
```
{"id":123,"name":"Example, with spaces","tags":["A","B"]}
```

---

### Example ID: 1384

**Description:** A complete syntax highlighter that finds keywords, strings, and comments, and wraps them in pseudo-HTML tags for styling.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // 1. Define integer constants for our syntax categories
   var TAG_KEYWORD = 1;
   var TAG_STRING = 2;
   var TAG_COMMENT = 3;

   // 2. Define the transformation rules and tag them
   t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
   t.Pattern("{@String}").SetTag(TAG_STRING);
   t.Pattern("// {text}").SetTag(TAG_COMMENT);

   // 3. Set the source code and run the find operation
   string sourceCode = """
for (i=0; i<10; i++) {
  s = "hello";
  // comment
}
""";
   t.Text = sourceCode;
   t.Find();

   // 4. Build the highlighted output string
   string highlightedOutput = "";
   var lastPos = 0;

   foreach(var match in t.Matches) {
      // Append the plain text between the last match and this one
      highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos, match.StartPosition - lastPos);

      // Get the tag and wrap the matched text accordingly
      var tag = match.Rule.Tag;
      if (tag == TAG_KEYWORD) {
         highlightedOutput = highlightedOutput + "<keyword>" + match.Text + "</keyword>";
      } else if (tag == TAG_STRING) {
         highlightedOutput = highlightedOutput + "<string>" + match.Text + "</string>";
      } else if (tag == TAG_COMMENT) {
         highlightedOutput = highlightedOutput + "<comment>" + match.Text + "</comment>";
      } else {
         highlightedOutput = highlightedOutput + match.Text; // No tag, append as-is
      }

      // Update the position for the next iteration
      lastPos = match.EndPosition;
   }

   // Append any remaining text after the last match
   highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos);

   Console.WriteLine(highlightedOutput);
}
```

**Output:**
```
<keyword>for</keyword> (i=0; i<10; i++) {
  s = <string>"hello"</string>;
  <comment>// comment</comment>
}
```

---

### Example ID: 1385

**Description:** A minimal example of a DSL command to move a player piece.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("player1_position = 0");

// Define a rule to translate the MOVE command
var t = uc.ExpressionTransformer;
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}");

// Execute a single command
uc.EvalStr("PLAYER 1 MOVES 5 SPACES");

Console.WriteLine($"Player 1 is now at position: {uc.EvalStr("player1_position")}");
```

**Output:**
```
Player 1 is now at position: 5
```

---

### Example ID: 1386

**Description:** A complete game turn script demonstrating multiple DSL commands for moving, gaining resources, and drawing cards.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Define the initial game state
uc.DefineVariable("p1_pos = 0");
uc.DefineVariable("p1_gold = 10");
uc.DefineVariable("p2_pos = 0");
uc.DefineVariable("p2_gold = 10");

// 2. Define the DSL rules
var t = uc.ExpressionTransformer;
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}");
t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}");

// 3. Define the script for the turn
var game_turn_script = """

PLAYER 1 MOVES 4
PLAYER 2 MOVES 2
PLAYER 1 GAINS 5 GOLD
PLAYER 2 MOVES 3

""";

// 4. Execute the script
uc.EvalStr(game_turn_script);

// 5. Display the final state
Console.WriteLine("--- End of Turn State ---");
Console.WriteLine($"Player 1 Position: {uc.EvalStr("p1_pos")}");
Console.WriteLine($"Player 1 Gold: {uc.EvalStr("p1_gold")}");
Console.WriteLine($"Player 2 Position: {uc.EvalStr("p2_pos")}");
Console.WriteLine($"Player 2 Gold: {uc.EvalStr("p2_gold")}");
```

**Output:**
```
--- End of Turn State ---
Player 1 Position: 4
Player 1 Gold: 15
Player 2 Position: 5
Player 2 Gold: 10
```

---

### Example ID: 1388

**Description:** Extracting the status code and response time from a single log line using a simple pattern.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   string logLine = """
2024-10-26 10:00:05 INFO 192.168.1.10 "GET /api/users HTTP/1.1" 200 15ms
""";

   // Define a pattern to capture the status and time
   string pattern = "{@String:request} {@Number:status} {@Number:time}ms";

   // The replacement string formats the captured data for display
   // {request} or {request(1)} would return the string without surrounding quotes
   // {request(0)} returns the string with surrounding quotes
   string replacement = "Request: {request(0)}, Status: {status}, Time: {time}ms";

   t.FromTo(pattern, replacement);

   // Use Filter() to extract only the transformed match
   Console.WriteLine(t.Transform(logLine).Matches);
}
```

**Output:**
```
Request: "GET /api/users HTTP/1.1", Status: 200, Time: 15ms
```

---

### Example ID: 1389

**Description:** A complete log processing pipeline that parses multiple lines and calculates aggregate metrics like total requests, error count, and average response time.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Define variables to hold the metrics
uc.DefineVariable("request_count = 0");
uc.DefineVariable("error_count = 0");
uc.DefineVariable("total_response_time = 0.0");
uc.DefineVariable("max_response_time = 0.0");

// 2. Create the transformer and define the rule
using (var t = new uCalc.Transformer(uc)) {
   var pattern = "{@String:request} {@Number:status} {@Number:time}ms";

   // 3. The replacement string uses @Exec for side-effects (updating variables)
   var replacement = """

{@Exec: request_count++}
{@Exec: total_response_time = total_response_time + Double(time)}
{@Exec: max_response_time = Max(max_response_time, Double(time))}
{@Exec: iif(Double(status) >= 400, error_count++, 0)}

""";

   t.FromTo(pattern, replacement);

   // 4. Define the multi-line log data
   var logText = """

2024-10-26 10:00:05 INFO    192.168.1.10   "GET /api/users HTTP/1.1" 200 15ms
2024-10-26 10:00:06 INFO    192.168.1.15   "GET /api/products HTTP/1.1" 200 22ms
2024-10-26 10:00:07 ERROR   192.168.1.22   "POST /api/login HTTP/1.1" 500 120ms
2024-10-26 10:00:08 INFO    192.168.1.10   "GET /api/users/1 HTTP/1.1" 200 8ms

""";

   // 5. Run the transformation (the output will be empty as we only use @Exec)
   t.Transform(logText);
}

// 6. Display the final aggregated metrics
Console.WriteLine("--- Log Analysis Summary ---");
Console.WriteLine($"Total Requests: {uc.EvalStr("request_count")}");
Console.WriteLine($"Total Errors: {uc.EvalStr("error_count")}");
Console.WriteLine($"Average Response Time: {uc.EvalStr("total_response_time / request_count")}ms");
Console.WriteLine($"Maximum Response Time: {uc.EvalStr("max_response_time")}ms");
```

**Output:**
```
--- Log Analysis Summary ---
Total Requests: 4
Total Errors: 1
Average Response Time: 41.25ms
Maximum Response Time: 120ms
```

---

### Example ID: 1391

**Description:** Evaluates a complex boolean expression using uCalc's built-in operators.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("status = 'Active'");
uc.DefineVariable("login_attempts = 2");
uc.DefineVariable("is_admin = false");

var rule = "(status == 'Active' AND login_attempts < 3) OR is_admin == true";

Console.WriteLine($"Evaluating rule: {rule}");
Console.Write("Result: ");
Console.WriteLine(uc.EvalStr(rule));
```

**Output:**
```
Evaluating rule: (status == 'Active' AND login_attempts < 3) OR is_admin == true
Result: true
```

---

### Example ID: 1398

**Description:** Extracting a single key-value pair from a query string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // Define a rule to find a key-value pair
   t.FromTo("{@Alphanumeric:key}={@Alphanumeric:val}", "Key: {key}, Value: {val}");

   // Process a simple query string
   Console.WriteLine(t.Transform("user=admin"));
}
```

**Output:**
```
Key: user, Value: admin
```

---

### Example ID: 1399

**Description:** A practical, real-world parser that handles multiple key-value pairs and URL-encoded characters using a custom callback.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void URLDecode(uCalc.Callback cb) {
   // In a real application, this would be a full URL decoding implementation.
   // For this example, we'll just handle spaces (%20) and plus signs (+).
   uCalc.String s = cb.ArgStr(1);
   s.Replace("%20", " ").Replace("+", " ");
   cb.ReturnStr(s.Text);
}


// 1. Define the custom URLDecode function in the uCalc engine
uc.DefineFunction("URLDecode(s As String) As String", URLDecode);

// 2. Create the transformer and configure its tokenizer
using (var t = new uCalc.Transformer(uc)) {
   // Treat '&' as a statement separator to process each pair individually
   t.Tokens.Add("&", TokenType.StatementSep);

   // 3. Define the rule to capture key-value pairs and decode the value
   t.FromTo("{@Alphanumeric:key}={value}", "- {key}: '{@Eval: URLDecode(value)}'");

   // 4. Process a real-world query string
   var queryString = "name=John%20Doe&role=user+admin&id=123";

   // Use Filter() to get a clean, newline-separated list of the results
   Console.WriteLine(t.Transform(queryString).Matches);
}
```

**Output:**
```
- name: 'John Doe'
- role: 'user admin'
- id: '123'
```

---

### Example ID: 1401

**Description:** A basic, token-aware variable rename.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // This rule will only match the standalone token 'rate', not 'exchange_rate'.
   t.FromTo("rate", "interestRate");

   var code = "var exchange_rate = 0.5; var rate = 0.1;";
   Console.WriteLine(t.Transform(code));
}
```

**Output:**
```
var exchange_rate = 0.5; var interestRate = 0.1;
```

---

### Example ID: 1402

**Description:** A practical implementation of the code refactoring utility, safely renaming a function while ignoring occurrences in comments and strings.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// Simulate user inputs for the tool
var findText = "GetUserData";
var replaceText = "FetchUserProfile";
var sourceCode = """

// Deprecated: Use FetchUserProfile instead of GetUserData
function GetUserData(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = GetUserData(123);

""";

using (var refactorTool = new uCalc.Transformer()) {
   // 1. Define rules to ignore comments. These have the highest precedence.
   refactorTool.SkipOver("// {text}");
   refactorTool.SkipOver("/* {text} */");

   // 2. Define the replacement rule. QuoteSensitive is true by default, protecting strings.
   var rule = refactorTool.FromTo(findText, replaceText);

   // 3. Run the transformation and print the result.
   Console.WriteLine(refactorTool.Transform(sourceCode));
}
```

**Output:**
```

// Deprecated: Use FetchUserProfile instead of GetUserData
function FetchUserProfile(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = FetchUserProfile(123);

```

---

### Example ID: 1404

**Description:** A single-pass transformer that converts headers, list items, bold, and italic Markdown syntax to HTML.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   t.DefaultRuleSet.RewindOnChange = true;

   // 2. Define Rules (General rules first, specific rules last for LIFO precedence)

   // -- Inline rules --
   // Italic is defined before Bold, giving Bold higher precedence.
   t.FromTo("*{text}*", "<i>{text}</i>");
   t.FromTo("**{text}**", "<b>{text}</b>");

   // -- Block-level rules --
   t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>");
   t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>");
   t.FromTo("</li>{@nl}{@nl}", "</li>{@nl}</ul>{@nl}"); // {@nl} = NewLine
   t.FromTo("{@nl}{@nl}*{@Whitespace}", "{@nl}<ul>{@nl}* ");

   // 3. Define the input Markdown text
   var markdown = """

# Main Header

* First list item
* Second list item with **bold** text.
* Third list item with *italic* text.

Another paragraph with **bold** and *italic*.

""";

   // 4. Run the transformation and print the result
   Console.WriteLine(t.Transform(markdown));
}
```

**Output:**
```
<h1>Main Header</h1>
<ul>
<li>First list item</li>
<li>Second list item with <b>bold</b> text.</li>
<li>Third list item with <i>italic</i> text.</li>
</ul>
Another paragraph with <b>bold</b> and <i>italic</i>.
```

---

### Example ID: 1409

**Description:** Basic forward and turn commands (LOGO).

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void MoveTurtle(uCalc.Callback cb) {
   var dist = cb.Arg(1);
   var uc_inst = cb.uCalc;
   var x = uc_inst.ItemOf("x").Value();
   var y = uc_inst.ItemOf("y").Value();
   var angle = uc_inst.ItemOf("angle").Value();
   var pen_down = uc_inst.ItemOf("pen_down").ValueBool();
   int new_x = Convert.ToInt32(x + dist * uc_inst.Eval("CosD(" + (angle).ToString() + ")"));
   int new_y = Convert.ToInt32(y + dist * uc_inst.Eval("SinD(" + (angle).ToString() + ")"));
   if (pen_down) {
      Console.WriteLine($"Drawing line to ({new_x},{new_y})");
   } else {
      Console.WriteLine($"Moving to ({new_x},{new_y})");
   }
   uc_inst.ItemOf("x").Value(new_x);
   uc_inst.ItemOf("y").Value(new_y);
}


// --- Setup ---
uc.DefineVariable("x = 0.0");
uc.DefineVariable("y = 0.0");
uc.DefineVariable("angle = 90.0");
uc.DefineVariable("pen_down = false");
uc.DefineConstant("PI = 3.1415926535");
uc.DefineFunction("CosD(a) = Cos(a * PI / 180)");
uc.DefineFunction("SinD(a) = Sin(a * PI / 180)");
uc.DefineFunction("Move(dist)", MoveTurtle);

var t = uc.ExpressionTransformer;
t.FromTo("FD {@Number:dist}", "Move({dist})");
t.FromTo("RT {@Number:deg}", "angle = angle - {deg}");
t.FromTo("PD", "pen_down = true");

// --- Script ---
var script = """

PD
FD 100
RT 90
FD 50

""";

uc.EvalStr(script);

Console.WriteLine($"Final Position: ({uc.Eval("x")}, {uc.Eval("y")})");
```

**Output:**
```
Drawing line to (0,100)
Drawing line to (50,100)
Final Position: (50, 100)
```

---

### Example ID: 1415

**Description:** A complete, working natural language date parser that handles keywords, relative days, and future durations.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void GetCurrentDate(uCalc.Callback cb) {
   // In a real application, this would return the system's current date.
   // For this example, we'll use a fixed date for consistent output.
   // Let's pretend today is January 15, 2026 (a Thursday).
   cb.Return(46036); // Using Excel-style date serial number for simplicity
}

static void AddDuration(uCalc.Callback cb) {
   var startDate = cb.Arg(1);
   var number = cb.Arg(2);
   var unit = cb.ArgStr(3);
   var result = startDate;

   if (unit == "day" || unit == "days") {
      result = startDate + number;
   } else if (unit == "week" || unit == "weeks") {
      result = startDate + (number * 7);
   } else if (unit == "month" || unit == "months") {
      result = startDate + (number * 30); // Approximation for example
   }
   cb.Return(result);
}

static void GetNextDayOfWeek(uCalc.Callback cb) {
   var dayName = cb.ArgStr(1);
   var today = 46036; // Thursday, Jan 15, 2026
   var todayDayOfWeek = 5; // 1=Sun, 2=Mon, ..., 5=Thu

   var targetDay = 0;
   if (dayName == "Sunday") targetDay = 1;
   if (dayName == "Monday") targetDay = 2;
   if (dayName == "Tuesday") targetDay = 3;
   if (dayName == "Wednesday") targetDay = 4;
   if (dayName == "Thursday") targetDay = 5;
   if (dayName == "Friday") targetDay = 6;
   if (dayName == "Saturday") targetDay = 7;

   var daysToAdd = (targetDay - todayDayOfWeek + 7) % 7;
   // Always get the *next* week's day
   if (daysToAdd == 0) daysToAdd = 7;

   cb.Return(today + daysToAdd);
}

static void FormatDate(uCalc.Callback cb) {
   // This is a simplified formatter for the example.
   // A real implementation would be more robust.
   var dateSerial = cb.Arg(1);
   if (dateSerial == 46036) cb.ReturnStr("2026-01-15");
   if (dateSerial == 46037) cb.ReturnStr("2026-01-16");
   if (dateSerial == 46039) cb.ReturnStr("2026-01-18");
   if (dateSerial == 46043) cb.ReturnStr("2026-01-22");
   if (dateSerial == 46050) cb.ReturnStr("2026-01-29");
   if (dateSerial == 46096) cb.ReturnStr("2026-03-16");
}


// 1. Define the helper functions in the uCalc engine
uc.DefineFunction("GetCurrentDate()", GetCurrentDate);
uc.DefineFunction("AddDuration(date, num, unit As String)", AddDuration);
uc.DefineFunction("GetNextDayOfWeek(dayName As String)", GetNextDayOfWeek);
uc.DefineFunction("FormatDate(date) As String", FormatDate);

// 2. Create the transformer and define the DSL rules
using (var t = new uCalc.Transformer(uc)) {
   // Set case-insensitivity for all rules
   t.DefaultRuleSet.CaseSensitive = false;

   // Define the rules
   t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}");
   t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}");
   t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}");
   t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}");

   // 3. Process the input strings
   Console.WriteLine($"Input: 'today' -> Output: {t.Transform("today")}");
   Console.WriteLine($"Input: 'tomorrow' -> Output: {t.Transform("tomorrow")}");
   Console.WriteLine($"Input: 'next Sunday' -> Output: {t.Transform("next Sunday")}");
   Console.WriteLine($"Input: 'in 2 weeks' -> Output: {t.Transform("in 2 weeks")}");
   Console.WriteLine($"Input: 'in 60 days' -> Output: {t.Transform("in 60 days")}");
}
```

**Output:**
```
Input: 'today' -> Output: 2026-01-15
Input: 'tomorrow' -> Output: 2026-01-16
Input: 'next Sunday' -> Output: 2026-01-18
Input: 'in 2 weeks' -> Output: 2026-01-29
Input: 'in 60 days' -> Output: 2026-03-16
```

---

### Example ID: 1416

**Description:** A simple LISP transpiler that handles only binary operators.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.ExpressionTransformer;
t.FromTo("({op:1} {a:1} {b:1})", "({a} {op} {b})");

Console.WriteLine("LISP: (+ 10 20)");
Console.WriteLine($"uCalc: {t.Transform("(+ 10 20)")}");
Console.WriteLine($"Result: {uc.Eval("(+ 10 20)")}");
```

**Output:**
```
LISP: (+ 10 20)
uCalc: (10 + 20)
Result: 30
```

---

### Example ID: 1417

**Description:** A practical LISP interpreter that handles variadic (multiple arguments) and nested expressions.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.DefaultRuleSet.RewindOnChange = true;

// {@@Eval} evaluates the expression obtained by concatinating the captured
// elements {op} for operator, and {a} and {b} for the two numbers.
// These elements are strings and do not need curly braces within {@@Eval}
// :1 tels it to capture one token at a time.
t.FromTo("({op:1} {a:1} {b:1})", "{@@Eval: a + op + b}");

// If there are more than to numbers, as indicated by {more}, then the first
// two numbers are evaluated and put back into the list.  The operator remains.
t.FromTo("({op:1} {a:1} {b:1} {more})", "({op} {@@Eval: a + op + b} {more})");

// If a nested expression is present, it is evaluated immediately, by using
// % in {expr%} and the section is reprocessed again with the resulting value
// since .@RewindOnChange(true) was set.
t.FromTo("({op:1} {expr%: ({exp})}", "({op} {expr}");
t.FromTo("({op:1} {a:1} {expr%: ({exp})}", "({op} {a} {expr}");

// --- Test Cases ---
Console.WriteLine("--- Simple Binary ---");
var expr = "(- 100 25)";
Console.WriteLine($"LISP: {expr}");
Console.WriteLine($"Result: {t.Transform(expr)}");
Console.WriteLine("");

Console.WriteLine("--- Variadic (Multiple Args) ---");
expr = "(* 2 3 4)";
Console.WriteLine($"LISP: {expr}");
Console.WriteLine($"Result: {t.Transform(expr)}");
Console.WriteLine("");

Console.WriteLine("--- Nested Expressions ---");
expr = "(/ 100 (+ 5 5))";
Console.WriteLine($"LISP: {expr}");
Console.WriteLine($"Result: {t.Transform(expr)}");
expr = "(+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))";
Console.WriteLine($"LISP: {expr}");
Console.WriteLine($"Result: {t.Transform(expr)}");
Console.WriteLine("");
```

**Output:**
```
--- Simple Binary ---
LISP: (- 100 25)
Result: 75

--- Variadic (Multiple Args) ---
LISP: (* 2 3 4)
Result: 24

--- Nested Expressions ---
LISP: (/ 100 (+ 5 5))
Result: 10
LISP: (+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))
Result: 270
```

---

### Example ID: 1434

**Description:** A complete, single-pass transformer that converts common BBCode tags (bold, italic, underline, URL, and quote) to their Markdown equivalents.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
// 1. Setup the Transformer
using (var t = new uCalc.Transformer()) {
   // Allow patterns to match across multiple lines
   t.DefaultRuleSet.StatementSensitive = false;

   // 2. Define the conversion rules

   // Simple inline tags
   t.FromTo("'['b']'{text}'['/b']'", "**{text}**");
   t.FromTo("'['i']'{text}'['/i']'", "*{text}*");
   t.FromTo("'['u']'{text}'['/u']'", "<u>{text}</u>");

   // URL tag with attribute
   t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})");

   // Quote block tag
   t.FromTo("'['quote']'{content}'['/quote']'", "> {content}");

   // 3. Define the input BBCode text
   var bbCode = """

Hello, this is a test of the converter.

This text is [b]bold[/b] and this is [i]italic[/i].
You can also [u]underline[/u] text.

Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url].

[quote]This is a block of quoted text.
It can span multiple lines.[/quote]

""";

   // 4. Run the transformation and print the result
   Console.WriteLine(t.Transform(bbCode));
}
```

**Output:**
```
Hello, this is a test of the converter.

This text is **bold** and this is *italic*.
You can also <u>underline</u> text.

Here is a link to the uCalc website: [uCalc](https://www.ucalc.com).

> This is a block of quoted text.
It can span multiple lines.

```

---

### Example ID: 1435

**Description:** Defining one static and one dynamic route, then matching a URL against each.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var router = new uCalc.Transformer()) {
   // Define routes
   router.FromTo("/home", "Handler: HomePage");
   router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");

   // Test routes
   Console.WriteLine($"Matching '/home': {router.Transform("/home")}");
   Console.WriteLine($"Matching '/users/42': {router.Transform("/users/42")}");
}
```

**Output:**
```
Matching '/home': Handler: HomePage
Matching '/users/42': Handler: UserProfile, id: 42
```

---

### Example ID: 1436

**Description:** A practical example of a router with multiple rules, demonstrating LIFO precedence and handling of a '404 Not Found' case.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var router = new uCalc.Transformer()) {
   // --- Define Routes ---
   // General rules first (lower precedence)
   router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}");
   router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");

   // Specific rule last (higher precedence)
   router.FromTo("/users/new", "Handler: CreateUserPage");

   // --- Simulate Requests ---
   string[] urls = {"/users/123", "/users/new", "/products/electronics/567", "/contact"};

   foreach(var url in urls) {
      var originalUrl = url;
      var result = router.Transform(url);

      if (result.Text == originalUrl) {
         Console.WriteLine($"URL: {originalUrl} -> 404 Not Found");
      } else {
         Console.WriteLine($"URL: {originalUrl} -> {result}");
      }
   }
}
```

**Output:**
```
URL: /users/123 -> Handler: UserProfile, id: 123
URL: /users/new -> Handler: CreateUserPage
URL: /products/electronics/567 -> Handler: ProductDetail, category: electronics, id: 567
URL: /contact -> 404 Not Found
```

---

### Example ID: 1449

**Description:** Checks for the existence of a required header in a string.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   var text_ok = "Header: OK";
   var text_fail = "Header: ERROR";

   // This rule only matches if the status is "OK"
   t.Pattern("Header: OK");

   // Find() returns the transformer, so we can chain Matches().Count()
   if (t.SetText(text_ok).Find().Matches.Count() > 0) {
      Console.WriteLine("text_ok is valid.");
   }

   if (t.SetText(text_fail).Find().Matches.Count() == 0) {
      Console.WriteLine("text_fail is invalid.");
   }
}
```

**Output:**
```
text_ok is valid.
text_fail is invalid.
```

---

### Example ID: 1450

**Description:** Validates a configuration file format by enforcing the number of times specific keys must appear.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
using (var validator = new uCalc.Transformer()) {
   // 1. Configure the transformer
   validator.DefaultRuleSet.StatementSensitive = false;
   validator.SkipOver(";{line}"); // Ignore comments

   // 2. Define rules with validation constraints
   var serverRule = validator.Pattern("'['Server']' {body}").SetMinimum(1).SetMaximum(1);
   serverRule.Description = "Server Section";

   var local_t = serverRule.LocalTransformer;
   var hostRule = local_t.Pattern("Host = {@Alpha}").SetMinimum(1).SetMaximum(1);
   hostRule.Description = "Host Key";

   var portRule = local_t.Pattern("Port = {@Number}").SetMinimum(1);
   portRule.Description = "Port Key";

   // --- Test Data ---
   var validConfig = "[Server]\nHost = db1\nPort = 1433";
   var invalidConfig = "Host = web1\nPort = 80"; // Missing [Server] section


   // --- Validate validConfig ---
   Console.WriteLine("--- Validating valid_config.ini ---");
   validator.SetText(validConfig).Find();
   Console.WriteLine($"  Server section check passed: {serverRule.Matches.Count() == 1}");
   Console.WriteLine($"  Host key check passed: {hostRule.Matches.Count() == 1}");
   Console.WriteLine($"  Port key check passed: {portRule.Matches.Count() >= 1}");
   Console.WriteLine("");

   // --- Validate invalidConfig ---
   Console.WriteLine("--- Validating invalid_config.ini ---");
   validator.SetText(invalidConfig).Find();
   Console.WriteLine($"  Server section check passed: {serverRule.Matches.Count() == 1}");
   // The host and port rules will have 0 matches because their parent rule (serverRule) failed.
   Console.WriteLine($"  Host key check passed: {hostRule.Matches.Count() == 1}");
   Console.WriteLine($"  Port key check passed: {portRule.Matches.Count() >= 1}");
}
```

**Output:**
```
--- Validating valid_config.ini ---
  Server section check passed: True
  Host key check passed: True
  Port key check passed: True

--- Validating invalid_config.ini ---
  Server section check passed: False
  Host key check passed: False
  Port key check passed: False
```

---

### Example ID: 1454

**Description:** Parsing a simple 'set timer' command to extract its intent and entities.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.DefaultRuleSet.CaseSensitive = false;

// Define a rule to capture the duration and unit
t.FromTo("set timer for {@Number:duration} {unit}", "INTENT:SET_TIMER DURATION:{duration} UNIT:{unit}");

var command = "set timer for 10 seconds";
Console.WriteLine(t.Transform(command));
```

**Output:**
```
INTENT:SET_TIMER DURATION:10 UNIT:seconds
```

---

### Example ID: 1455

**Description:** A practical example parsing multiple command variations for different intents, such as playing music and setting alarms.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.DefaultRuleSet.CaseSensitive = false;

// Define multiple rules for different intents
t.FromTo("play music by {artist}", "INTENT:PLAY_MUSIC ARTIST:{artist}");
t.FromTo("play the song {song_title}", "INTENT:PLAY_MUSIC SONG:{song_title}");
t.FromTo("set an alarm for {time}", "INTENT:SET_ALARM TIME:{time}");

Console.WriteLine(t.Transform("play music by Queen"));
Console.WriteLine(t.Transform("play the song Bohemian Rhapsody"));
Console.WriteLine(t.Transform("set an alarm for 7 am"));
```

**Output:**
```
INTENT:PLAY_MUSIC ARTIST:Queen
INTENT:PLAY_MUSIC SONG:Bohemian Rhapsody
INTENT:SET_ALARM TIME:7 am
```

---

### Example ID: 1457

**Description:** Checking the error code for a simple syntax error

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var result = uc.Eval("MyVar * 10");
Console.WriteLine("An error has occurred!");
Console.WriteLine($"Error #: {(int)uc.Error.Code}");
Console.WriteLine($"Error Message: {uc.Error.Message}");
Console.WriteLine($"Error Location: {uc.Error.Location}");
Console.WriteLine($"Error Expression: {uc.Error.Expression}");
```

**Output:**
```
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10
```

---

### Example ID: 1460

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable w/ stopwatch.

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var variableX = uc.DefineVariable("x");
var userExpression = "x * 2 + 5";
var Total = 0.0;
var UpperBound = 1000000; // One million

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse(userExpression);

var stopwatch = System.Diagnostics.Stopwatch.StartNew();
for (double x = 1; x <= UpperBound; x++) {
   variableX.Value(x);
   Total = Total + parsedExpr.Evaluate();
}
stopwatch.Stop();
//Uncomment the following line to reveal the actual speed:
//Console.WriteLine($"Elapsed Milliseconds: {stopwatch.ElapsedMilliseconds} ms");

Console.Write("Sum(1, "); Console.Write(UpperBound); Console.Write(", "); Console.Write(userExpression); Console.Write(") = "); Console.Write(Total);
```

**Output:**
```
Sum(1, 1000000, x * 2 + 5) = 1000006000000
```

---

### Example ID: 1461

**Description:** Building an Equation Solver with the Parser and Transformer

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

static void EqSolveCb(uCalc.Callback cb) { // Callback based on the Bisection Method
   var expr = cb.ArgExpr(1);     // ByExpr: Unevaluated Expression object (lazy evaluation)
   var a = cb.Arg(2);            // Argument 2: Range Minimum
   var b = cb.Arg(3);            // Argument 3: Range Maximum
   var variable = cb.ArgItem(4); // ByHandle: The variable Item object

   // Helper to update the variable in the uCalc engine and evaluate the expression
   double EvaluateAt(double val) {
      variable.Value(val);   // Push the new test value to the variable
      return expr.Evaluate(); // Evaluate the pre-parsed expression
   }

   // Ensure f(a) < f(b) so we always know which direction to slide the bounds; swap a & b if necessary
   if (EvaluateAt(b) < EvaluateAt(a)) (a, b) = (b, a);

   var midpoint = 0.0;
   var fMidpoint = 0.0;

   // Bisection loop
   for (int i = 0; i <= 100; i++) {
      midpoint = (a + b) / 2;
      fMidpoint = EvaluateAt(midpoint);

      if (Math.Abs(fMidpoint) < 1e-7) break; // Stop if close enough to 0

      // Narrow the bounds (compact logic!)
      if (fMidpoint < 0) a = midpoint; else b = midpoint;
   }

   if (Math.Abs(fMidpoint) > 1e-5) cb.Error.Raise("No solution found in the given range.");
   cb.Return(Math.Round(midpoint, 7)); // Return the final solved value
}

// 1. Define variables that might be used by the end-user
uc.DefineVariable("x");
uc.DefineVariable("MyVar");

// 2. Transformer converts `EqSolve(L = R)` into `EqSolve(L - (R))` & sets defaults before it hits the parser
var t = uc.ExpressionTransformer;
t.FromTo("EqSolve({L} = {R} [[,]for {var}][, {min}, {max}])",
"EqSolve({L} - ({R}), {min}{!min:-10000}, {max}{!max: 10000}, {var}{!var: x})");

// 3. Define the custom function signature
uc.DefineFunction("EqSolve(ByExpr eq, min, max, ByHandle variable)", EqSolveCb);

// --- Demo Executions ---
System.Collections.Generic.List<string> eqList = new() {
   "EqSolve(x + 5 = 125)", // Using default range [-10000,10000]
   "EqSolve(x^2 + 5 = 105)", // Picks one result from the default range
   "EqSolve(x^2 + 5 = 105, 0, 100)", // Restricts to positive root
   "EqSolve(x^2 + 5 = 105, -100, 0)", // Restricts to negative root
   "EqSolve(x^2 + 1000 = 5)", // No existing solution
   "EqSolve(40 + MyVar * 6 = 88, for MyVar)" // Uses custom variable 'MyVar' instead of 'x'
};

foreach(var eq in eqList) {
   Console.WriteLine(uc.ExpressionTransformer.Transform(eq)); // Displays transformed expression
   Console.WriteLine($"Result: {uc.EvalStr(eq)}"); // Returns result
}
```

**Output:**
```
EqSolve(x + 5 - (125), -10000,  10000,  x)
Result: 120
EqSolve(x^2 + 5 - (105), -10000,  10000,  x)
Result: 10
EqSolve(x^2 + 5 - (105), 0, 100,  x)
Result: 10
EqSolve(x^2 + 5 - (105), -100, 0,  x)
Result: -10
EqSolve(x^2 + 1000 - (5), -10000,  10000,  x)
Result: No solution found in the given range.
EqSolve(40 + MyVar * 6 - (88), -10000,  10000, MyVar)
Result: 8
```

---

### Example ID: 1462

**Description:** A simple cascading transformation (`A` -> `B` -> `C` -> `D`) shows the step-by-step output with configurable separator

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// RewindOnChange is necessary for cascading rules to be re-evaluated.
t.FromTo("A", "B").RewindOnChange = true;
t.FromTo("B", "C").RewindOnChange = true;
t.FromTo("C", "D").RewindOnChange = true;

// Trace the transformation of "A"
Console.WriteLine(t.TraceTransform("A", " -> "));
```

**Output:**
```
A -> B -> C -> D
```

---

### Example ID: 1464

**Description:** Demonstration of TraceTrancform with formatting argument and IndexBase

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.DefaultRuleSet.RewindOnChange = true;
t.FromTo("AddUp({x})", "{x}");
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

Console.WriteLine(t.TraceTransform("AddUp(1, 2, 3, 4)", "", "$'Step {Index}: {x}\n'"));

// 0 is the default IndexBase.  Now we use 1 instead.
// So it will now start with "Step: 1" instead of "Step: 0"
Console.WriteLine("--- Now with IndexBase = 1 ---");
Console.WriteLine(t.TraceTransform("AddUp(1, 2, 3, 4)", "", "$'Step {Index} of {Count}: {x}\n'").IndexBase(1));
```

**Output:**
```
Step 0: AddUp(1, 2, 3, 4)
Step 1: (1 + AddUp(2, 3, 4))
Step 2: (1 + (2 + AddUp(3, 4)))
Step 3: (1 + (2 + (3 + AddUp(4))))
Step 4: (1 + (2 + (3 + 4)))

--- Now with IndexBase = 1 ---
Step 1 of 5: AddUp(1, 2, 3, 4)
Step 2 of 5: (1 + AddUp(2, 3, 4))
Step 3 of 5: (1 + (2 + AddUp(3, 4)))
Step 4 of 5: (1 + (2 + (3 + AddUp(4))))
Step 5 of 5: (1 + (2 + (3 + 4)))
```

---

### Example ID: 1465

**Description:** Binding a uCalc variable to a host variable in your C++ code

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();

// This example is mainly meant for C++ where it works with ordinary scalar variables
// See the other example where we work with a uCalc array

// 1. Use an array so the data lives on the heap as a reference type
// Boxing is used for scalar variables; a boxed copy of the scalar disconnected from the uCalc
// variable would prevent the example from working as expected.
// You technically can get around this with the C# "unsafe" directive, but it's not recommended
double[] myHostVar = new double[] { 1234.5 };

// 2. Pin the array
var myHostVarHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostVar, System.Runtime.InteropServices.GCHandleType.Pinned);

// 3. Bind the uCalc variable to the pinned memory address
uc.DefineVariable("myVar", myHostVarHandle.AddrOfPinnedObject());

Console.WriteLine(uc.Eval("myVar")); // Output: 1234.5

// Changing the uCalc variable updates the pinned array
uc.Eval("myVar = 456");

// The change is reflected in the C# array
Console.WriteLine(myHostVar[0]); // Output: 456

// Changing the C# array updates uCalc
myHostVar[0] = 9876;

Console.WriteLine(uc.Eval("myVar")); // Output: 9876

// Fast Parse & Evaluate loop
var expr = uc.Parse("myVar * 10");
for (myHostVar[0] = 1; myHostVar[0] <= 5; myHostVar[0]++) {
   Console.WriteLine(expr.Evaluate());
}

// Don't forget to free the handle when you are completely done with the parser instance
myHostVarHandle.Free();

```

**Output:**
```
1234.5
456
9876
10
20
30
40
50
```

---

### Example ID: 1466

**Description:** Binding a uCalc array to a host array

**Code:**
```csharp
using uCalcSoftware;

var uc = new uCalc();
double[] myHostArray = new double[] { 5, 10, 15, 20 };

// Pin the array
var myHostArrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostArray, System.Runtime.InteropServices.GCHandleType.Pinned);

// Bind the uCalc variable to the pinned memory address
uc.DefineVariable("MyArray[]", myHostArrayHandle.AddrOfPinnedObject());

// The uCalc array values come from the host array
Console.WriteLine(uc.Eval("MyArray[0]"));
Console.WriteLine(uc.Eval("MyArray[1]"));
Console.WriteLine(uc.Eval("MyArray[2]"));
Console.WriteLine(uc.Eval("MyArray[3]"));
Console.WriteLine("");

// Changing the uCalc array updates the pinned array
uc.Eval("MyArray[0] = 10; MyArray[1] = 20; MyArray[2] = 30; MyArray[3] = 40; ");

// The changes the uCalc array are reflected in the host array
Console.WriteLine(myHostArray[0]);
Console.WriteLine(myHostArray[1]);
Console.WriteLine(myHostArray[2]);
Console.WriteLine(myHostArray[3]);
Console.WriteLine("");

// One more round trip
myHostArray[0] = 10;
myHostArray[1] = 11;
myHostArray[2] = 12;
myHostArray[3] = 13;

Console.WriteLine(uc.Eval("MyArray[0]"));
Console.WriteLine(uc.Eval("MyArray[1]"));
Console.WriteLine(uc.Eval("MyArray[2]"));
Console.WriteLine(uc.Eval("MyArray[3]"));

// Don't forget to free the handle when you are completely done with the parser instance
myHostArrayHandle.Free();
```

**Output:**
```
5
10
15
20

10
20
30
40

10
11
12
13
```

---

### Example ID: 1467

**Description:** Simplified syntax for evaluating an expression

**Code:**
```csharp
using uCalcSoftware;

var myExpr = new uCalc.Expression("5+4");
Console.WriteLine(myExpr);

myExpr = "10+20";
Console.WriteLine(myExpr);
```

**Output:**
```
9
30
```

---

