Refactoring to remove all the mallocs
restructuring, when moving do it to temp file and rename
misc cleanup and restructuring