Shortened the code and added pipe reading mode.