import os,sys
from casatools import msmetadata,table,measures,quanta,agentflagger,image,calibrater,ms
from casatasks import *
from datetime import datetime as dt, timedelta
import logging,numpy as np,sys,copy,glob,psutil,json,urllib.request
from paircarstools.basic_func import *
from paircarstools.access_ms import *
from astropy.io import fits
from optparse import OptionParser
os.system('rm -rf casa*log')
'''
Code is written by Devojyoti Kansabanik, 01 Feb, 2021

Code to validate the P-AIRCARS input parameters
#######################
# Here we are validating the user given parameters. 
# If some parameters are found to be unsuitable, code will take default suitable value or show error and stop.
#######################
'''

def main():
	usage= 'Validate P-AIRCARS input file'
	parser = OptionParser(usage=usage)
	parser.add_option('--basedir',dest="basedir",default=None,help="Name of the base directory",metavar="Directory name")
	parser.add_option('--input_file',dest="input_file",default=None,help="Name of the input file",metavar="String")
	(options, args) = parser.parse_args()
	if options.basedir==None or options.basedir=='':
		print ('Give the base directory path.\n')
		os._exit(1)
	if options.input_file==None or options.input_file=='':
		print ('Give the P-AIRCARS input file to validate.\n')
		os._exit(1)
	final_input_file=validate_inputs(basedir=options.basedir,input_file=options.input_file)
	if final_input_file!=1:
		print ('Validated input file saved at : '+str(final_input_file)+'\n')
		return 
	else:
		os._exit(1)

