#!/usr/bin/python3
import socket
import sys
import ssl

args = sys.argv
length = len(args)

if length == 3:
    hostname = args[1]
    neuID = args[2]
    port = 27993
    encryptedSock = False
elif length == 4:
    if args[1] == "-s":
        encryptedSock = True
        port = 27994
        hostname = args[2]
        neuID = args[3]
    else:
        raise ValueError
elif length == 5:
    if args[1] == "-p":
        port = args[2]
        hostname = args[3]
        neuID = args[4]
        encryptedSock = False
    else:
        raise ValueError
elif length == 6:
    if args[1] == "-p" and args[3] == "-s":
        port = args[2]
        encryptedSock = True
        hostname = args[4]
        neuID = args[5]
    else:
        raise ValueError
else:
    raise ValueError


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    if encryptedSock is True:
        s = ssl.wrap_socket(sock) 
    else:
        s = sock
    
    s.connect((hostname, int(port)))
    helloINP = "ex_string HELLO " + neuID + "\n"
    s.sendall(bytes(helloINP, 'utf-8'))
    

    while True:


        Message = "" 
        while not '\n' in Message:
            Message += s.recv(8192).decode('utf-8')
        Message1 = Message.split(' ')
        try: 
            flag = target = Message1[2]
            accurance = str(Message1[3].count(target))
            Message2 = 'ex_string COUNT ' + accurance + '\n'
            s.sendall(bytes(Message2, 'utf-8'))
        except:
            break
    print(flag)
    s.close()
