refactored order of function definitions, working on flatten(Ptree)