#!/usr/bin/python3
# Martin Budaj 2014

import sys

if len(sys.argv) == 1:
  print('usage: %s <coefficients.txt>' % sys.argv[0])
  sys.exit(1)

def get_values(d):
  return d[3:len(d)-1]

def iround(d):
  if '.' in d:
    return d.rstrip('0').rstrip('.')
  else:
    return d

data = dict()
max_n = 0

with open(sys.argv[1]) as fin:
  for l in fin:
    if l.startswith(('#', 'c/s')): continue
    l = l.rstrip()
    ldata = l.split()
    if ldata[0] == 'g/h':
      assert(ldata[1] == 'n' and ldata[2] == 'm')
      years = get_values(ldata)
    elif ldata[0] in ('g', 'h'):
      n = int(ldata[1])
      m = int(ldata[2])
      data[ldata[0],n,m] = list(get_values(ldata))
      data[ldata[0]+'_delta',n,m] = ldata[len(ldata)-1],
      max_n = max(max_n, n, m)
    else:
      raise ValueError('data line in unknown format!')

with open('../thgeomagdata.h','w') as fout:
  fout.write('''// generated by geomag/igrf2c.py

#ifndef thgeomagdata_h
#define thgeomagdata_h

''')
  for gh in ('g', 'h', 'g_delta', 'h_delta'):
    if 'delta' in gh: 
      isdelta = True 
      suffix = 'D'
      yy = (0,)
    else: 
      isdelta = False
      suffix = '[%d]' % len(years)
      yy = range(0,len(years))
    fout.write('static const double thgeomag_%sNM%s[%d][%d] = {\n' % 
      (gh[0].upper(),suffix,max_n+1,max_n+1))
    for y in yy:
      if not isdelta: fout.write('{\n')
      for n in range(0,max_n+1):
        fout.write('  {')
        for m in range(0,max_n+1):
          fout.write('%s, ' % (iround(data[gh,n,m][y]) if (gh,n,m) in data else '0'))
        fout.write('},\n')
      if not isdelta: fout.write('},\n')
    fout.write('};\n')

  fout.write(
'''#define thgeomag_maxmindex %d
#define thgeomag_step %d
#define thgeomag_minyear %d
#define thgeomag_maxdeg %d

#endif

''' % (len(years)-1, float(years[1])-float(years[0]), float(years[0]), max_n))

  print('OK: ../thgeomagdata.h created')
