import numpy as np
from subprocess import call

#from Spider import Spiderarray

import mrc
import Spiderarray

def mrc2vol(fin, fout):
    '''
    Convert an mrc file to a volume file.

    Can then compare resolutions with:
    xmipp_resolution_fsc -ref ref.vol -i mixture.vol -sam 2

    @param fin: mrc file to convert
    @type fin: string
    @param fout: output filename
    @type fout: string
    '''

    data = mrc.read(fin)[0]
    # Switch between C and Fortran order.
    s = data.shape
    d = np.swapaxes(data, 0, 2)
    d = np.reshape(d, s)
    Spiderarray.array2spider(d, fout)

def vol2mrc(fin, fout, spacing=1.0, origin=None):
    """
    Convert vol file (as produced by xmipp) to mrc.
    """

    data = Spiderarray.spider2array(fin)
    s = data.shape
    data = np.swapaxes(data, 0, 2)
    data = np.reshape(data, s)

    mrc.write(data, fout, spacing=spacing, origin=origin)



def pdb2mrc(pdb_name, mrc_filename, resolution, grid_spacing):
    """Load PDB structure using chimera, and save as mrc file."""

    # Create chimera script.
    script_filename = '/tmp/chimera_pdb2mrc.cmd'
    with open(script_filename, 'w') as fout:
        fout.write('open %s\n' % pdb_name)
        fout.write('molmap #0 %1.2f gridSpacing %1.6f\n' %
                   (resolution, grid_spacing))
        fout.write('volume #0 save %s\n' % mrc_filename)

    # Call script.
    return_code = call('chimera --nogui %s' % script_filename, shell=True)
    print '\n'


def align_resample(ref_filename, rec_filename, resampled_filename):
    """Align reference to xmipp rec with chimera and resample.

    The motivation is to evaluate the resolution of an xmipp reconstruction.

    When creating a reference volume with the same grid spacing,
    the amount of zero-padding is usually too much. So here the reference
    is aligned to the reconstruction, and resampled on the grid of
    the reconstruction.
    """

    # Create chimera script.
    script_filename = '/tmp/chimera_align.cmd'
    with open(script_filename, 'w') as fout:
        fout.write('open %s\n' % ref_filename)
        fout.write('open %s\n' % rec_filename)
        fout.write('fitmap #0 #1 envelope false\n')
        fout.write('vop resample #0 onGrid #1\n')
        fout.write('volume #2 save %s\n' % resampled_filename)

    # Call script.
    return_code = call('chimera --nogui %s' % script_filename, shell=True)
    print '\n'

