getArgselected = function(args)
{
    # describe loci list for each trait (arg structure : a1 a2 a3 lociList or a1 a2 a3 tX-tY lociListX-lociListY)
    if(length(args)==4)
    {
        argName = c("T1")
    } else {
        argName = strsplit(args[4], "-")[[1]]
    }
    argSelectRaw = strsplit(args[5], "-")[[1]]
    argSelected = list()
    for(m in 1:length(argSelectRaw))
    {
        currSelected = c()
        argSelectSplit = strsplit(argSelectRaw[m], ";")[[1]]
        for(l in 1:length(argSelectSplit))
        {
            currSelected = c(currSelected, as.integer(strsplit(argSelectSplit[l],",")[[1]]))
        }
        argSelected = c(argSelected, list(currSelected))
    }
    names(argSelected) <- argName
    return(argSelected)
}


getArgLtselected = function(args)
{
    # describe loci list for each trait (arg structure : a1 a2 a3 lociList or a1 a2 a3 tX-tY lociListX-lociListY)
    if(length(args)==4)
    {
        argName = c("T1")
        argSelectRaw = strsplit(args[4], "-")[[1]]
    }
    else
    {
        argName = strsplit(args[4], "-")[[1]]
        argSelectRaw = strsplit(args[5], "-")[[1]]
    }
    isLt = TRUE %in% grepl(";", argSelectRaw, fixed=TRUE)
    if (isLt) {
        argSelected = list()
        for(l in 1:length(argSelectRaw))
        {
            selectPostSplit = list()
            argSelectSplit = strsplit(argSelectRaw[l], ";")[[1]]
            for(m in 1:length(argSelectSplit))
            {
                selectPostSplit = c(selectPostSplit, list(as.integer(strsplit(argSelectSplit[m],",")[[1]])))
            }
            names(selectPostSplit) <- c("a", "b", "c")[1:length(selectPostSplit)]
            argSelected <- c(argSelected, list(selectPostSplit))
        }
        names(argSelected) <- argName
        print(argSelected)
        return(argSelected)
    }
    else
    {
        return(list())
    }
}

getMapDim = function(relPos)
{
    previousPos = getwd()
	if(file.exists(relPos))
	{
		setwd(relPos)
	} # if relPos not recognized, may be because of call in standalone version
	else
	{
		#print(paste("Path not found", relPos))
		#print(paste("MAPH", previousPos))

	}

    mapHeight = 11#get value automatically from the MTP/user_input/conf.lua
    mapWidth = 5
    refConf = "../../user_input/simuConf.lua"
    refConfReg = "../MTP/user_input/simuConf.lua"
	  refConfRep = "../../../user_input/simuConf.lua"
    refCReal = ""
    if(file.exists(refConfReg))
    {
        refCReal = refConfReg
    } else {
        if (file.exists(refConf))
        {
            refCReal = refConf
        } else {
    			if (file.exists(refConfRep))
    			{
    				refCReal = refConfRep
    			}	else {
              print("conf does not exist. Keep default mapHeight")
          }
    		}
    }

    if(refCReal != "")
    {
       lconf = readLines(refCReal)
        for(l in lconf)
        {
            if (l != "")
            {
                lsp = strsplit(l, " ")[[1]]
                if (lsp[1] == "mapLength")
                {
                    print("change map length from conf")
                    mapHeight = as.numeric(lsp[3])
                }
                else if  (lsp[1] == "mapWidth")
                {
                    mapWidth = as.numeric(lsp[3])
                }
            }
        }
    }
    setwd(previousPos)
    return(c(mapWidth, mapHeight))
}

#S1 1 /home/athoni/newgitmtp/METAPOP/raw_outputs/genetic/ T1-T2 1,3,7-2,4,6

