cleaned up code, make loops more efficient