#!/usr/bin/env python

########################################################
#
# Script to split nmrPipe peak table from nlinLS
# function into peak specific files containing the
# extracted peak intensities
#
# Guillaume Bouvignies, July 19th, 2012
# gbouvignies+ignore@gmail.com
#
########################################################

import sys
import os.path
import argparse
from scipy import genfromtxt
import nmrglue as ng

# Command Line Parser
parser = argparse.ArgumentParser(description='Extract the intensity profile from an nmrPipe table.')
parser.add_argument('--tbl', type=str, required=True, nargs=1, default='nlin.tab', help='pipe table containing the intensities')
parser.add_argument('--par', type=str, required=True, nargs=1, default='fq3list', help='arrayed parameter file')
parser.add_argument('--out', type=str, nargs=1, default='./', help='output directory')

args = parser.parse_args()

pcomment, pformat, ptable = ng.fileio.pipe.read_table(args.tbl[0])
array = genfromtxt(args.par[0], dtype=None)

try:
  float(array[0])
except ValueError:
  print "Something wrong with the format of {}".format(args.par[0])
  exit()

for a in ptable.dtype.names:
  if "A" + str(len(array)-1) in a:
    p = a[:3]
    
plane_names = [_ for _ in ptable.dtype.names if p in _]

print len(array)
print len(plane_names)

if len(array) != len(plane_names):
    print('There exists a discrepency between the number of intensities and the')
    print('size of the array \'{}\''.format(args.arr[0]))
    print('Aborted...')

for peak in ptable:

    ass = peak['ASS']
    print ass
    height = peak['HEIGHT']
    dheight = peak['DHEIGHT']
#    err = dheight / height

    fileout = '.'.join([ass,'out'])
    fileout = os.path.join(args.out[0],fileout)

    with open(fileout,'w') as fo:

        for xval, plane_name in zip(array,plane_names):

            fo.write(
                '{:15.6e} {:15.6e} {:15.6e}\n'.format(
                    float(xval),
                    peak[plane_name]*height,
                    dheight
                )
            )
