Rewrote the codes to make it work