fix several bugs.. needs more testing.