First, if you not reset a layer, the globel variable stay alive.
If I see right you never save to LocalStorage.
Or I miss, everything is a little messed up.
In first you save only the 0.
In second you never get it, so you never can save.
Clean up and try again.