Rewriting functions & fixing some bugs