import requests
import csv


def count_header_lines(url):
    """ Counts header lines in a CTD file.
    Seward Line CTD files have a variable number of header lines at the top of
    the file.  This function count the header rows by looking for the 'END' string
    that terminates it.
    
    Args:
        url : the URL of the CTD data file (string)
    Returns:
        the number of header lines that need to be skipped when reading (int)
    """
    
    nhdr=0
    with requests.Session() as s:
        download = s.get(url)

        decoded_content = download.content.decode('utf-8')

        cr = csv.reader(decoded_content.splitlines(), delimiter=',')
        my_list = list(cr)
        for row in my_list:
            nhdr+=1
            if row[0].find('END')>1:  # Warning: I've seen cases with "END" in station name
                #print(row[0])
                break
    return(nhdr)