# Title: ConvertTsv2Csl.py
# Author: Rubinigg Michael
# Contributor: Rubinigg Michael
# Abstract: Converts tab separated value files of any structure to CSV files based on user input
# Version 1.0
# Release date: 2023-09-12
# Place: Graz, Austria, EU
# Company: dr Mag. rer. nat. Michael Rubinigg
# Programming Language: Python 3.11
# Rights:  Creative Commons Attribution 4.0 (CC-BY)

import tkinter as tk
from tkinter import filedialog
import csv

def convert_tab_to_csv(input_file_path, output_file_path):
    try:
        with open(input_file_path, 'r', newline='', encoding='utf-8') as input_file:
            with open(output_file_path, 'w', newline='', encoding='utf-8') as output_file:
                tab_reader = csv.reader(input_file, delimiter='\t')
                csv_writer = csv.writer(output_file, delimiter=',')

                for row in tab_reader:
                    # Replace missing data with "NULL"
                    cleaned_row = ['NULL' if cell.strip() == '' else cell for cell in row]
                    csv_writer.writerow(cleaned_row)

        print("Conversion completed successfully.")

    except Exception as e:
        print("An error occurred:", str(e))

def select_input_file():
    input_file_path = filedialog.askopenfilename(filetypes=[("Tab-Delimited Files", "*.txt")])
    return input_file_path

def select_output_file():
    output_file_path = filedialog.asksaveasfilename(defaultextension=".csv", filetypes=[("CSV Files", "*.csv")])
    return output_file_path

def main():
#    tk.Tk().withdraw()  # Hide the main tkinter window
    print("Select the input tab-separated text file.")
    input_file_path = select_input_file()

    if not input_file_path:
        print("No input file selected. Exiting.")
        return

    print("Select the output CSV file.")
    output_file_path = select_output_file()

    if not output_file_path:
        print("No output file selected. Exiting.")
        return

    # Perform the conversion
    convert_tab_to_csv(input_file_path, output_file_path)

if __name__ == "__main__":
    main()