fixed and optimized. tested working locally