Re-coded to fix bugs