refactoring internal functions. Fix boundary condition