# Program to convert a FITS file into an ASCII array : x y z v

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.fits'

outfile=str(infile.split('.fits')[0])+str('_text')+str('.txt')

output=open(outfile,'w')

FitsFile = pyfits.open(infile)
image = FitsFile[0].data

sizez = image.shape[0]
sizey = image.shape[1]
sizex = image.shape[2]


for xp in range(0,sizex):
	print xp
	
	for yp in range(0,sizey):
		
		for zp in range(0,sizez):
			
			stuff = str(xp)+' '+str(yp)+' '+str(zp)+' '+str(image[zp,yp,xp])+'\n'
			
			output.write(stuff)


output.close()
		
FitsFile.close()
