working code with some minor fixes such as null char issues