      program kylie

C***********************************************
C
C This program (so-named coz it's short and sweet)
C is designed to take raw output files from the
C program bruce, containing velocity, temperature,
C gravity, cosMu and projected area values for elements
C across the surface of a star, and use Keith Smith's
C tgprof3 routine to calculate spectra for the all
C the elements summed. The parameters for kylie are
C read in from a file pointed to by the environment
C parameter KYLIE_PARAMS; this file specifies the
C wavelength grid now
C
C Started   :25/9/95
C Modified  :11/10/95
C            4/9/96 - If the user specifies the
C            LIMB_BETA_OVERRIDE parameter in the #FIELDS
C            command, the limb-darkening is done artificially
C            using the supplied limb-darkening beta
C
C Modified  :19/7/97 - Modified to take command files from
C            standard input; DEC Fortran specific bits removed
C
C            8/1/99 - Made the output reporting more sensible,
C                     and renamed errcnt to nOut
C
C            3/2/99 - Put in a check to abort if temperatures
C                     or gravities drop below zero
C
C***************************************************

C Turn off implicit typing...

      implicit none

C Define the hard-wired parameters

      include "kylie.compar_define.inc"

C *** Start of Include block load ***

C Load in the File control common block

      include "kylie.filcon_common.inc"

C Load in the File names common block

      include "kylie.filnam_common.inc"

C Load in the wavelength/field common block

      include "kylie.wavfld_common.inc"

C LOad in the angles and constants include file

      include "angles.inc"

      include "constants.inc"

C *** End of Include Block Load ***

C Delclare the in-program variables

      character*80 string               ! A string variable to hold filenames, titles etc...
      character*80 title		! The title of the spectra written out
      character*24 getlog	        ! The login name of the user
      character*24 fdate	        ! The date at which the routine is run
      integer getcwd		        ! The get cwd function
      integer ierrno		        ! The error returned by getcwd
      integer ferr		        ! The error number for a file operation
      integer wcount		        ! Counter to loop over the wavelength grid points
      integer fcount			! Counter to loop through the fields to be processed
      integer gcount			! Counter to loop through the visible grid points of each field
      integer GrdVis			! The number of visible grid points for a given field
      integer nOut                      ! number of points outside tgkiel grids
      integer nIn                       ! number of points inside tgkiel grids
      logical ok		        ! A status value for some of the routines

      real FTime			! The times of the input dump files
      real FGrid(NWGrid)	        ! The absoulte flux grid
      real WRest			! The rest wavelength of an observed wavelength
      real dummy		        ! A dummy (scratch) variable

      real VProj		        ! The projected velocity
      real AProj			! The projected area
      real Grav				! The gravity
      real Temp				! The temperature
      real CosMu			! Cos(mu)
      real tgprof3			! Keith's tgkiel

C Declare the external, DEF Fortran-specific routines

      external getenv			! The external routine to read an environment variable
      external getlog			! The external function to read the login name
      external getcwd			! The external function to read the current dir
      external fdate

C Print out the introductory banner

      write(chandl,'('' Kylie Version '',F4.2,'' ('',A,'')'')')
     :                                             Version, Date
      write(chandl,'('' -------------------------------------------'',
     :''---------------'')')

C Call klojob to parse the standard input command file (which has file handle fhandl)
      
      call klojob(ok)

C Check that all was OK; otherise jump to the end of the program

      if(.not.ok) goto 9000

C Print out the number of wavelength points

      write(chandl,'(I5,'' Wavelength Grid points found'')') NWDef

C Initialise tgprof3
C MODIFY:
C **************************************************************
C *** REPLACE THIS WITH YOUR SPECTRAL-SYNTHESIS INIT ROUTINE ***
C **************************************************************
      
      dummy=tgprof3(0.,0.,0.,0.,ok)

C Check it loaded OK

      if(.not.ok) then
        write(ehandl,'('' *** There was an error attempting'',
     :  '' to initialise the model atmospheres'')')
        goto 9000
      endif

C Print out a separator line

      write(chandl,'(A)') ' '
      write(chandl,'('' -------------------------------------------'',
     :''-------------------------'')')
      write(chandl,'(1X,''Filename            '',1X,''Grid Size'',1X,
     :  ''   TgK In'',1X,''  TgK Out'',1X,''  TgK Tot'',1X,
     :  ''  % Out'')')
      write(chandl,'('' -------------------------------------------'',
     :''-------------------------'')')

C Loop over the number of fields defined (hope they are all there!)

      do fcount=1,NField,1

C Zero the data in the flux grid...

      do wcount=1,NWDef,1
        FGrid(wcount)=0.0
      enddo

C Get the name of the field into string

      write(string,'(A,I3.3)') 
     :  DmStub(1:index(DmStub,' ')-1),fcount

C Open the current dump file

      open(unit=dhandl,status='old',file=string,form='UNFORMATTED')

C Grab the number of visible grid points from the input file and the time

      read(dhandl) GrdVis,FTime

C Zero the TGkiel counters

      nOut=0
      nIn=0

C Read in the stellar parameters GrdVis times...

      do gcount=1,GrdVis,1

        read(dhandl) Temp,VProj,AProj,Grav,CosMu

C Check that the values are reasonable

        if(Grav.lt.0.) then
          write(chandl,'(''*** A negative-gravity point was '',
     :  ''found in the file'',A)') string(1:index(string,' '))
          goto 9000
        endif

        if(Temp.lt.0.) then
          write(chandl,'(''*** A negative-temperature point was '',
     :  ''found in the file'',A)') string(1:index(string,' '))
          goto 9000
        endif

C Covert the gravity into dex

        Grav=log10(Grav)+2.0

C Update the flux grid for this grid point

        do wcount=1,NWDef,1

C Get the rest wavelength of the wavelength we are looking at. Note that
C the velocity convention is that a positive velocity is a velocity *towards*
C the observer.

          WRest=WGrid(wcount)/(1.0-VProj/CLight)

C Call TGProf3 to set up the flux at this wavelength; if an error
C is returned, increment the error counter

C MODIFY:
C ***********************************************************************
C *** REPLACE THIS WITH YOUR SECTRAL-SYNTHESIS ROUTINE. IN THIS CASE, ***
C *** TGPROF3(T,G,M,W,O) RETURNS THE INTENSITY AT TEMPERATURE T,      ***
C *** GRAVITY G, LIMB-PARAMTER M (SAME AS COS THETA), REST WAVELENGTH ***
C *** W, AND SETS OK TO .TRUE. TO SIGNIFY SUCCESS.                    ***
C ***********************************************************************

          ok=.true.
          if(LimbB.lt.0) then
            FGrid(wcount)=FGrid(wcount)+
     :      AProj*tgprof3(Temp,Grav,CosMu,WRest,ok)
            if(.not.ok) then
              nOut=nOut+1
            else
              nIn=nIn+1
            endif
          else
            FGrid(wcount)=FGrid(wcount)+
     :      AProj*tgprof3(Temp,Grav,1.,WRest,ok)*
     :      ((1.-LimbB)+LimbB*CosMu)
            if(.not.ok) then
              nOut=nOut+1
            else
              nIn=nIn+1
            endif
          endif

C Loop back around to do the next wavelength point...

        enddo

C Get the next grid element from the raw file by looping back around...

      enddo

C Close the file...

      close(dhandl,iostat=ferr,err=8000)

C Write out the flux array to an .sdf file

      title=string(1:index(string,' ')-1)//'.sdf'

C MODIFY:
C *******************************************************
C *** REPLACE THIS WITH YOUR SPECTRUM-WRITING ROUTINE ***
C *******************************************************

      call wrsdf1(title(1:index(title,' ')-1),
     :            title(1:index(title,' ')-1),
     :            'Wavelength',
     :            'Flux',
     :            'Angstrom',
     :            'cgs',
     :            NWGrid,
     :            NWDef,
     :            WGrid,
     :            FGrid,
     :            ok)

C Print out some summary information

      write(chandl,'(1X,A20,1X,I9,1X,I9,1X,I9,1X,I9,5X,I3)') title,
     :  GrdVis,nIn,nOut,nOut+nIn,int(nOut/real(nOut+nIn)*100)

C Now loop back to get the name of the next dump file and open it up

      enddo

C Jump to the end of the program for a normal exit...

      goto 9000

C Error jump-in for failure on a dump file

 8000 continue

      write(chandl,'(''*** An error was encountered whilst'',
     :'' trying to acess the file '',A)') string
      goto 9000

C End pof program jump-in point

 9000 continue

      end
