debugged and optimized. Full code working