# -*- coding: iso-8859-15 -*-
# L. Fita, LMD. Feburary 2015. Python script to generate a new ASCII file from a 
#    nother with [char] separated values
## e.g. # create_list.py -a ';' -c 1,7,6 -f MeteoFrancesfc/0_Documentation/POSTES 
## e.g. # create_list.py -a ',' -c 1,2,3 -f AEMETsfc/0_Documentation/AWS_AEMET-stations.csv
import numpy as np
import os
import re
from optparse import OptionParser

main = 'create_list.py'
errormsg = 'ERROR -- error -- ERROR -- error'
warnmsg = 'WARNING -- warning -- WARNING -- warning'

def remove_NONascii(string):
    """ Function to remove that characters which are not in the standard 127 ASCII
      string= string to transform
    >>> remove_NONascii('Lluís')
    Lluis
    """
    fname = 'remove_NONascii'

    newstring = string

    RTFchar= ['á', 'é', 'í', 'ó', 'ú', 'à', 'è', 'ì', 'ò', 'ù', 'â', 'ê', 'î', 'ô',  \
      'û', 'ä', 'ë', 'ï', 'ö', 'ü', 'ç', 'ñ','æ', 'œ', 'Á', 'É', 'Í', 'Ó', 'Ú', 'À', \
      'È', 'Ì', 'Ò', 'Ù', 'Â', 'Ê', 'Î', 'Ô', 'Û', 'Ä', 'Ë', 'Ï', 'Ö', 'Ü', 'Ç', 'Ñ',\
      'Æ', 'Œ', '\n', '\t']
    ASCchar= ['a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o',  \
      'u', 'a', 'e', 'i', 'o', 'u', 'c', 'n','ae', 'oe', 'A', 'E', 'I', 'O', 'U', 'A', \
      'E', 'I', 'O', 'U', 'A', 'E', 'I', 'O', 'U', 'A', 'E', 'I', 'O', 'U', 'C', 'N',\
      'AE', 'OE', '', ' ']

    Nchars = len(RTFchar)
    for ichar in range(Nchars):
        foundchar = string.find(RTFchar[ichar])
        if foundchar != 0:
            newstring = newstring.replace(RTFchar[ichar], ASCchar[ichar])

    return newstring

####### ###### ##### #### ### ## #

parser = OptionParser()
parser.add_option("-a", "--chracter", dest="cchar", 
  help="chracter of new value", metavar="VALUE")
parser.add_option("-c", "--columns", dest="cols", 
  help="',' list of cols to use (1 based, sorted)", metavar="VALUES")
parser.add_option("-f", "--file", dest="stfile", help="stations file", 
  metavar="FILE")
(opts, args) = parser.parse_args()

########    ####### 
## MAIN
    #######

ofile = 'newlist.dat'

if not os.path.isfile(opts.stfile):
    print errormsg
    print '   ' + main + ": stations file '" + opts.stfile + "' does not exist !!"
    quit(-1)

desiredcols = opts.cols.split(',')

print 'desiredcols:',desiredcols

oasciif = open(opts.stfile, 'r')
onewf = open(ofile, 'w')

for line in oasciif:
    vals = line.replace('\n','').replace(chr(13),'')
    values = vals.split(opts.cchar)

    newline = '' 
    for icol in range(len(desiredcols)):
        newline = newline + " " + remove_NONascii(values[int(desiredcols[icol])-1]).replace('"','')

#    print vals
#    print values
#    print newline

    onewf.write(newline + '\n')

oasciif.close()
onewf.close()

print main + ": sucessfull written of '" + ofile + "' !!"
