algorithm and code improvement