add K&R code style,refactoring,improve error handling