### This script fetches level-1 PACS imaging data, using a list generated by the
### archive (in the CSV format), attaches sky coordinates and masks to them
### (by calling the convertL1ToScanam task) and save them to disk in the correct
### format for later use by Scanamorphos.
### See important instructions below.


#######################################################

### This script is part of the Scanamorphos package.

###  HCSS is free software: you can redistribute it and/or modify
###  it under the terms of the GNU Lesser General Public License as
###  published by the Free Software Foundation, either version 3 of
###  the License, or (at your option) any later version.

#######################################################

## Import classes and definitions:
import os
from herschel.pacs.spg.phot import ConvertL1ToScanamTask

#######################################################


## local settings:

dir_root = "/pcdisk/stark/aribas/Desktop/modeling_TDs/remaps_Cha/PACS/scanamorphos/"
path = dir_root +"L1/"

### number of observations:
n_obs = 2


#######################################################

## Do a multiple target search in the archive and use the "save all results as CSV" option.
## --> ascii table 'results.csv' where lines can be edited
## (suppress unwanted observations and correct target names)

## Create the directories contained in the dir_out variables (l. 57)
## before running this script.

#######################################################


## observations:
table_obs = asciiTableReader(file=dir_root+'results_fast.csv', tableType='CSV', skipRows=1)
list_obsids = table_obs[0].data
list_names = table_obs[1].data


for i_obs in range(n_obs):
    ##
    num_obsid = list_obsids[i_obs]
    source = list_names[i_obs]
    source = str.lower(str(source))
    dir_out = path+source+"_processed_obsids"
    # create directory if it does not exist
    if not(os.path.exists(dir_out)):
        os.system('mkdir '+dir_out)
	##
    print ""
    print "Downloading obsid " + `num_obsid`
    obs = getObservation(num_obsid, useHsa=True, instrument="PACS", verbose=True)
    ###
    frames = obs.level1.refs["HPPAVGR"].product.refs[0].product
    convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)
    ###
    frames = obs.level1.refs["HPPAVGB"].product.refs[0].product
    convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)


### END OF SCRIPT

#######################################################
