Add comments, documentation, consolidate code, remove unused vars, additional memory leak protection