package org.ngsutils.fastq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class FastqRead {
	private String name;
	private String comment;
	private String seq;
	private String qual;
	
	public FastqRead(String name, String seq, String qual) {
		this.name = name;
		this.comment = null;
		this.seq = seq.toUpperCase();
		this.qual = qual;		
	}
	public FastqRead(String name, String seq, String qual, String comment) {
		this.name = name;
		if (comment != null && !comment.equals("")) {
			this.comment = comment;
		} else {
			this.comment = null;
		}
		this.seq = seq.toUpperCase();
		this.qual = qual;
	}

	public String getName() {
		return name;
	}
	public String getComment() {
		return comment;
	}
	public String getSeq() {
		return seq;
	}
	public String getQual() {
		return qual;
	}
	
	static public FastqRead read(BufferedReader in) {
		try {
			String name = in.readLine();
			if (name == null) {
				return null;
			}
			name = name.substring(1); // strip the @
			String comment = null;
			if (name.indexOf(' ') > -1) {
				name = name.substring(0, name.indexOf(' '));
				comment = name.substring(name.indexOf(' ') + 1);
			}
			String seq = in.readLine();
			if (seq == null) {
				return null;
			}
			in.readLine();
			String qual = in.readLine();
			if (qual == null) {
				return null;
			}
			return new FastqRead(name, seq, qual, comment);
		} catch (Exception e) {
			return null;
		}
	}	
	
public void write(OutputStream out) throws IOException {
		String rec;
		if (comment != null) {
			rec = "@"+name+" "+comment+"\n"+seq+"\n+\n"+qual+"\n";
		} else {
			rec = "@"+name+"\n"+seq+"\n+\n"+qual+"\n";
		}
		out.write(rec.getBytes(Charset.forName("ASCII")));
	}
}

@@ -1112,16 +1112,31 @@
 ) %7B%0A
-%09%09%09%09name
+                comment
  = n
@@ -1153,11 +1153,8 @@
 ing(
-0, 
 name
@@ -1170,22 +1170,23 @@
 ' ')
+ + 1
 );%0A%09%09%09%09
-comment
+name
  = n
@@ -1191,32 +1191,35 @@
  name.substring(
+0, 
 name.indexOf(' '
@@ -1215,28 +1215,24 @@
 indexOf(' ')
- + 1
 );%0A%09%09%09%7D%0A%09%09%09S

comment needs to be pulled before name is redone...