#!/usr/bin/env python

import os,sys
import csv
import numpy as np

class Station_loc_creator(object):

	def __init__(self):

		self.edi_list = [os.path.join(os.getcwd(),edi) for edi in os.listdir(os.getcwd()) if edi.find('.edi')>0]
		print(str(len(self.edi_list)) + ' stations are found.')
		print('Do you want to continue ? y/n')
		prim_answer = raw_input()
		if prim_answer == 'y':
			pass
		else:
			print("Bye.")
			sys.exit()

		print 'What will be the output filename'
		self.edi_list.sort()
		out_file_inp = raw_input()

		self.out_file = out_file_inp

		self.len_edi_list = len(self.edi_list)

		self.file_names = []
		for i in range(0,len(self.edi_list)):
			self.file_names.append(self.edi_list[i][self.edi_list[i].rfind('/')+1:-4])

	def read_write_edi(self):

		###----------EDI PART----------###
		#Searching for edi files and appending them to a list.
		if len(self.edi_list) == 0:
			print('Warning : There are no edi files in the current direction.')
			sys.exit()
		self.edi_list.sort()

		#Creating empty arrays for information.
		self.station_lon_list = []
		self.station_lat_list = []
		self.lat_degrees_list = []
		self.lon_degrees_list = []
		self.station_name_list = []

		for i in range(0,self.len_edi_list):

			edi_obj = open(self.edi_list[i],'rb')
			edi_csv = csv.reader(edi_obj, delimiter = ' ')
			data_station = []

			for row in edi_csv:
				data_station.append(row)

			for row in range(0,len(data_station)):
				data_station[row] = filter(None,data_station[row])

			data_station = filter(None,data_station)
			edilendata = len(data_station)

			for k in range(0,edilendata):
				if data_station[k][0][:6] == 'DATAID':
					index_id = k
				elif data_station[k][0][:6] == 'REFLAT':
					index_lat = k
				elif data_station[k][0][:7] == 'REFLONG':
					index_long = k
					if len(data_station[k]) == 1:
						index_help = 0
					else:
						index_help = 1

			self.station_name_list.append(data_station[index_id][0][8:len(data_station[1][0])-1])

			self.station_lat_list.append(data_station[index_lat][0][7:])
			if index_help == 0:
				self.station_lon_list.append(data_station[index_long][0][8:])
			else:
				self.station_lon_list.append(data_station[index_long][1])

			latitude_string_find = [pos for pos, char in enumerate(self.station_lat_list[i]) if char == ':']
			longitude_string_find = [pos for pos, char in enumerate(self.station_lon_list[i]) if char == ':']


			deg = float(self.station_lat_list[i][0:latitude_string_find[0]])
			minute = float(self.station_lat_list[i][latitude_string_find[0]+1:latitude_string_find[1]]) / 60.0
			second = float(self.station_lat_list[i][latitude_string_find[1]+1:]) / 3600.0
			if deg < 0.0:
				lat = round(deg - minute - second,5)
			else:
				lat = round(deg + minute + second,5)
			self.lat_degrees_list.append(lat)
			deg = float(self.station_lon_list[i][0:longitude_string_find[0]])
			minute = float(self.station_lon_list[i][longitude_string_find[0]+1:longitude_string_find[1]]) / 60.0
			second = float(self.station_lon_list[i][longitude_string_find[1]+1:]) / 3600.0
			if deg < 0.0:
				lon = round(deg - minute - second,5)
			else:
				lon = round(deg + minute + second,5)
			self.lon_degrees_list.append(lon)

			self.station_name_list.append(data_station[index_id][0][8:len(data_station[1][0])-1])

		lenstation = len(self.lon_degrees_list)
		lines = []
		lines.append('Longitude,Latitude,St.No,St.Name\n')
		for i in range(0,lenstation):
			lines.append(str(self.lon_degrees_list[i]) + ',' + str(self.lat_degrees_list[i]) + ','+ str(i+1) + ',' + str(self.file_names[i]) + '\n')

		filesave = file(str(self.out_file) + '.csv','w')
		filesave.writelines(lines)
		filesave.close()
		print('Wrote the file in ' + str(os.getcwd()))

###SCRIPT###

aaa = Station_loc_creator()
aaa.read_write_edi()
