Fixed many bugs, changed the API a bit (should be backward compatible)