Fixed memleaks, rearranged sources to be more readable.