Somewhat simplified the code