added a state vector and cleaned up loops