package scripts.lincs.util;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;

import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMFileWriter;
import net.sf.samtools.SAMFileWriterFactory;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.SAMFileReader.ValidationStringency;

public class ExtractFirstBaseFromBam {
	public void process(String inBam,String outBam)
	{
		SAMFileReader samReader = new SAMFileReader(new File(inBam));
		SAMFileHeader header = samReader.getFileHeader();
		SAMFileWriterFactory writerFactory = new SAMFileWriterFactory();
		SAMFileWriter samWriter = writerFactory.makeBAMWriter(header, false, new File(outBam));
		samReader.setValidationStringency(ValidationStringency.SILENT);
		for (final SAMRecord samRecord : samReader) {
			samRecord.setHeader(header);
			if (samRecord.getReadNegativeStrandFlag())
			{
				samRecord.setAlignmentStart(samRecord.getAlignmentEnd()-1);
				samRecord.setBaseQualityString(samRecord.getBaseQualityString().substring(samRecord.getBaseQualityString().length()-1));
				samRecord.setReadString(samRecord.getReadString().substring(samRecord.getReadString().length()-1));
			} else {
				samRecord.setReadString(samRecord.getReadString().substring(0,1));
				samRecord.setBaseQualityString(samRecord.getBaseQualityString().substring(0,1));
			}
			samRecord.setCigar(new Cigar(new LinkedList<CigarElement>(Collections.singleton(new CigarElement(1, CigarOperator.M)))));
			samWriter.addAlignment(samRecord);
		}
		samWriter.close();
		samReader.close();
	}
	public final static void main(String[] args) throws IOException
	{
		ExtractFirstBaseFromBam script = new ExtractFirstBaseFromBam();
		script.process(args[0], args[1]);
	}
}
