      SUBROUTINE OPENDENSEFILES(npots,jpotlevs,ireqpars,ip2,
     *  maxlevel,ioutfile,maxparm,maxpot,inewfile,iposfile,m,
     *  ipressno)

C     OPENDENSEFILES OPENS FILES CONTAINING VARIABLES
C     ON GIVEN DENSITY SURFACES, ALWAYS INCLUDING
C     PRESSURE

      parameter (maxlevloc=6000)
      character*3 mtype
      character*5 cnew
      character*8 cpot
      character*80 filename,cfile
      
      common /parname1/ mtype(maxlevloc)

      dimension ip2(0:maxlevel),ioutfile(0:maxparm,maxpot)
      dimension iposfile(maxpot)
      dimension jpotlevs(maxpot)

c     set for new or old file open

      if ( inewfile .eq. 1 ) then
       cnew='w+'//CHAR(0)
      else
       cnew='rb+'//CHAR(0)
      endif

c     run through for each requested reference surface

      do 45 n=1,npots

c     create character representation of reference surface

       ipot=0
       if ( jpotlevs(n) .lt. 0 ) then
        cpot='insitu'
        ipot=6
       elseif ( jpotlevs(n) .lt. 1 ) then
        cpot='surf'
        ipot=4
       elseif ( jpotlevs(n) .lt. 1000 ) then
        cpot='500'
        ipot=3
       else
        write(cpot(1:4),'(i4)') jpotlevs(n)
        ipot=4
       endif

c     open position file

      cfile='pos'//cpot(1:ipot)//CHAR(0)
      call densesurffilename(cfile,m,filename)
      if ( iposfile(n) .eq. 0 ) iposfile(n)=-1
      call fileopen(filename,cnew,iposfile(n))

c     open variable files

       ipress=0
       do 50 i0=1,ireqpars
        if ( ip2(i0) .eq. 25 ) ipress=1
        cfile=mtype(ip2(i0))(1:1)//cpot(1:ipot)//
     * CHAR(0)
        call densesurffilename(cfile,m,filename)
        if ( ioutfile(ip2(i0),n) .eq. 0 ) ioutfile(ip2(i0),n)=-1
        call fileopen(filename,cnew,ioutfile(ip2(i0),n))
50     continue
       
       if ( ipress .eq. 0 .and. ipressno .eq. 0 ) then
        cfile=mtype(25)(1:1)//cpot(1:ipot)//CHAR(0)
        call densesurffilename(cfile,m,filename)
        if ( ioutfile(25,n) .eq. 0 ) ioutfile(25,n)=-1
        call fileopen(filename,cnew,ioutfile(25,n))
       endif
45    continue

      return
      end

