Refractored and tried to fix bugs
Refractored Code