adapt code and fix bug