reconstructed and removed duplicated code, fixed bugs