Fixed some bugs & cleaed up implementation