added some loops and fixed bugs