refacting code, cleaned up a few bugs