rewritten and bug fixes