general logic complete but untested
some bugs fixed