# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 10:10:29 2020
Updated: Monstein, 01.12.2022, 01.08.2023

@author: STEG
"""


# import sys
# import os

S = 250 # number of instruments

D = {}

def count_words_in_file(filepath, words, action=None):
    with open(filepath) as f:
        data = f.read()
        for key,val in words.items():
            #print ("key is " + key + "\n")
            ct = data.count(key)
            words[key] = ct
        if action:
             action(filepath, words)


def print_summary(filepath, words):
    print(filepath)
    for key,val in sorted(words.items()):
        print('{0}:\t{1}'.format(key,val))
        D[key]=val


#filepath = sys.argv[1]
filepath = 'C:/FHNW/2024/2024.txt'
savename = "BurstCounts2024.png"
mytitle  = 'Number of solar radio bursts observed in 2024 within the ISWI instrument network e-Callisto'

# Check keys, whether complete!!!!
# check title and filename!!!!
burst = 0
file1 = open(filepath, 'r') 
  
while True: 
    line = file1.readline() 
    print (line,end=" ")
    if not line: 
        break
    if ('#' not in line):
        burst = burst + 1
  
file1.close() 


keys = [
"ALASKA-ANCHORAGE",
"ALASKA-COHOE",
"ALASKA-HAARP",
"ALGERIA-CRAAG",
"ALMATY",
"AUSTRIA-Krumbach",
"AUSTRIA-MICHELBACH", 
"AUSTRIA-OE3FLB",
"AUSTRIA-UNIGRAZ",
"Australia-ASSA",
"Australia-LMRO",
"Arecibo-Observatory",
"BIR",
"Croatia-Visnjan",
"DENMARK",
"EGYPT-Alexandria",
"EGYPT-SpaceAgency",
"FINLAND-Siuntio",
"Finland-Kempele",
"GREENLAND",
"GERMANY-DLR",
"GERMANY-ESSEN",
"GLASGOW",
"HUMAIN", 
"HURBANOVO",
"INDIA-GAURI",
"INDIA-IISERP",
"INDIA-Nashik",
"INDIA-OOTY", 
"INDIA-UDAIPUR", 
"INDONESIA",
"INPE",
"ITALY-Strassolt",
"JAPAN-IBARAKI",
"KASI",
"KRIM",
"Malaysia-Banting",
"MEXART",
"MEXICO-LANCE",
"MEXICO-FCFM-UANL",
"MEXICO-FCFM-UNACH",
"MONGOLIA",
"MRO",
"MRT", 
"NORWAY-EGERSUND",
"NORWAY-NY-AALESUND",
"NORWAY-RANDABERG",
"POLAND-Grotniki",
"PARAGUAY",
"ROMANIA",
"ROSWELL-NM",
"SOUTHAFRICA-SANSA",
"RWANDA",
"SPAIN-ALCALA",
"SPAIN-PERALEJOS",
"SPAIN-SIGUENZA",
"SRI-Lanka",
"SSRT",
"SWISS-HB9SCT",
"SWISS-CalU",
"SWISS-HEITERSWIL", 
"SWISS-IRSOL",
"SWISS-Landschlacht",
"SWISS-MUHEN",
"THAILAND-BKK", 
"TAIWAN-NCU",
"TRIEST",
"TURKEY",
"UNAM",
"URUGUAY",
"USA-BOSTON",
"USA-ARIZONA-ERAU",
"UZBEKISTAN"]
words = dict.fromkeys(keys,0)

count_words_in_file(filepath, words, action=print_summary)

import operator                             #Importing operator module
dc_sort = sorted(D.items(),key = operator.itemgetter(1),reverse = True)
#print (dc_sort,'\n')
print ('Number of bursts: ',burst,'\n')

import matplotlib.pyplot as plt; plt.rcdefaults()
import matplotlib.pyplot as plt
import numpy as np
#-----------------------------------------------------------------------------
x=[]
y=[]
N = len(dc_sort)
for i in range(0,N):
    x.append(dc_sort[i][0])
    y.append(dc_sort[i][1])
 
plt.figure(figsize=(12,5))
plt.bar(x,y, align='center', alpha=0.9,color='g')
plt.xticks(rotation=90)
plt.xticks(x, x)
#plt.yscale('log')
plt.ylabel('Counts')
# plt.yticks(np.arange(min(y), max(y)+1, 20.0)) # 5
#plt.grid()
plt.text (len(x)*0.7,max(y)*0.9,'Total contributing stations:     {:3.0f}'.format(N))
plt.text (len(x)*0.7,max(y)*0.8,'Total reported observations: {:5.0f}'.format(np.sum(y)))
plt.text (len(x)*0.7,max(y)*0.7,'Total bursts detected:            {:4.0f}'.format(burst))
#plt.text (len(x)*0.4,max(y)*0.5,'Analysis only Oct. 18-31 due to vacation of PI')

# plt.text (len(x)*0.6,max(y)*0.3,'Analysis only Sep 01-12 due to vacation of PI')
#plt.title('Number of solar radio bursts observed in September 2021 within the ISWI instrument network e-Callisto')
plt.title(mytitle)
plt.savefig(savename, bbox_inches='tight') 
#plt.savefig("BurstCounts20-21.jpg", bbox_inches='tight') 
plt.tight_layout()
plt.show()

#-----------------------------------------------------------------------------
with open('BurstCounts.txt', "w") as fp:   # Save x/y-data in file
    fp.write("#\n") # write header information
    fp.write("# Purpose: Counts all bursts per station\n") # write header information
    fp.write("# All entries may be edited manually using Notepad.exe\n") # write header information
    fp.write("#\n") # write header information
    fp.write("\n")
    
    for i in range(0,len(x)):
        st = '{},{}\n'.format(x[i],y[i])
        fp.write(st)      
#-----------------------------------------------------------------------------
