Updated working version; cleaner code