Refine simulation and refactor sim/circuit.js