Corrected many bugs. Still need to be tested.