fixed many bugs and cleaned up code