// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

public class SpecialParser {
    private static String CHARSET = "ISO-8859-1";
    private static String Q = "";
    private static String SEP = ",";
    private static interface DataParse {
        public String parse(InputStream is) throws IOException;
    }
    private static class CountedDataParse implements DataParse {
        public String parse(InputStream is) throws IOException {
            int len = is.read();
            byte[] b = new byte[len];
            is.read(b);
            return new String(b, CHARSET);
        }
    }
    private static class FixedDataParse implements DataParse {
        private int len;
        public FixedDataParse(int len) {
            this.len = len;
        }
        public String parse(InputStream is) throws IOException {
            byte[] b = new byte[len];
            is.read(b);
            return new String(b, CHARSET);
        }
    }
    private static final byte[][] marker = { { 0x07, 0x07 }, { 0x08, 0x09, 0x0A, 0x0B, 0x0C } };
    private static final DataParse[] handler = { new CountedDataParse(), new FixedDataParse(3) };
    public void parse(InputStream is, PrintStream ps) throws IOException {
        String[] res = new String[marker.length];
        int state = 0;
        int len = 0;
        int c;
        while((c = is.read()) >= 0) {
            if(c == marker[state][len]) {
                len++;
            } else {
                len = 0;
            }
            if(len == marker[state].length) {
                res[state] = handler[state].parse(is);
                state++;
                len = 0;
                if(state == marker.length) {
                    ps.print(Q + res[0] + Q);
                    for(int i = 1; i < res.length; i++) {
                        ps.print(SEP + Q + res[i] + Q);
                    }
                    ps.println();
                    state = 0;
                }
            }
        }
    }
    public static void main(String[] args) throws Exception {
        // format:
        //   ....
        //   marker #1 = 0x07 0x07
        //   1 byte length
        //   N bytes of data in ISO-8859-1
        //   ...
        //   marker #2 = 0x08 0x09 0x0A 0x0B 0x0C
        //   3 bytes of data in ISO-8859-1
        //   ...
        byte[] b = { 0, 7, 7, 2, 65, 66, 0, 0, 8, 9, 10, 11, 12, 65, 66, 67, 0, 0, 0, 7, 7, 2, 66, 67, 0, 0, 8, 9, 10, 11, 12, 66, 67, 68, 0 };
        SpecialParser p = new SpecialParser();
        p.parse(new ByteArrayInputStream(b), System.out);
    }
}
