Add scoping and fix bugs