fixed some final bugs, and cleand up the code