Adjust code to pattern and fixes bug