copied code from lecture notes