/*
 * 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.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.broad.igv.preprocess;

import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Mitchell Guttman, Jim Robinson
 */
public class AlignmentToWigConverter {

    static String usageString = "run_<platform>  inputDirectory  outputDirector genome " +
        "[-m maskDirectory] [-w windowSize] [-ext extensionFactor] [-z maxZoomLevel] ";

    /**
     * Required parameters
     *      -i [input directory]
     *      -o [output directory]
     *      -genome [genome]
     * @param args
     */
    public static void main(String[] args) {


        if (args.length < 3)
        {
            System.out.println("Usage: " + usageString);
            System.exit(-1);
        }

        String inputDirectoryPath = args[0];
        String outputDirectoryPath = args[1];
        String genomeId = args[2];


        Map<String, String> argMap = ProcessingUtils.parseArgs(args, 3);

        File inputDirectory = new File(inputDirectoryPath);
        if (!inputDirectory.isDirectory())
        {
            System.out.println(inputDirectory + " is not a directory");
            System.exit(-1);
        }

        File outputDir = new File(outputDirectoryPath);
        if (!outputDir.isDirectory())
        {
            System.out.println(outputDir + " is not a directory");
            System.exit(-1);
        }


        // Path to a directory containing mask files.
        String maskDirectory = argMap.get("-m");

        int span = 25;
        String spanString = argMap.get("-w");
        try
        {
            span = Integer.parseInt(spanString);

        } catch (NumberFormatException e)
        {

        }

        int extensionFactor = 0;
        String extFactorString = argMap.get("-ext");
        if (extFactorString != null)
        {
            try
            {
                extensionFactor = Integer.parseInt(argMap.get("-ext"));
            } catch (NumberFormatException numberFormatException)
            {
                System.out.println("Extension factor (-ext) must be an integer.");
                System.exit(-1);
            }
        }

        int maxZoom = 6;
        String maxZoomLevel = argMap.get("-z");
        if (maxZoomLevel != null && maxZoomLevel.length() > 0)
        {
            try
            {
                maxZoom = Integer.parseInt(maxZoomLevel);
            } catch (NumberFormatException numberFormatException)
            {
                System.err.println(numberFormatException.getMessage());
            }
        }

        boolean replaceExistingFiles = true;
        /*
        String replaceOption = argMap.get("-f");
        if (replaceOption != null && replaceOption.length() > 0) {
        replaceExistingFiles = true;
        }
         */

        // Control file
        ReadCounter.Counts controlCounts = null;
        String controlFilename = argMap.get("-c");
        File controlFile = null;
        if (controlFilename != null)
        {
            controlFile = controlFilename == null ? null : new File(inputDirectory, controlFilename);
            HashMap<String, Integer> ignore = new HashMap();

            ReadCounter controlParser = new ReadCounter(controlFile);
            controlCounts = controlParser.doReadCounts(span, extensionFactor, genomeId, ignore);
        }


        for (File file : getInputFiles(inputDirectory))
        {
            if (controlFile == null || !file.equals(controlFile))
            {
                try
                {
                    System.out.println("Processing: " + file.getName());
                    File outputFile = new File(outputDir, file.getName() + ".wig");
                    if (replaceExistingFiles || !outputFile.exists())
                    {
                        convertFile(
                            file,
                            outputFile,
                            maskDirectory,
                            genomeId,
                            span,
                            extensionFactor,
                            controlCounts.countsPreChr);

                    }
                } catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static File[] getInputFiles(File sourceDirectory) {

        FilenameFilter filter = new FilenameFilter() {

            public boolean accept(File dir, String fn) {
                return fn.endsWith(".aligned") || fn.endsWith("aligned.txt") ||
                    fn.endsWith(".realign") || fn.endsWith(".realign.txt");
            }
        };
        return sourceDirectory.listFiles(filter);
    }

    /**
     * @throws java.lang.Exception
     * 
     *
     */
    public static void convertFile(
        File inputFile,
        File outputFile,
        String maskDirectory,
        String genomeId,
        int span,
        int extensionFactor,
        Map<String, short[]> controlCounts) throws Exception {


        AlignmentDataset ds = new AlignmentDataset(inputFile, extensionFactor,
            maskDirectory, span, genomeId, controlCounts, false);


        PrintWriter writer = new PrintWriter(new FileWriter(outputFile));

        String h = ds.getDataHeadings()[0];

        for (String chr : ds.getChromosomes())
        {
            int[] start = ds.getStartLocations(chr);
            float[] counts = ds.getData(h, chr);

            for (int i = 0; i < start.length; i++)
            {
                if (i == 0 || (start[i] != start[i - 1] + span))
                {
                    writer.println("fixedStep chrom=" + chr + " start=" + start[0] + " step=" + span +
                        " span=" + span);
                }
                writer.println((int) counts[i]);
            }
        }

        writer.close();

    }
}
