/*
 * The Broad Institute
 * SOFTWARE COPYRIGHT NOTICE AGREEMENT
 * This is copyright (2007-2008) by the Broad Institute/Massachusetts Institute 
 * of Technology.  It is licensed to You under the Gnu Public License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *    http://www.opensource.org/licenses/gpl-2.0.php
 *
 * This software is supplied without any warranty or guaranteed support
 * whatsoever. Neither the Broad Institute nor MIT can be responsible for its
 * use, misuse, or functionality.
*/

package org.broad.igv.feature;

import java.io.*;
import java.util.*;

public class CytoBandFileParser {

    public static LinkedHashMap<String, Chromosome> loadData(BufferedReader reader) {

        LinkedHashMap<String, Chromosome> dataMap = new LinkedHashMap<String, Chromosome>();
        try {

            String nextLine;
            while ((nextLine = reader.readLine()) != null && (nextLine.trim().length() > 0)) {
                String[] data = nextLine.split("\t");
                String chr = data[0].trim();
                Chromosome chromosome = dataMap.get(chr);
                if (chromosome == null) {
                    chromosome = new Chromosome(chr);
                    dataMap.put(chr, chromosome);
                }
                Cytoband cytoData = new Cytoband(chr);
                parseData(nextLine.split("\t"), cytoData);
                chromosome.addCytoband(cytoData);
            }

            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataMap;

    }

    private static void parseData(String[] tokens, Cytoband cytoData) {

        try {
            cytoData.setStart(Integer.parseInt(tokens[1].trim()));
            cytoData.setEnd(Integer.parseInt(tokens[2].trim()));

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Error parsing gene row " + tokens[1]);
        }
    }

    private static String parseChromosome(String[] data) {
        String chr = data[0].substring(3);
        int underscore = chr.indexOf('_');
        if (underscore > 0) {
            chr = chr.substring(0, underscore);
        }
        return chr;
    }
}
