#!/usr/bin/env python

try:
	import msvcrt, os
	msvcrt.setmode(1, os.O_BINARY)
except:
	pass

import os, sys
from cgitools import isOnline, cgi_token, exitWithInfo, decodeStr

#print   'Content-type:   text/plain   name="test_name"\n'
#print   'Content-Disposition:   inline; filename="obj.Rdata"\n\n'  

#print "Content-Type:application/octet-stream\n"
#print "Content-Disposition:attachment;filename='test_name'\n\n"


#print "Content-Disposition: attachment;filename=test_file\n"
#print "Content-Transfer-Encoding: binary\n"
#print "Accept-Ranges: bytes\n"
#print "Content-Length: %ld\n" % os.stat(fn).st_size
#print "Connection: close\n"
#print "Content-type: application/octet-stream\n"
#print "\n");  

# need a comma after "print" to prevent extra line char - '\n'
#print "Content-Type:application/x-download\n",
#print "Content-Disposition:attachment;filename=%s\n\n" % fn,
#print open(fn, 'rb').read(), # this will append a line char anyway

if not isOnline(): exitWithInfo('Logon first please.')

request_page = os.getenv('QUERY_STRING')
if not request_page: #is None: 
	request_page = os.getenv('PATH_INFO')
	if request_page and len(request_page)>1: request_page = request_page[1:] # remove the leading slash '/'
	else: exitWithInfo('No file name offered!')

filename = decodeStr(request_page)

if not os.path.exists(filename): exitWithInfo('The file is not found!')

#print "Content-Type:image/png\n\n",
#print "Content-Disposition:attachment;filename=%s\n\n" % os.path.split(filename)[1],

fext = os.path.splitext(filename)[1].lower()
if fext in ('.png', '.jpg'):
	print "Content-Type:image/%s\n\n" % {'.png':'png', '.jpg':'jpeg'}[fext],
	sys.stdout.write(open(filename, 'rb').read()) # write won't append a line char
else:
	try:
		#sys.stdout.write(os.popen('gs -sDEVICE=png256 -sOutputFile=- "%s" -q -c quit' % filename, 'r').read())

		prog = sys.platform == 'win32' and 'gswin32c' or 'gs'
		f = os.popen('%s -q -sDEVICE=png256 -sOutputFile=- "%s" -c quit' % (prog, filename), 'r').read()
		if f[-40:] == '>>showpage, press <return> to continue<<': f = f[:-40]
		print "Content-Type:image/png\n\n",
		sys.stdout.write(f)
	except: 
		pass
		#print cgi_token
		#print filename, '<p>\n'
		#import traceback
		#traceback.print_exc()

		#raise


