Code reorganization, fixed few bugs