consolidated the code in lines 30+