clean-up and minor bug fix. ready for freeing memory and merging