Fixed a few bugs. This is a working version