Fixed synchronization problem and restructured code