;+
; NAME:
;         p3d_misc_initialize
;
;         $Id: p3d_misc_initialize.pro 83 2010-03-05 11:33:06Z olestreicher $
;
; PURPOSE:
;         This routine sets up system variables for p3d:
;
;         !p3d_path ::
;          The directory where the p3d distribution is found. Nothing is done if
;          !p3d_path is already set. If it is not then the first option is to
;          use the system environmental variable p3d_path. The second option is
;          to the directory where this routine is found.
;
;         !p3d_data_path ::
;          A directory which is first used when starting file dialogs of data
;          to reduce. Nothing is done if !p3d_data_path is already set. If it is
;          not then the first option is to use the system environmental variable
;          p3d_data_path. A second option is to use the user home directory (if
;          found).
;
;         This routine also checks if the necessary routines of mpfit
;         (mpfit.pro and mpcurvefit.pro) are available. These two routines are
;         used when calculating cross-dispersion line profiles on the trace
;         mask, and are subsequently used in the optimal extraction routine.
;         The required routines can be downloaded using the provided script in:
;         ${p3d_path}/vm/.
;
; AUTHOR:
;         Christer Sandin
;         Astrophysikalisches Institut Potsdam (AIP)
;         An der Sternwarte 16
;         D-14482 Potsdam, GERMANY
;
; COPYRIGHT:
;         p3d: a general data-reduction tool for fiber-fed IFSs
;
;         Copyright 2009,2010 Astrophysikalisches Institut Potsdam (AIP)
;
;         This program is free software; you can redistribute it and/or modify
;         it under the terms of the GNU General Public License as published by
;         the Free Software Foundation; either version 3 of the License, or
;         (at your option) any later version.
;
;         This program is distributed in the hope that it will be useful, but
;         WITHOUT ANY WARRANTY; without even the implied warranty of
;         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;         General Public License for more details.
;
;         You should have received a copy of the GNU General Public License
;         along with this program; if not, see <http://www.gnu.org/licenses>.
;
;         Additional permission under GNU GPL version 3 section 7
;
;         If you modify this Program, or any covered work, by linking or
;         combining it with IDL (or a modified version of that library),
;         containing parts covered by the terms of the IDL license, the
;         licensors of this Program grant you additional permission to convey
;         the resulting work.
;
; CATEGORY:
;         p3d :: auxiliary routines
;
; CALLING SEQUENCE:
;         p3d_misc_initialize,mpfitpresent,verbose=,error=,/help
;
; KEYWORD PARAMETERS:
;         verbose         - Show more information on what is being done.
;         error           - Returns an error code if set.
;         help            - Show this routine documentation, and exit.
;
; OUTPUTS:
;         mpfitpresent    - This keyword is set to 1 if mpfit.pro and
;                           mpcurvefit.pro are found in !path.
;
; COMMON BLOCKS:
;         none
;
; SIDE EFFECTS:
;         none
;
; RESTRICTIONS:
;         IDL version 6.2 or higher is required.
;
; MODIFICATION HISTORY:
;         22.10.2008 - This is a new routine. /CS
;-
PRO p3d_misc_initialize_addpath,path
  compile_opt hidden,IDL2

  ;;========================================------------------------------
  ;; Checking if PATH is in !path, if not, then it is added:

  tmp=strpos(path,path_sep(),/reverse_search)
  path_=tmp eq strlen(path)-1L?strmid(path,0L,tmp):path
  tmpx=path_+':'+path_+path_sep()+'routines' & slen=strlen(tmpx)

  path=!path
  tmp=strpos(path,tmpx)
  ;; Removing all current occurences of !p3d_path from !path (cleaning up):
  while tmp ne -1L do begin
    path=strmid(path,tmp+1L+slen)
    tmp=strpos(path,tmpx)
  endwhile

  ;; Setting up !path anew:
  !path=tmpx+':'+path

  return
END ;;; procedure: p3d_misc_initialize_addpath


