// 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/b/RAM512.hdl
/**
 * Memory of 512 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 RAM512 {
    IN in[16], load, address[9];
    OUT out[16];

    PARTS:

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

    // Writing the correct RAM address inside the register
    RAM64(in=in, load=load01, address=address[0..5],out=ram64out01);
    RAM64(in=in, load=load02, address=address[0..5],out=ram64out02);
    RAM64(in=in, load=load03, address=address[0..5],out=ram64out03);
    RAM64(in=in, load=load04, address=address[0..5],out=ram64out04);
    
    RAM64(in=in, load=load05, address=address[0..5],out=ram64out05);
    RAM64(in=in, load=load06, address=address[0..5],out=ram64out06);
    RAM64(in=in, load=load07, address=address[0..5],out=ram64out07);
    RAM64(in=in, load=load08, address=address[0..5],out=ram64out08);

    // Reading the selected RAM Register
    Mux8Way16(
        a=ram64out01,
        b=ram64out02,
        c=ram64out03,
        d=ram64out04,
        e=ram64out05,
        f=ram64out06,
        g=ram64out07,
        h=ram64out08,
        sel=address[6..8],
        out=out
    );
}