Cleaned and simplified the implementation