      SUBROUTINE CALCMAG (z,k,result)
c
c calculate plate magnitude for this star
c k: 1=J 2=F 3=N 4=O 5=E
c z(6) = standard magnitude/colors for this star
c       in order: V, B-V, U-B, V-R, R-I, V-I
c return: plate magnitude if it can determined for this object
c  else 99.999
c written 14-Oct-94 AAH
c
      REAL*4 z(6),fx(15,10),fy(15,10),base,rise,run
      REAL*4 result
      INTEGER indx,iflag,nentry(10),isub(2,10),jflag(10)
      INTEGER i,j,k,jj
      DATA iflag /0/
      COMMON/cmblk/nentry, isub, jflag, fx, fy
c
      IF (iflag.eq.0) THEN
        open (unit=33,file='tables.txt',status='old')
        DO i=1,10
          read (33,9000,end=10) nentry(i),(isub(j,i),j=1,2),jflag(i)
9000      format(8x,4i5)
          DO j=1,nentry(i)
            read (33,9001) fx(j,i),fy(j,i)
9001        format(2f7.3)
          ENDDO
        ENDDO
10      CONTINUE
        iflag = 1
        close(33)
      ENDIF
c now find right table for this star/plate
c four tests:
c (1) (B-V) best and good (B-V)
      indx = k*2-1
      jj = 2
      IF (jflag(indx).gt.0.and.fx(1,indx).le.z(jj)
     $  .and.z(jj).le.fx(nentry(indx),indx)) GOTO 100
c (2) (V-R) best and good (V-R)
      indx = k*2
      jj = 4
      IF (jflag(indx).gt.0.and.fx(1,indx).le.z(jj)
     $  .and.z(jj).le.fx(nentry(indx),indx)) GOTO 100
c (3) good (B-V)
      indx = k*2-1
      jj = 2
      IF (fx(1,indx).le.z(jj).and.
     $   z(jj).le.fx(nentry(indx),indx)) GOTO 100
c (4) good (V-R)
      indx = k*2
      jj = 4
      IF (fx(1,indx).le.z(jj).and.
     $   z(jj).le.fx(nentry(indx),indx)) GOTO 100
c else just return
      result = 99.999
      RETURN
100   CONTINUE
c find appropriate standard magnitude that forms (J-n) etc.
      base = z(isub(1,indx))
      IF (isub(2,indx).ne.0) base = base - z(isub(2,indx))
c do piecewise linear interpolation in appropriate table
      DO i=1,nentry(indx)-1
        IF (z(jj).ge.fx(i,indx).and.
     $      z(jj).le.fx((i+1),indx)) THEN
          rise = fy((i+1),indx) - fy(i,indx)
          run = fx((i+1),indx) - fx(i,indx)
          result = base + fx(i,indx) + (z(jj)-fx(i,indx))*rise/run
          GOTO 200
        ENDIF
      ENDDO
      result = 88.888
200   CONTINUE
      RETURN
      END