def validate_inputs(basedir='',input_file=''):
	'''
	This function check the P-AIRCARS selfcal input file and set wrong parameters to default values with a warning
	Parameters
	----------
	basedir : str
		Name of the base directory
	input_file : str
		P-AIRCARS selfcal input file
	Returns
	-------
	str
		New selfcal input file
	'''
	# Validating basedir path
	#########################
	if os.path.isfile(input_file)==False:
		print ('Input file does not exist. Exiting P-AIRCARS......\n')
		os.system('rm -rf casa*log')
		return 1
	elif basedir=='':
		print ('Path of the base directory is empty\n')
		print ('Base directory path is empty. Exititng P-AIRCARS.....\n')
		os.system('rm -rf casa*log')
		return 1
	if os.path.isdir(basedir)==False: # If basedir is not present making it
		print ('Base directory is not present. Making base directory at :'+basedir)
		try:
			os.makedirs(basedir)
		except:
			print('Give correct path. Base directory could not be made')
			return 1
	else:
		if basedir[-1]=='/':
			basedir=basedir[:-1]
		print ('Validating inputs........\n')
		if os.path.dirname(input_file)!=basedir:
			os.system('cp -r '+input_file+' '+basedir+'/selfcal_inputs.py')
		inpfil=open(basedir+'/selfcal_inputs.py','r+')
		lines=inpfil.readlines()
	sys.path.append(basedir)
	cwd=os.getcwd()
	os.chdir(basedir)
	import selfcal_inputs as inputs
	# Logger initiating
	###################
	formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
	mainlog = logging.getLogger('paircars_main_log')
	mainlog.setLevel(logging.DEBUG)
	console=logging.StreamHandler(sys.stdout)
	console.setFormatter(formatter)
	mainlog.addHandler(console)
	mainlog.propagate = False

	# Starting P-AIRCARS
	###################

	if os.path.isfile(basedir+'/.paircars_running'):
		mainlog.error('P-AIRCARS is already running in this base directory. Choose a different directory. Exiting P-AIRCARS......\n')
		os.system('rm -rf casa*log')
		return 1
	elif os.path.isfile(basedir+'/.paircars_finished'):
		mainlog.error('P-AIRCARS is already have final results in this base directory.\n')
		want_to_continue=input('Do you want to run it again? Y/y/N/n')
		if want_to_continue=='Y' or want_to_continue=='y':
			os.system('mv '+basedir+'/P-AIRCARS_mainlog.log temp.log')
			os.system('rm -rf '+basedir+'/*')
			os.system('rm -rf '+basedir+'.paircars_failed')
			loglist=len(glob.glob(basedir+'/P-AIRCARS_mainlog*.log'))
			os.system('mv temp.log '+basedir+'/P-AIRCARS_mainlog_'+str(loglist)+'.log')
			filehandle=logging.FileHandler(basedir+'/P-AIRCARS_mainlog.log')
			filehandle.setFormatter(formatter)
			mainlog.addHandler(filehandle)
		else:
			mainlog.info('Exiting the code.\n')
			os.system('rm -rf casa*log')
			return 1
	else:
		filehandle=logging.FileHandler(basedir+'/P-AIRCARS_mainlog.log')
		filehandle.setFormatter(formatter)
		mainlog.addHandler(filehandle)
		mainlog.info('Starting P-AIRCARS in fresh base directory.\n')

	# Validating calibrator caltables
	#################################
	if len(inputs.calibrator_caltable)==0:
		mainlog.info('No calibrator caltable is provided\n')
	else:
		for i in range(len(inputs.calibrator_caltable)): # If wrong calibrator caltable path is given, make the calibrator caltable list empty
			if os.path.isdir(inputs.calibrator_caltable[i])==False:
				mainlog.info('Calibrator caltable '+str(inputs.calibrator_caltable[i])+' is not present\n')
				calibrator_caltable.remove(inputs.calibrator_caltable[i])
			else:
				mainlog.info('Calibrator caltable '+str(inputs.calibrator_caltable[i])+' is present\n')
		for i in range(len(lines)):
			if 'calibrator_caltable' in lines[i]:
				lines[i]='calibrator_caltable='+str(inputs.calibrator_caltable)+'\n'

	
	# Validating Safety standard and quality factor
	###############################################
	if type(inputs.safety_factor)==int and inputs.safety_factor>2:
		mainlog.info('Safety factor is outside possible range. Setting it to default value : 1\n')
		inputs.safety_factor=1
		for i in range(len(lines)):
			if 'safety_factor' in lines[i]:
				lines[i]='safety_factor='+str(inputs.safety_factor)+'\n'
	elif type(inputs.safety_factor)!=int:
		mainlog.info('Safety factor was not integer. Setting it to default value : 1\n')
		inputs.safety_factor=1
		for i in range(len(lines)):
			if 'safety_factor' in lines[i]:
				lines[i]='safety_factor='+str(inputs.safety_factor)+'\n'
	###
	if type(inputs.quality_factor)==int and inputs.quality_factor>2:
		mainlog.info('Quality factor is outside possible range. Setting it to default value : 1\n')
		inputs.quality_factor=1
		for i in range(len(lines)):
			if 'quality_factor' in lines[i]:
				lines[i]='quality_factor='+str(inputs.quality_factor)+'\n'
	elif type(inputs.quality_factor)!=int:
		mainlog.info('Quality factor was not integer. Setting it to default value : 1\n')
		inputs.quality_factor=1
		for i in range(len(lines)):
			if 'quality_factor' in lines[i]:
				lines[i]='quality_factor='+str(inputs.quality_factor)+'\n'

	# Validating verbose and do_decor_correction
	############################################################
	if type(inputs.verbose)!=bool:
		mainlog.info('Verbose parameter was not boolean. Setting it to default value False.\n')
		inputs.verbose=False
		for i in range(len(lines)):
			if 'verbose' in lines[i]:
				lines[i]='verbose=False\n'
	if type(inputs.do_decor_correction)!=bool:
		mainlog.info('do_decor_correction parameter was not boolean. Setting it to default value True.\n')
		inputs.do_decor_correction=True
		for i in range(len(lines)):
			if 'do_decor_correction' in lines[i]:
				lines[i]='do_decor_correction=True\n'

	# Validating ref ant
	####################
	if type(inputs.ref_ant)==int and inputs.ref_ant>30:
		mainlog.info('Reference antenna was chosen beyond core 30 antennas. Setting it to default value 1.\n')
		inputs.ref_ant=1
		for i in range(len(lines)):
			if 'ref_ant' in lines[i]:
				lines[i]='ref_ant='+str(inputs.ref_ant)+'\n'
	elif type(inputs.ref_ant)!=int:
		mainlog.info('Given reference antenna parameter is not an integer.\n')
		try:
			inputs.ref_ant=int(inputs.ref_ant)
		except:
			inputs.ref_ant=1
		mainlog.info('Change reference antenna to :'+str(inputs.ref_ant)+'\n')
		for i in range(len(lines)):
			if 'ref_ant' in lines[i]:
				lines[i]='ref_ant='+str(inputs.ref_ant)+'\n'

	# Validating calc_image_parameters and calc_selfcalib_params
	############################################################
	if type(inputs.calc_image_parameters)!=bool:
		mainlog.info('calc_image_parameters was not boolean. Setting it to default value True.\n')
		inputs.calc_image_parameters=True
		for i in range(len(lines)):
			if 'calc_image_parameters' in lines[i]:
				lines[i]='calc_image_parameters=True\n'

	if type(inputs.calc_selfcalib_params)!=bool:
		mainlog.info('calc_selfcalib_params was not boolean. Setting it to default value True.\n')
		inputs.calc_selfcalib_params=True
		for i in range(len(lines)):
			if 'calc_selfcalib_params' in lines[i]:
				lines[i]='calc_selfcalib_params=True\n'

	# Validating the exsistence of maskfile
	#######################################
	if os.path.isdir(inputs.maskfile)==False:
		mainlog.info('Given maskfile is not present. Setting it to default value \' \'\n')
		inputs.maskfile=''
		for i in range(len(lines)):
			if 'maskfile' in lines[i]:
				lines[i]='maskfile=\''+inputs.maskfile+'\'\n'


	# Validating want_auto_masking
	##############################
	if type(inputs.want_auto_masking)!=bool:
		mainlog.info('want_auto_masking was not boolean. Seting it to default value False.\n')
		inputs.want_auto_masking=False
		for i in range(len(lines)):
			if 'want_auto_masking' in lines[i]:
				lines[i]='want_auto_masking=False\n'

	# Validating ref_time
	#####################
	try:
		ref_mjdsec=timestamp_to_mjdsec(inputs.ref_time,format=0)
	except:
		mainlog.info('Reference time format is not correct. Setting it default value.\n')
		inputs.ref_time=''
		for i in range(len(lines)):
			if 'ref_time' in lines[i]:
				lines[i]='ref_time=\'\'\n'

	# Validating cpu_frac
	#####################
	if inputs.cpu_frac>0.9:
		inputs.cpu_frac=0.9
		mainlog.info('CPU fraction was chosen more than 90%. Setting it to maximum value : 0.9\n')
		for i in range(len(lines)):
			if 'cpu_frac' in lines[i]:
				lines[i]='cpu_frac='+str(inputs.cpu_frac)+'\n'

	if inputs.cpu_frac==0:
		inputs.cpu_frac=0.5
		mainlog.info('CPU fraction was chosen to be 0%. Setting it to default value : 0.5\n')
		for i in range(len(lines)):
			if 'cpu_frac' in lines[i]:
				lines[i]='cpu_frac='+str(inputs.cpu_frac)+'\n'

	# Validating do_bandpass and do_polcal
	######################################
	if type(inputs.do_bandpass)!=bool:
		mainlog.info('do_bandpass was not boolean. Setting it to default value True.\n')
		do_bandpass=True
	for i in range(len(lines)):
		if 'do_bandpass' in lines[i]:
			lines[i]='do_bandpass='+str(inputs.do_bandpass)+'\n'

	if type(inputs.do_polcal)!=bool:
		mainlog.info('do_polcal was not boolean. Setting it to default value True.\n')
		inputs.do_polcal=True
	for i in range(len(lines)):
		if 'do_polcal' in lines[i]:
			lines[i]='do_polcal=True\n'

	# Validating send_notification and email address
	################################################
	if type(inputs.send_notification)!=bool or inputs.email=='':
		mainlog.info('send_notification was not boolean or no valid email is given. Setting it to default value False.\n')
		inputs.send_notification=False
		for i in range(len(lines)):
			if 'send_notification' in lines[i]:
				lines[i]='send_notification='+str(inputs.send_notification)+'\n'

	if inputs.email!='' and inputs.send_notification==False:
		mainlog.info('send_notification = False. Setting email address to to default value None.\n')	
		inputs.email=''
		for i in range(len(lines)):
			if 'email' in lines[i]:
				lines[i]='email=\'\'\n'

	# Validating use wsclean
	########################
	wsclean_datadir=os.path.abspath(os.path.dirname(paircarsdata.__file__))
	if type(inputs.use_wsclean)!=bool:
		inputs.use_wsclean=True
	if inputs.use_wsclean==True:
		wsclean_path=str(np.load(wsclean_datadir+'/wsclean_path.npy',allow_pickle=True))
		a=os.system(wsclean_path+'/wsclean > wsclean_test')
		if a!=0:
			print('WSClean is not installed. Using CASA for imaging.\n')
			inputs.use_wsclean=False
		os.system('rm -rf wsclean_test')
	for i in range(len(lines)):
		if 'use_wsclean' in lines[i]:
			lines[i]='use_wsclean='+str(inputs.use_wsclean)+'\n'	
	
	# Validating use_cubical
	########################
	if type(inputs.use_cubical)!=bool:
		inputs.use_cubical=True
	for i in range(len(lines)):
		if 'use_cubical' in lines[i]:
			lines[i]='use_cubical='+str(inputs.use_cubical)+'\n'		

	# Validating basic imaging parameters
	######################################
	if inputs.calc_image_parameters==False:
		if float(inputs.cellsize)==0 or inputs.imsize[0]==0:
			mainlog.info('calc_image_parameters=False, Have you drunk? Pixel size or image size can not 0. Setting it to default value.\n')	
			inputs.cellsize=80
			inputs.imsize=1280
			for i in range(len(lines)):
				if 'cellsize' in lines[i]:
					lines[i]='cellsize='+str(inputs.cellsize)+'\n'
				if 'imsize' in lines[i]:
					lines[i]='imsize=['+str(inputs.imsize)+']\n'

		if len(inputs.multiscale_scales)!=0:
			types=[type(i) for i in inputs.multiscale_scales]
			c=0
			for i in types:
				if i!=int:
					c+=1
			if c!=0:
				mainlog.info('Multiscale scale list should have anything other than integer. Setting it to default.')
				inputs.multiscale_scales='nan'
				for i in range(len(lines)):
					if 'multiscale_scales' in lines[i]:
						lines[i]='multiscale_scales='+str(inputs.multiscale_scales)+'\n'

		uvtaper_format_err=False
		if inputs.uvtaper!='':
			if 'lambda' not in inputs.uvtaper:
				uvtaper_format_err=True
			else:
				uvtaper_list=inputs.uvtaper.split('lambda')
				if uvtaper_list[-1]!='':
					uvtaper_format_err=True
				else:
					uvtaper_str=uvtaper_list[0]
					try:
						inputs.uvtaper=float(uvtaper_str)
					except:
						try:
							inputs.uvtaper=float(uvtaper_str[:-1])
						except:
							uvtaper_format_err=True
			if uvtaper_format_err==True:
				mainlog.info('uvtaper format is wrong. Setting it to default value.\n')
				for i in range(len(lines)):
					if 'uvtaper' in lines[i]:
						lines[i]='uvtaper=\'\'\n'

	# Validating selfcal parameters
	###############################
	if inputs.calc_selfcalib_params==False:
		#
		try:
			inputs.start_sigma=float(inputs.start_sigma)
			if inputs.start_sigma<7.0:
				mainlog.info('Start sigma is very low at :'+str(inputs.start_sigma)+'. Setting it to default value 8.0.\n')
				inputs.start_sigma=8.0
				for i in range(len(lines)):
					if 'start_sigma' in lines[i]:
						lines[i]='start_sigma='+str(8.0)+'\n'
		except:
			mainlog.info('Start sigma was not float or integer. Setting it to default value 10.0.\n')
			inputs.start_sigma=10.0
			for i in range(len(lines)):
				if 'start_sigma' in lines[i]:
					lines[i]='start_sigma='+str(10.0)+'\n'
		#
		try:
			inputs.sigma_step=float(inputs.sigma_step)
			if inputs.sigma_step>2:
				mainlog.info('Sigma step was greater than 2. Setting it to default value 1.5.\n')
				inputs.sigma_step=1.5
				for i in range(len(lines)):
					if 'sigma_step' in lines[i]:
						lines[i]='sigma_step='+str(1.5)+'\n'
			elif inputs.sigma_step==0:
				mainlog.info('Sigma step was 0.0. Setting it to default value 0.5.\n')
				inputs.sigma_step=0.5
				for i in range(len(lines)):
					if 'sigma_step' in lines[i]:
						lines[i]='sigma_step='+str(0.5)+'\n'
		except:
			mainlog.info('Sigma step was not float or integer. Setting it to default value 0.5.\n')
			inputs.sigma_step=0.5
			for i in range(len(lines)):
				if 'sigma_step' in lines[i]:
					lines[i]='sigma_step='+str(0.5)+'\n'
		#
		try:
			inputs.residual_frac=float(inputs.residual_frac)
			if inputs.residual_frac>=0.5:
				mainlog.info('residual_frac was greater than or equal to 0.5. Setting it to default value 0.1.\n')
				inputs.residual_frac=0.1
				for i in range(len(lines)):
					if 'residual_frac' in lines[i]:
						lines[i]='residual_frac='+str(0.1)+'\n'
			elif inputs.residual_frac==0:
				mainlog.info('residual_frac was 0. Setting it to default value 0.1.\n')
				inputs.residual_frac=0.1
				for i in range(len(lines)):
					if 'residual_frac' in lines[i]:
						lines[i]='residual_frac='+str(0.1)+'\n'
		except:
			mainlog.info('residual_frac was not float or integer. Setting it to default value 0.1.\n')
			inputs.residual_frac=0.1
			for i in range(len(lines)):
				if 'residual_frac' in lines[i]:
					lines[i]='residual_frac='+str(0.1)+'\n'
		#
		try:
			inputs.min_sigma=float(inputs.min_sigma)
			if inputs.min_sigma<5:
				mainlog.info('min_sigma is less than 5. Setting it to default value 5.0.\n')
				inputs.min_sigma=5.0
				for i in range(len(lines)):
					if 'min_sigma' in lines[i]:
						lines[i]='min_sigma='+str(5.0)+'\n'
		except:
			mainlog.info('min_sigma was not float or integer. Setting it to default value 8.0.\n')
			inputs.min_sigma=8.0
			for i in range(len(lines)):
				if 'min_sigma' in lines[i]:
					lines[i]='min_sigma='+str(8.0)+'\n'

		#
		uv_format_err=False
		if inputs.uvrange_to_cal!='':
			if 'lambda' not in inputs.uvrange_to_cal:
				uv_format_err=True
			else:
				uv_list=inputs.uvrange_to_cal.split('lambda')
				if uv_list[-1]!='':
					uv_format_err=True
				else:
					uv_str=uv_list[0]
					if uv_str[-1]=='k':
						uv_str=uv_str[:-1]
					if '~' not in uv_str and '>' not in uv_str and '<' not in uv_str:
						uv_format_err=True
					elif '~' in uv_str:
						uv_str_list=uv_str.split('~')
						if len(uv_str_list)!=3:
							uv_format_err=True
						else:
							try:
								a=float(uv_str_list[0])
								b=float(uv_str_list[1])
							except:
								uv_format_err=True
					elif '>' in uv_str:
						uv_str_list=uv_str.split('>')
						if len(uv_str_list)!=2:
							uv_format_err=True
						else:
							try:
								a=float(uv_str_list[1])
							except:
								uv_format_err=True
					elif '<' in uv_str:
						uv_str_list=uv_str.split('<')
						if len(uv_str_list)!=2:
							uv_format_err=True
						else:
							try:
								a=float(uv_str_list[1])
							except:
								uv_format_err=True

			if uv_format_err==True:
				inputs.uvrange_to_cal=''
				mainlog.info('uvrange format is wrong. Setting it to default value.\n')
				for i in range(len(lines)):
					if 'uvrange_to_cal' in lines[i]:
						lines[i]='uvrange_to_cal=\''+str(inputs.uvrange_to_cal)+'\'\n'
		
		###
		try:
			inputs.gain_minsnr=float(inputs.gain_minsnr)
			if inputs.gain_minsnr<3.0:
				mainlog.info('Gain SNR is less than 3.0. Setting it to default 3.0.\n')
				inputs.gain_minsnr=3.0
				for i in range(len(lines)):
					if 'gain_minsnr' in lines[i]:
						lines[i]='gain_minsnr='+str(3.0)+'\n'
		except:
			mainlog.info('gain_minsnr was not float or integer. Setting it to default value 3.0.\n')
			inputs.gain_minsnr=3.0
			for i in range(len(lines)):
				if 'gain_minsnr' in lines[i]:
					lines[i]='gain_minsnr='+str(3.0)+'\n'
		###

		try:
			if type(inputs.DR_delta)!=int or type(inputs.DR_delta)!=float:
				inputs.DR_delta=int(inputs.DR_delta)
		except:
			mainlog.info('DR_delta could not be convereted to integer. Setting it to default value 20.\n')
			inputs.DR_delta=20
			for i in range(len(lines)):
				if 'DR_delta' in lines[i]:
					lines[i]='DR_delta='+str(20)+'\n'
		###
		
		if type(inputs.max_DR)!=int or type(inputs.max_DR)!=float:
			try:
				inputs.max_DR=int(inputs.max_DR)
				if inputs.max_DR==0:
					mainlog.info('max_DR = 0. Setting it to default value 10000.\n')
					inputs.max_DR=10000
					for i in range(len(lines)):
						if 'max_DR' in lines[i]:
							lines[i]='max_DR='+str(10000)+'\n'
			except:
				mainlog.info('max_DR was not an integer or float or could not be converted to integer/float. Setting it to default value 10000.\n')
				inputs.max_DR=10000
				for i in range(len(lines)):
					if 'max_DR' in lines[i]:
						lines[i]='max_DR='+str(10000)+'\n'

		if type(inputs.min_DR)!=int or type(inputs.min_DR)!=float:
			try:
				inputs.min_DR=int(inputs.min_DR)
				if inputs.max_DR==0:
					mainlog.info('min_DR = 0. Setting it to default value 20.\n')
					inputs.min_DR=20
					for i in range(len(lines)):
						if 'min_DR' in lines[i]:
							lines[i]='min_DR='+str(20)+'\n'
			except:
				inputs.min_DR=20
				if inputs.min_DR>inputs.max_DR:
					mainlog.info('min_DR is greater than max_DR. Setting it to default 20.\n')
					inputs.min_DR=20
					for i in range(len(lines)):
						if 'min_DR' in lines[i]:
							lines[i]='min_DR='+str(inputs.min_DR)+'\n'
				else:
					mainlog.info('min_DR was not an integer or float or could not be converted to integer/float. Setting it to default value 20.\n')
					for i in range(len(lines)):
						if 'min_DR' in lines[i]:
							lines[i]='min_DR='+str(20)+'\n'
		
		if type(inputs.min_selfcal_snr)!=int or type(inputs.min_selfcal_snr)!=float:
			try:
				inputs.min_selfcal_snr=int(inputs.min_selfcal_snr)
				if inputs.min_selfcal_snr<3:
					mainlog.info('min_selfcal_snr is less than 3. Setting it to default value 3.\n')
					inputs.min_selfcal_snr=3
					for i in range(len(lines)):
						if 'min_selfcal_snr' in lines[i]:
							lines[i]='min_selfcal_snr='+str(inputs.min_selfcal_snr)+'\n'
			except:
				inputs.min_selfcal_snr=3
				mainlog.info('min_selfcal_snr was not an integer or float or could not be converted to integer/float. Setting it to default value 3.\n')
				for i in range(len(lines)):
					if 'min_selfcal_snr' in lines[i]:
						lines[i]='min_selfcal_snr='+str(inputs.min_selfcal_snr)+'\n'

	# Validating flagging parameters
	################################

	if type(inputs.want_uvsub_flag)!=bool:
		mainlog.info('want_uvsub_flag was not an boolean. Setting it to default value False.\n')
		inputs.want_uvsub_flag=False
		for i in range(len(lines)):
			if 'want_uvsub_flag' in lines[i]:
				lines[i]='want_uvsub_flag='+str(False)+'\n'
	if type(inputs.use_ankflagger)!=bool:
		mainlog.info('use_ankflagger was not an boolean. Setting it to default value True.\n')
		inputs.use_ankflagger=False
		for i in range(len(lines)):
			if 'use_ankflagger' in lines[i]:
				lines[i]='use_ankflagger='+str(False)+'\n'
	elif inputs.want_uvsub_flag==True:
		if inputs.use_ankflagger:
			try:
				from paircarsutils.aNKflag import runank
				inputs.use_ankflagger=True
			except:
				mainlog.info('aNKflag can not be imported. Not using aNKflagger.\n')
				inputs.use_ankflagger=False
			for i in range(len(lines)):
				if 'use_ankflagger' in lines[i]:
					lines[i]='use_ankflagger='+str(inputs.use_ankflagger)+'\n'

	# Validating image export options
	#################################
	if inputs.savedir!='':
		basedir_path=inputs.basedir.split('/')
		if 'basedir_for' in basedir_path[-1]:
			save_basedir='/'.join(basedir_path[:-1])
		else:
			save_basedir=inputs.basedir
		if os.path.isdir(inputs.savedir)==False:
			mainlog.info('savedir is not present. Making save directory.\n')
			try:
				os.makedirs(inputs.savedir)
			except:
				mainlog.info('Save directory is not made. Settings save directory to base directory.\n')
				inputs.savedir=save_basedir+'/final_images'
				if os.path.isdir(inputs.savedir)==False:
					os.makedirs(inputs.savedir)
		else:
			mainlog.info('Setting save directory to base directory.\n')
			inputs.savedir=save_basedir+'/final_images'
			if os.path.isdir(inputs.savedir)==False:
				os.makedirs(inputs.savedir)
		for i in range(len(lines)):
			if 'savedir' in lines[i]:
				lines[i]='savedir=\''+str(inputs.savedir)+'\'\n'

	if inputs.final_image_dir!='':
		basedir_path=inputs.basedir.split('/')
		if 'basedir_for' in basedir_path[-1]:
			save_basedir='/'.join(basedir_path[:-1])
		else:
			save_basedir=inputs.basedir
		if os.path.isdir(inputs.final_image_dir)==False:
			mainlog.info('final_image_dir is not present. Making save directory.\n')
			try:
				os.makedirs(inputs.final_image_dir)
			except:
				mainlog.info('Save directory is not made. Setting save directory to base directory.\n')
				inputs.final_image_dir=save_basedir+'/final_images'
				if os.path.isdir(inputs.final_image_dir)==False:
					os.makedirs(inputs.final_image_dir)
		else:
			mainlog.info('Setting save directory to base directory.\n')
			inputs.final_image_dir=save_basedir+'/final_images'
			if os.path.isdir(inputs.final_image_dir)==False:
				os.makedirs(inputs.final_image_dir)
		for i in range(len(lines)):
			if 'final_image_dir' in lines[i]:
				lines[i]='final_image_dir=\''+str(inputs.final_image_dir)+'\'\n'

	if type(inputs.savemodel)!=bool:
		mainlog.info('savemodel was not boolean. Set it default value False.\n')
		for i in range(len(lines)):
			if 'savemodel' in lines[i]:
				lines[i]='savemodel='+str(False)+'\n'
		
	if type(inputs.saveresidual)!=bool:
		mainlog.info('saveresidual was not boolean. Set it default value False.\n')
		for i in range(len(lines)):
			if 'saveresidual' in lines[i]:
				lines[i]='saveresidual='+str(False)+'\n'

	# Writing corrected parameters
	##############################

	inpfil.seek(0)
	inpfil.writelines(lines)
	inpfil.close()
	os.system('rm -rf casa*log')
	mainlog.info('Input file validation complete.\n')
	os.getcwd()
	return basedir+'/selfcal_inputs.py'	
	

if __name__=='__main__':
	main()






