Fixed bugs in implementing function.