Cleaned code by removing some duplication