import csv


def load_object_detection_results(filename, width_height=False):
    """Load object detection results.

    The csv file should contain 8 columns
    (frame id, xmin, ymin, xmax, ymax, t, score, object id)
    or 7 columns
    (frame id, xmin, ymin, xmax, ymax, t, score).

    Args
        filename(string): filename of object detection results in csv format.
        width_height(bool): Return box format [xmin, ymin, w, h, ...] if True.
                            Otherwise, return [xmin, ymin, xmax, ymax, ...].
                            Default: False.
    Return
        dets(dict): a dict mapping frame id to bounding boxes.
    """
    dets = {}
    with open(filename, 'r') as f:
        reader = csv.reader(f)
        _ = next(reader)
        for row in reader:
            if len(row) == 8:
                frame_id, xmin, ymin, xmax, ymax, t, score, obj_id = row
                if int(frame_id) not in dets:
                    dets[int(frame_id)] = []
                if xmin and ymin and xmax and ymax and t and score and obj_id:
                    if width_height:
                        dets[int(frame_id)].append([
                            float(xmin), float(ymin), float(xmax)-float(xmin),
                            float(ymax)-float(ymin), int(float(t)),
                            float(score), int(float(obj_id))])
                    else:
                        dets[int(frame_id)].append([
                            float(xmin), float(ymin), float(xmax), float(ymax),
                            int(float(t)), float(score), int(float(obj_id))])
            elif len(row) == 7:
                frame_id, xmin, ymin, xmax, ymax, t, score = row
                if int(frame_id) not in dets:
                    dets[int(frame_id)] = []
                if xmin and ymin and xmax and ymax and t and score:
                    if width_height:
                        dets[int(frame_id)].append([
                            float(xmin), float(ymin), float(xmax)-float(xmin),
                            float(ymax)-float(ymin), int(t), float(score)])
                    else:
                        dets[int(frame_id)].append([
                            float(xmin), float(ymin), float(xmax), float(ymax),
                            int(t), float(score)])

    return dets