Cleaned code, added synchronization