fixing stateful routine. still not getting correct length