/*
 * Tutorial: Custom Trit Gates
 * How to build complex ternary logic gates from basic operators.
 * 
 * RFI-IRFOS · PUBLIC repo · v1.0
 */

// A custom "Sum" gate (balanced ternary half-adder sum)
// Truth table for balanced ternary addition (sum only):
//  A | B | Sum
// ---+---+----
//  1 | 1 | -1  (2 in decimal = 1*3 + -1)
//  1 | 0 |  1
//  1 |-1 |  0
//  0 | 1 |  1
//  0 | 0 |  0
//  0 |-1 | -1
// -1 | 1 |  0
// -1 | 0 | -1
// -1 |-1 |  1  (-2 in decimal = -1*3 + 1)
fn sum_gate(a: trit, b: trit) -> trit {
    match a {
         1 => {
             match b {
                  1 => { return -1; }
                  0 => { return  1; }
                 -1 => { return  0; }
             }
         }
         0 => { return b; }
        -1 => {
             match b {
                  1 => { return  0; }
                  0 => { return -1; }
                 -1 => { return  1; }
             }
         }
    }
}

// A custom "Buffer" gate that only passes Affirm
fn affirm_only(a: trit) -> trit {
    if a == 1 ? {
        return 1;
    } else {
        return 0;
    } else {
        return 0;
    }
}

fn main() -> trit {
    println("=== Custom Trit Gates Tutorial ===");
    
    println("Testing Balanced Ternary Sum Gate:");
    let r1: trit = sum_gate(1, 1);
    println("1 + 1 sum:"); println(cast(r1));
    
    let r2: trit = sum_gate(-1, -1);
    println("-1 + -1 sum:"); println(cast(r2));
    
    if r1 == -1 && r2 == 1 {
        println("Gates verified successfully.");
        return 1;
    }
    
    println("Verification failed.");
    return -1;
}