findCsv = function(filesList, isGene)
{
    #Split extension. Allows only one dot in the name !
    s = strsplit(filesList, split='\\.')
    #Keeps only csv extension
    s = s[lapply(s, tail, 1) == "csv"]
    #Remove extensions(everything afeter the first dot)
    s = lapply(s, head, 1)
    s = unlist(s)

    #Split fiels separated by "_"
    s2 = strsplit(s, split='_')
    #Select files with 3 fields, there should be exacly 3
    s2 = s2[lapply(s2, length) == 3]
    
    if (isGene)
    {
        #Check "genes" keyword presence
        sel = lapply(s2, head, 1) == "genes"
        s2 = s2[sel]
        filesList = filesList[sel]
        #Remove "genes" keyword
        s2 = lapply(s2, `[`, -1)
    }

    #print("S2")
    #print(s2)

    ############### SPECIES #################
    #    We need to isolate each species    #
    #########################################
    #Get species of all files
    species = unlist(lapply(s2, `[`, 1))
    #Make a list without species
    s3 = lapply(s2, `[`, -1)
    #Get unique types
    speNames = as.list(unique(species))
    #For each type, get sublist of files
    sublists  = lapply(speNames, '==', species)
    if (isGene)
    {

        #print("S3")
        #print(s3)
        speList = lapply(sublists, function(x) s3[x])
        filesList = lapply(sublists, function(x) filesList[x]) 
        names(speList) = speNames
        names(filesList) = speNames
        #Sort steps & Files names i ndexed by step
        for(spe in names(speList))
        {
            names(filesList[[spe]]) = unlist(speList[[spe]])
            steps = as.numeric(names(filesList[[spe]]))
            sortInd = sort.int(steps, index.return=T)$i
            filesList[[spe]] = filesList[[spe]][sortInd]
        }

        #print("filesList")
        #print(filesList)

        return(list(s3, filesList, sublists))
    }
    else
    {
        #Split names list according to types
        speList = lapply(sublists, function(x) s3[x]) 
        names(speList) = speNames
        for(i in names(speList))
        {
            #Types of all files
            types = unlist(lapply(speList[[i]], `[`, 2))
            #Make a list without types (only steps remain)
            sTemp = unlist(lapply(speList[[i]], `[`, -2))
            #Get unique types
            typesNames = as.list(unique(types))
            #For each type, get sublist of files
            sublists  = lapply(typesNames, '==', types)
            #Split names list according to types
            speList[[i]] = lapply(sublists, function(x) sTemp[x])
            speList[[i]] = lapply(speList[[i]], as.numeric)
            speList[[i]] = lapply(speList[[i]], sort)
            speList[[i]] = lapply(speList[[i]], as.character)
            #Add names
            names(speList[[i]]) = typesNames
        }

        ########### Reconstruction ################
        # Now that we have classified, we just    #
        # reconstruct the file names              #
        # That is easier than keeping track of    #
        # original parsed names                   #
        ###########################################
        filesList = sapply(names(speList), function(x) NULL)
        for(spe in names(speList))
        {
            filesList[[spe]] = sapply(names(speList[[spe]]), function(x) NULL)
            for(trait in names(speList[[spe]]))
            {
                filesList[[spe]][[trait]] = lapply(speList[[spe]][[trait]], function(x) paste(spe, "_", x, "_", trait, ".csv", sep=""))
                names(filesList[[spe]][[trait]]) =  speList[[spe]][[trait]]
            }    
        }
        return(list(s3, filesList, sublists))
    }
}


checkSpecies = function(fileList, argSpecies, argStep)
{
    if(sum(argSpecies == names(filesList)) <= 0) 
    {
        print("Error, no files of this species")
        quit()
    }
}

checkConsistencyGeno = function(fileList, argSpecies, argStep)
{
    checkSpecies(fileList, argSpecies, argStep)
    if(sum(argStep == names(filesList[[argSpecies]])) <= 0)
    {
        print("Error, no files of this step")
        quit()
    }
    if(sum(argSpecies == names(filesList)) <= 0) 
    {
        print("Error, ploidy missing for this species")
        quit()
    }
}

checkConsistencyPheno = function(fileList, argSpecies, argTraits, argStep)
{
    #Checking consistency of arguments
    checkSpecies(fileList, argSpecies, argStep)
    for(t in argTraits)
    {
        if(sum(t == names(filesList[[argSpecies]])) <= 0)
        {
            print("Error, no files of this trait")
            quit()
        }
        if(sum(argStep == names(filesList[[argSpecies]][[t]])) <= 0)
        {
            print("Error, no files of this step")
            quit()
        }
    }
}
