/*
 * 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.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

    static String usageString = "run_<platform>  inputFile  outputFile genome " +
            "[-m maskDirectory] [-w windowSize] [-ext extensionFactor] " +
            "[-normalize]";

    /**
     * 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 inputDirOrFile = new File(inputDirectoryPath);

        File outputFileOrDir = new File(outputDirectoryPath);
        if (inputDirOrFile.isDirectory() &&  !outputFileOrDir.isDirectory()) {
            System.out.println(outputFileOrDir + " 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) {
        }

        boolean normalize = argMap.containsKey("-normalize");
        System.out.println("Normalize = " + normalize);

        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
        Map<String, short[]> controlCounts = null;
        String controlFilename = argMap.get("-c");
        File controlFile = null;
        if (controlFilename != null) {
            controlFile = controlFilename == null ? null : new File(
                    inputDirOrFile, controlFilename);
            HashMap<String, Integer> ignore = new HashMap();

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

        File[] files = inputDirOrFile.isDirectory() ? getInputFiles(
                inputDirOrFile)
                : new File[]{inputDirOrFile};

        for (File file : files) {
            if (controlFile == null || !file.equals(controlFile)) {
                System.out.println("Processing: " + file.getName());
                String fn = file.getName() + ".h5";
                File outputFile = outputFileOrDir.isDirectory() ? new File(outputFileOrDir, fn) :
                    outputFileOrDir;
                if (replaceExistingFiles || !outputFile.exists()) {
                    processFile(
                            file,
                            outputFile,
                            maskDirectory,
                            genomeId,
                            span,
                            extensionFactor,
                            maxZoom,
                            controlCounts,
                            normalize);
                }
            }

        }
    }

    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") ||
                        fn.endsWith(".bam") || fn.endsWith(".sam");

            }
        };
        return sourceDirectory.listFiles(filter);
    }

    /**
     * @throws java.lang.Exception
     *
     *
     */
    public static void processFile(
            File inputFile,
            File outputFile,
            String maskDirectory,
            String genomeId,
            int span,
            int extensionFactor,
            int maxZoomLevel,
            Map<String, short[]> controlCounts,
            boolean normalize) {
        try {
            AlignmentDataset ds = new AlignmentDataset(inputFile,
                    extensionFactor, maskDirectory, span, genomeId,
                    controlCounts, normalize);
            NonOverlappingProcessor pr = new NonOverlappingProcessor(ds);
            pr.setZoomMax(maxZoomLevel);

            String ofileName = outputFile.getAbsolutePath();
            if(!ofileName.endsWith(".h5")) {
                ofileName = ofileName + ".h5";
            }

            pr.process(ofileName);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
