// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/3/a/RAM64.hdl
/**
 * Memory of sixty four 16-bit registers.
 * If load is asserted, the value of the register selected by
 * address is set to in; Otherwise, the value does not change.
 * The value of the selected register is emitted by out.
 */
CHIP RAM64 {
    IN in[16], load, address[6];
    OUT out[16];

    PARTS:

    // Figuring out which RAM8 to write to
    DMux8Way(
        in=load,
        sel=address[3..5],
        a=load01,
        b=load02,
        c=load03,
        d=load04,
        e=load05,
        f=load06,
        g=load07,
        h=load08
    );

    // Writing the correct RAM address inside the register
    RAM8(in=in, load=load01, address=address[0..2],out=ram8out01 );
    RAM8(in=in, load=load02, address=address[0..2],out=ram8out02 );
    RAM8(in=in, load=load03, address=address[0..2],out=ram8out03 );
    RAM8(in=in, load=load04, address=address[0..2],out=ram8out04 );
    
    RAM8(in=in, load=load05, address=address[0..2],out=ram8out05 );
    RAM8(in=in, load=load06, address=address[0..2],out=ram8out06 );
    RAM8(in=in, load=load07, address=address[0..2],out=ram8out07 );
    RAM8(in=in, load=load08, address=address[0..2],out=ram8out08 );

    // Reading the selected RAM Register
    Mux8Way16(
        a=ram8out01,
        b=ram8out02,
        c=ram8out03,
        d=ram8out04,
        e=ram8out05,
        f=ram8out06,
        g=ram8out07,
        h=ram8out08,
        sel=address[3..5],
        out=out
    );
}