###########################################################################
#                                                                         #
# C O P Y R I G H T   N O T I C E                                         #
#  Copyright (c) 2003-10 by:                                              #
#    * California Institute of Technology                                 #
#                                                                         #
#    All Rights Reserved.                                                 #
#                                                                         #
# Permission is hereby granted, free of charge, to any person             #
# obtaining a copy of this software and associated documentation files    #
# (the "Software"), to deal in the Software without restriction,          #
# including without limitation the rights to use, copy, modify, merge,    #
# publish, distribute, sublicense, and/or sell copies of the Software,    #
# and to permit persons to whom the Software is furnished to do so,       #
# subject to the following conditions:                                    #
#                                                                         #
# The above copyright notice and this permission notice shall be          #
# included in all copies or substantial portions of the Software.         #
#                                                                         #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,         #
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF      #
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                   #
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS     #
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN      #
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN       #
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE        #
# SOFTWARE.                                                               #
###########################################################################
#
# data for Strongylocentrotus purpuratus
import string
from cistematic.genomes import Genome
from os import environ

if environ.get("CISTEMATIC_ROOT"):
    cisRoot = environ.get("CISTEMATIC_ROOT") 
else:
    cisRoot = "/proj/genome"

geneDB = "%s/S_purpuratus/spurpuratus.genedb" % cisRoot


def loadChromosome(db, chromPath, chromOutPath):
    seqArray = []
    seqLen = 0
    spGenome = Genome("spurpuratus", dbFile=db)
    inFile = open(chromPath, "r")
    header = inFile.readline()
    while header != "":
        seqArray = []
        seqLen = 0
        fields = header.split()
        if "purpuratus" in header:
            idpart = fields[3]
        else:
            idpart = fields[-1].strip()

        parts = idpart.split("_")
        chromID = parts[-1]
        currentLine = inFile.readline()
        while currentLine != "" and currentLine[0] != ">":
            lineSeq = currentLine.strip()
            seqLen += len(lineSeq)
            seqArray.append(lineSeq)
            currentLine = inFile.readline()

        seq = string.join(seqArray, "")
        if seqLen < 50000:
            print "Added contig %s to database" % chromID
            spGenome.addSequence(("spurpuratus", chromID), seq, "chromosome", str(seqLen))
            spGenome.addChromosomeEntry(chromID, chromID, "db")
        else:
            outFileName = "%s%s.bin" % (chromOutPath, chromID)
            outFile = open("%s%s" % (cisRoot, outFileName), "w")
            outFile.write(seq)
            outFile.close()
            print "Added contig file %s to database" % outFileName
            spGenome.addChromosomeEntry(chromID, outFileName, "file")

        header = currentLine

    inFile.close()


def createDBFile(db):
    spGenome = Genome("spurpuratus", version="2.1",  dbFile=db)
    spGenome.createGeneDB(db)


def createDBindices(db):
    spGenome = Genome("spurpuratus", version="2.1", dbFile=db)
    spGenome.createIndices()


def buildSpurpuratusDB(db=geneDB):
    chromoPath = "%s/download/Spur2.1_Nmasked.txt" % cisRoot
    chromoOutPath = "/S_purpuratus/"

    print "Creating database %s" % db
    createDBFile(db)

    print "Loading genomic sequence" 
    loadChromosome(db, chromoPath, chromoOutPath)

    print "Creating Indices"
    createDBindices(db)

    print "Finished creating database %s" % db