added comments, fixed a bug
improved performance by remembering states