package org.cobbzilla.util.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public class MultiReader extends Reader {

    private final List<Reader> readers = new ArrayList<>();
    private Reader currentReader;
    private int readerIndex = 0;
    private boolean endOfReaders = false;

    public MultiReader (Reader r) {
        addReader(r);
        currentReader = r;
    }

    public MultiReader (InputStream in) {
        this(new InputStreamReader(in));
    }

    public void addReader (Reader r) { readers.add(r); }

    public void addLastReader (Reader r) {
        addReader(r);
        endOfReaders = true;
    }

    public void addStream (InputStream in) { addReader(new InputStreamReader(in)); }

    public void addLastStream (InputStream in) { addLastReader(new InputStreamReader(in)); }

    @Override public int read(char[] buf, int off, int len) throws IOException {
        int count = currentReader.read(buf, off, len);
        if (count == -1) {
            if (readerIndex == readers.size()-1) {
                return endOfReaders ? -1 : 0;
            }
            currentReader.close();
            readerIndex++;
            currentReader = readers.get(readerIndex);
            return read(buf, off, len);
        }
        return count;
    }

    @Override public void close() throws IOException {
        if (currentReader != null) currentReader.close();
    }
}

@@ -25,16 +25,51 @@
 il.io;%0A%0A
+import lombok.extern.slf4j.Slf4j;%0A%0A
 import j
@@ -225,16 +225,23 @@
 .List;%0A%0A
+@Slf4j%0A
 public c
@@ -481,117 +481,358 @@
 er r
-) %7B%0A        addReader(r);%0A        currentReader = r;%0A    %7D%0A%0A    public MultiReader (InputStream in) %7B%0A       
+, boolean last) %7B%0A        if (last) %7B%0A            addLastReader(r);%0A        %7D else %7B%0A            addReader(r);%0A        %7D%0A        currentReader = r;%0A    %7D%0A%0A    public MultiReader (Reader r) %7B this(r, false); %7D%0A%0A    public MultiReader (InputStream in) %7B this(new InputStreamReader(in), false); %7D%0A%0A    public MultiReader (InputStream in, boolean last) %7B
  thi
@@ -858,22 +858,24 @@
 ader(in)
-);%0A   
+, last);
  %7D%0A%0A    
@@ -908,16 +908,149 @@
 der r) %7B
+%0A        if (endOfReaders) %7B%0A            log.warn(%22addReader: endOfReaders is true, not adding reader%22);%0A        %7D else %7B%0A           
  readers
@@ -1057,16 +1057,30 @@
 .add(r);
+%0A        %7D%0A   
  %7D%0A%0A    

allow first reader to be last reader