import os

def parse(filepath):
    """Parse raw data file.

    Add column names. Transform from 3D to 2D table by adding measurement
    metadata (ID and GPS position) to corresponding lines.

    :param filepath: path to raw data file
    :return: path to parsed file
    """

    parsed_path = "tmp/parsed_" + os.path.basename(filepath)
    columns = ["meas_id", "meas_lat", "meas_lon", "RAT", "cell_id", "mcc", "mnc"
              ,"lac", "ARFCN", "signal", "ASU", "TA", "BSIC"]

    with open(filepath) as f, open(parsed_path, 'w') as p:
        p.write(','.join(columns) + '\n')
        meas_id = 0
        for line in f:
            if line.startswith("MEAS"):
                meas_id += 1
                meas_lat, meas_lon = line.split(',')[1:3]
            if line.startswith("GSM"):
                p.write(','.join([str(meas_id), meas_lat, meas_lon, line]))

    return parsed_path
