added lazy stream open
refactored code for more flexibility