completed and debugged implementation