Fixed stream read length calculation.
Added tests.
Fixed stream writing issue.