added state counting code