refactored with some better code