Code for state management.

I'm now thinking of changing this to C++. Memory management is becoming
cumbersome.
switching from C to C++, adding datastructures