Fixed bugs: #1 #3 #4 and improving the code