refined mathlab code