refectoring. encountered more bugs