# Program to convert an ASCII x y z v array into a FITS file

import pyfits
import numpy
import math
import os
from math import *

# Change to directory where script is located
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

infile = 'M33_text.txt'

#text = open(infile,'r')

outfile=str(infile.split('.txt')[0])+str('_FITS')+str('.fits')

# Read in the data as a numpy array
print 'Reading in data...'
data = numpy.genfromtxt(infile,delimiter=" ")
print 'Done !'

xmax = int(numpy.max(data[:,0]))
ymax = int(numpy.max(data[:,1]))
zmax = int(numpy.max(data[:,2]))

image = numpy.zeros((zmax+1,ymax+1,xmax+1))

print xmax, ymax, zmax

listlength = data.shape[0]

print listlength

print 'Converting to FITS image...'
for i in range(0,listlength):
	x = int(data[i,0])
	y = int(data[i,1])
	z = int(data[i,2])
	#print x,y,z,i
	v = data[i,3]
	if 'nan' not in str(v):
		image[z,y,x] = float(v)
	else:
		image[z,y,x] = 'nan'
print 'Done !'

print 'Writing FITS file...'
FitsFile = pyfits.writeto(outfile,image,header=None)
print 'Done !'
