copied some code from old version to fix bug