Code restructure, resolve issues #22 and #27