import json


def read_coco(cocofile):
    """Read coco annotation file (json format) into dictionaries"""
    # Read file
    with open(cocofile, 'r') as fptr:
        cocojson = json.load(fptr)
    
    imgid_to_annot = {}
    # Create dict of image id to filename and annots for all images
    imgid_to_filename = {img['id']: (img['file_name'], img['width'], 
                             img['height']) for img in cocojson['images']}
    catid_to_category = {(cat['id']-1): cat['name'] for cat in 
                             cocojson['categories']}
    for annot in cocojson['annotations']:
        image_id = annot['image_id']
        if image_id in imgid_to_annot:
            info = imgid_to_annot[image_id]
            info.append((annot['bbox'], annot['category_id']-1))
            imgid_to_annot[image_id] = info
        else:
            imgid_to_annot[image_id] = [(annot['bbox'], 
                                         annot['category_id']-1)]

    return imgid_to_filename, imgid_to_annot, catid_to_category