refactor code and add logic for pages