#!/usr/bin/env python

# takes a fits verion of a mangle file and removes unobserved sectors
# converts a mangle FITS file to a .ply file

import numpy as np
import os
import sys
import pylab as plt
import pyfits as py

maskFile = os.getenv("HOME")+"/workspace/Voids/catalogs/boss/boss_geometry_2011_06_10.fits"
outFile = os.getenv("HOME")+"/workspace/Voids/catalogs/boss/boss_mask.ply"

hdulist = py.open(maskFile)
maskData = hdulist[1].data
hdulist.close()

fp = open(len(maskData), 'w')
fp.write(str(numKeep) + " polygons\n")
fp.write("pixelization 6s\n")
fp.write("snapped\n")
fp.write("balkanized\n")
iKeep = 0
for i in xrange(len(maskData)):
  fp.write("polygon %22d ( %d caps, %20.7f weight, %d pixel, %20.16f str):\n" %
             (iKeep, 
              maskData.field('NCAPS')[i], 
              maskData.field('WEIGHT')[i], 
              maskData.field('PIXEL')[i], 
              maskData.field('STR')[i] ))

  ncaps = maskData.field('NCAPS')[i]
  for iCap in xrange(ncaps):
    fp.write("%24.20f %24.20f %24.20f %24.20f\n" % 
               (maskData.field('XCAPS')[i][iCap][0], 
                maskData.field('XCAPS')[i][iCap][1], 
                maskData.field('XCAPS')[i][iCap][2], 
                maskData.field('CMCAPS')[i][iCap]))
  iKeep += 1

fp.close()
