Re-organized and made code more robust