#!/bin/ksh 
#  Execute: params_erro.ksh 20130803 20130804 BOIA_SC 00

     dateini=$1
     datefin=$2
     station=$3
     hourfcst=$4

     file_in=/scratchout/grupos/oceano/rosio.camayo/validation/validate_pesq/d-input/d-mod_vs_obs/all/mod_obs_${station}_${dateini}_${datefin}_${hourfcst}
     file_out=/scratchout/grupos/oceano/rosio.camayo/validation/validate_pesq/d-input/d-mod_vs_obs/all/params_erro_${station}_${dateini}_${datefin}_${hourfcst}.dat

     np=$(wc  -l $file_in | awk '{print $1}')
    
cat <<EOF> params_erro.f90

!    REAL, DIMENSION ( $nfre )    :: FRE , PER, EFRE
     REAL :: TIMEJUL,H_OBS, H_WWW

    OPEN(80,FILE='$file_in', STATUS='UNKNOWN', FORM='FORMATTED' )
    OPEN(90,FILE='$file_out', STATUS='UNKNOWN', FORM='FORMATTED' )

!  ---   zerar variaveis estatisticas

    N_C   = 0.
    S_OBS = 0.
    S_WWW = 0.
    S_SxS = 0.
    S_WxW = 0.
    S_SxW = 0. 

    DO NL=1,$np

    READ(80,*) TIMEJUL,H_OBS,H_WWW

    N_C   = N_C   + 1
    S_OBS = S_OBS + H_OBS
    S_WWW = S_WWW + H_WWW 
    S_SxS = S_SxS + H_OBS**2 
    S_WxW = S_WxW + H_WWW**2 
    S_SxW = S_SxW + H_OBS*H_WWW 

    END DO

!  ---  
    AV_OBS   =  S_OBS / FLOAT(N_C) 
    AV_WWW   =  S_WWW / FLOAT(N_C)
    VAR_OBS  =  S_SxS / FLOAT(N_C) - ( S_OBS/FLOAT(N_C) )**2
    VAR_WWW  =  S_WxW / FLOAT(N_C) - ( S_WWW/FLOAT(N_C) )**2
    BIAS     =  ( S_WWW - S_OBS ) / FLOAT(N_C)
    RMSE     =  SQRT(( S_SxS + S_WxW - 2.*S_SxW ) / FLOAT(N_C))
    COVAR    =  S_SxW / FLOAT(N_C)  - AV_OBS*AV_WWW 
    CCOR     =  COVAR / ( VAR_OBS*VAR_WWW )**0.5
    SC_IND   =  ( RMSE - ( AV_OBS - AV_WWW )**2. )**0.5 / AV_OBS
    DESV_OBS =  SQRT(VAR_OBS)
    DESV_WWW =  SQRT(VAR_WWW)
    CENT_RMS =  VAR_OBS + VAR_WWW - 2*(S_SxW/FLOAT(N_C)-AV_OBS*AV_WWW) 

    WRITE(90,*) "NP ","MEAN_O ", "MEAN_M ", "DESV_O ", "DESV_M ", &
                 "BIAS ","RMSE ", "SI ", "CC ", "C_RMS"
    WRITE(90,6000) N_C , AV_OBS, AV_WWW, DESV_OBS, DESV_WWW, &
                                  BIAS,   RMSE,  SC_IND, CCOR, CENT_RMS

6000  FORMAT ( I10 , 2F6.2 , 2F6.2 , 5F6.2 ) 

    CLOSE(80)
    CLOSE(90)
    END

EOF

    ftn -o  params_erro  params_erro.f90

    ./params_erro

    \rm params_erro  params_erro.f90

exit
exit

