updated and tested code