Fixed some bugs. Seems to be working now. Not throughly tested yet.