Code restructure; few bugs left to fix