import numpy as np


def expwrite(contours, filename):
    """EXPWRITE - write an Argus file from a dictionary given in input

    This routine writes an Argus file from a dict containing the fields:
    x and y of the coordinates of the points.
    The first argument is the list containing the points coordinates and the
    second one the file to be written.

    Usage:
        expwrite(contours, filename)

    Example:
        expwrite(coordstruct, 'domainoutline.exp')

    See also EXPDOC, EXPREAD, EXPWRITEASVERTICES
    """

    fid = open(filename, 'w')
    for x, y in zip(contours['x'], contours['y']):
        if len(x) != len(y):
            raise RuntimeError('contours x and y coordinates must be of identical size')

        if 'name' in contours:
            fid.write('{}{}\n'.format('## Name:', contours['name']))
        else:
            fid.write('{}{}\n'.format('## Name:', filename))

        fid.write('{}\n'.format('## Icon:0'))
        fid.write('{}\n'.format('# Points Count Value'))
        if 'density' in contours:
            if isinstance(contours['density'], int):
                fid.write('{} {}\n'.format(np.size(x), contours['density']))
            else:
                fid.write('{} {}\n'.format(np.size(x), 1.))
        else:
            fid.write('{} {}\n'.format(np.size(x), 1.))
        fid.write('{}\n'.format('# X pos Y pos'))
        for xi, yi in zip(x, y):
            fid.write('%10.10f %10.10f\n' % (xi, yi))
        fid.write('\n')

    fid.close()