PRO p3d_misc_initialize,mpfitpresent,verbose=verbose,error=error,help=help
  compile_opt hidden,IDL2

  if !version.release lt 6.2 then message,'IDL Version <6.2. Cannot continue.'
  error=0 & rname='p3d_misc_initialize: '
  if ~n_elements(verbose) then verbose=0

  if keyword_set(help) then begin
    doc_library,'p3d_misc_initialize'
    return
  endif

  ;;========================================------------------------------
  ;; Setting up a system variable holding the main p3d directory:

  defsysv,'!p3d_path',exists=pexists
  if ~pexists then begin

    tmp=getenv('p3d_path')
    if tmp eq '' then begin
      tmp=file_search(strsplit(!path,path_sep(/search_path),/extract)+ $
                      path_sep()+'p3d.pro')
      if tmp[0] eq '' then begin
        print,rname+'The path to where the p3d distribution is found is'
        print,rname+'unknown. Either set the IDL system variable !p3d_path' + $
              ', or'
        print,rname+'the system environmental variable p3d_path, or includ' + $
              'e the'
        print,rname+'directory where p3d.pro is found in !path - before st' + $
              'arting this program.'
        errmsg='Cannot continue.'

        goto,error_handler
      endif else begin
        tmp=tmp[0]
        tmp=strmid(tmp,0,1+strpos(tmp,path_sep(),/reverse_search))
        if verbose ge 2 then $
           print,rname+'Extracted p3d_path from !path, !p3d_path="'+tmp+'".'
      endelse
    endif else begin
      if verbose ge 2 then $
         print,rname+'Using the system environmental variable p3d_path="' + $
               tmp + '".'
    endelse
    tmp+=(strpos(tmp,path_sep(),/reverse_search) eq strlen(tmp)-1L)?'': $
         path_sep()
    defsysv,'!p3d_path',tmp

  endif else begin ;; ~pexists
    if verbose ge 2 then $
       print,rname+'Using the system variable !p3d_path="'+!p3d_path+'".'
  endelse ;; ~pexists

  if ~file_test(!p3d_path,/directory) then begin
    print,rname+'The directory !p3d_path="'+!p3d_path+'" does not exist.'
    errmsg='Cannot continue!'
    goto,error_handler
  endif

  ;; Adding !p3d_path to !path:
  p3d_misc_initialize_addpath,!p3d_path

  ;;========================================------------------------------
  ;; Setting up the p3d data directory:

  defsysv,'!p3d_data_path',exists=pexists
  if ~pexists then begin

    tmp=getenv('p3d_data_path')
    if tmp[0] eq '' then begin
      print,rname+'The path to where the data to use with the p3d distrib' + $
            'ution is found is unknown.'
      print,rname+'You could either set the IDL system variable' + $
        ' "!p3d_data_path", or'
      print,rname+'the system environmental variable "p3d_data_path". '

      cd,current=tmp
      print,rname+'Using the current directory ['+tmp+'].'

    endif else begin
      if verbose ge 2 then $
         print,rname+'Using the system environmental variable p3d_data_pat' + $
               'h="' + tmp + '".'
    endelse
    tmp+=(strpos(tmp,path_sep(),/reverse_search) eq strlen(tmp)-1L)?'': $
         path_sep()
    defsysv,'!p3d_data_path',tmp
    
  endif else begin ;; ~pexists
    if verbose ge 2 then $
       print,rname+'Using the system variable !p3d_data_path="'+ $
             !p3d_data_path+'".'
  endelse ;; ~pexists

  defsysv,'!p3d_data_path',exists=exists
  if exists then begin
    tmp=strpos(!p3d_data_path,path_sep(),/reverse_search)
    if tmp ne strlen(!p3d_data_path)-1L then begin
      tmp=!p3d_data_path+path_sep()
      defsysv,'!p3d_data_path',tmp
    endif
  endif

  if ~file_test(!p3d_data_path,/directory) then begin
    print,rname+'The directory !p3d_data_path="'+!p3d_data_path+ $
          '" does not exist.'
    errmsg='Cannot continue!'
    goto,error_handler
  endif

  ;;========================================------------------------------
  ;; Checking for the existence of mpfit.pro and mpcurvefit.pro and
  ;; other files:

  mpfitpresent=1L
;  mpfitpresent=0L
;  tmp1=file_search(strsplit(!path,path_sep(/search_path),/extract)+ $
;           path_sep()+'mpfit.pro')
;  tmp2=file_search(strsplit(!path,path_sep(/search_path),/extract)+ $
;           path_sep()+'mpcurvefit.pro')
;
;  if tmp1[0L] ne '' and tmp2[0L] ne '' then mpfitpresent=1L
;
;  ;; Checking for some other files (of astro-lib):
;  tmp1=file_search(strsplit(!path,path_sep(/search_path),/extract)+ $
;           path_sep()+'readcol.pro')
;  if tmp1[0L] eq '' then begin
;    print,'Cannot find the astro-lib routine "readcol.pro".'
;    print,'Please make sure the astro-lib routines are in the path of IDL.'
;    print,'  [You could use the script ${p3d_path}/vm/p3d_acquire_xtools.sh'
;    print,'   to download all required supplementary routines.]'
;    errmsg='  Cannot continue!'
;    goto,error_handler
;  endif

  return

error_handler:
  message,errmsg,/informational
  error=-1
  return
END ;;; procedure: p3d_misc_initialize
