Working version; fixed some bugs