def main(argsIn):

    print "Started positionCorrector.py"

    try:
        try:
            usage = "usage: positionCorrector.py [--input <cube file>][--output <path>][--manual]\n  "
            parser = optparse.OptionParser(usage=usage)
            parser.add_option("-i", "--input", dest="inputPath",
                              help="Path to the input file.")
            parser.add_option("-o", "--output", dest="outputPath",
                              help="Where to write the output file.")

            # The default working directory path is kind of ugly...
            parser.add_option("--workDir", dest="workDir",  help="Folder to store temporary files in")

            parser.add_option("--manual", action="callback", callback=man,
                              help="Read the manual.")
            parser.add_option("--keep", action="store_true",
                              dest="keep",
                              help="Do not delete the temporary files.")
            parser.add_option("--spk", dest="spkPath", help='Output SPK path (always keep)')
            (options, args) = parser.parse_args(argsIn)

            if not options.inputPath:  parser.error("Need input path")
            if not options.outputPath: parser.error("Need output path")

        except optparse.OptionError, msg:
            raise Usage(msg)

        print "Beginning processing....."

        startTime = time.time()

        outputFolder  = os.path.dirname(options.outputPath)
        inputBaseName = os.path.basename(options.inputPath)
        tempFolder    = outputFolder + '/' + inputBaseName + '_posCorrectTemp/'
        if (options.workDir):
            tempFolder = options.workDir
        if not os.path.exists(tempFolder):
            os.mkdir(tempFolder) 

        # Copy the input file to the output location
        cmd = "cp " + options.inputPath + " " + options.outputPath
        #print cmd
        os.system(cmd)

        # Retrieve a list of all the kernels needed by the input cube file
        kernelDict = IrgIsisFunctions.getKernelsFromCube(options.outputPath)

        # Find the leap second file
        if not ('LeapSecond' in kernelDict):
            os.remove(options.outputPath)
            raise Exception('Error! Unable to find leap second file!')
        else:
            leapSecondFilePath = kernelDict['LeapSecond'][0] # Only deal with a single file
            

        # Convert the kernels into a list of strings to pass as arguments
        kernelStringList = []
        for k, v in kernelDict.iteritems(): # Iterate through dictionary entries
            # Add everything except the gigantic shape model (DEM)
            if k != 'ShapeModel':
                for i in v: # Iterate through type lists
                    kernelStringList.append(str(i))


        # Determine if the input file is LE or RE
        lePos = options.inputPath.rfind('LE')
        rePos = options.inputPath.rfind('RE')

        # Set the offsets from LRO spacecraft to the LRONAC cameras in meters
        if (lePos > rePos):
            lronacOffset = [1.3462, 0.8890, -0.1778] # LE
        else: 
            lronacOffset = [1.0160, 0.8890, -0.1778] # RE

        # Write out a file containing the LRONAC camera offset
        lronacOffsetPath = os.path.join(tempFolder, "lronacCameraOffset.csv")
        f = open(lronacOffsetPath, 'w')
        f.write('1 0 0 ' + str(lronacOffset[0]) + '\n')
        f.write('0 1 0 ' + str(lronacOffset[1]) + '\n')
        f.write('0 0 1 ' + str(lronacOffset[2]) + '\n')
        f.write('0 0 0 1')
        f.close()


        # Make sure the SPK data path does not already exist
        tempDataPrefix = os.path.join(tempFolder, "tempNavData")
        spkDataPath    = tempDataPrefix + "-spkData.txt"
        if os.path.exists(spkDataPath):
            os.remove(spkDataPath)

        # Call lronac spice editor tool to generate modified text file
        # - Call is silent unless there is an error
        cmd = ['spiceEditor', '--transformType', '1', '--transformFile', lronacOffsetPath, 
                              '--outputPrefix', tempDataPrefix, '--sourceCube', options.inputPath,
                              '--kernels'] + kernelStringList
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        outputText, err = p.communicate()       
        if not os.path.exists(spkDataPath):
            os.remove(options.outputPath)
            print cmd
            print outputText 
            raise Exception('Failed to create modified SPK data!')

        # Write the config file needed for the mkspk function
        #print 'Writing mkspk config file...'
        mkspkConfigPath = os.path.join(tempFolder, "spkConfig.txt")
        IsisTools.makeSpkSetupFile(leapSecondFilePath, mkspkConfigPath)

        # If the file already exists, delete it and rewrite it.
        if options.spkPath:
          tempSpkPath = options.spkPath
          #print 'Storing modified SPK file ' + tempSpkPath
        else:
          tempSpkPath = os.path.join(tempFolder, "modifiedLrocSpk.bsp")
        if os.path.exists(tempSpkPath):
            os.remove(tempSpkPath)

        #TODO: Temp trick to make sure this works for long paths

        # Create new SPK file using modified data
        # - Call is silent unless there is an error
        cmd = ['mkspk', '-setup', mkspkConfigPath, '-input', spkDataPath, '-output', tempSpkPath]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        outputText, err = p.communicate()
        if not os.path.exists(tempSpkPath):
            os.remove(options.outputPath)
            print cmd
            print outputText
            raise Exception('Failed to create modified SPK file!')

        # Re-run spiceinit using the new SPK file
        cmd = ['spiceinit', 'attach=', 'true', 'from=', options.outputPath, "spk=", tempSpkPath]
        #print cmd
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        outputText, err = p.communicate()
 
        if (outputText.find('ERROR') >= 0):
            print cmd
            print outputText
            raise Exception('Found error when calling spiceinit!') 

        # Clean up temporary files
        if not options.keep:
            os.remove(spkDataPath)
            os.remove(mkspkConfigPath)

        endTime = time.time()

        print "Finished in " + str(endTime - startTime) + " seconds."
        return 0