static char szModuleName__[] = "c:/nordrad/unix/export.c";
static char szLastVersion[] = "Version 0.18";
static char szLastSave[] = "1997-02-10*20:51";
static char NradIdStr[]="####  N O R D R A D   M S G . P A R   -   F I L E";

/************************************************************
Abstract
Export.c - Nordrad API primitive to convert Nordrad file
           to BUFR file

(C) Copyright AU-System Communication AB 1994.

Change activity
990125		ARG, Modified entry names to avoid collision w. filep
1998-04-29      ARG  Switch northwest and southeast corners
1997-12-10      ARG  Dont write lat/long into BUFR file
1997-02-05      ARG  Modified for new BUFR conversion
1994-04-07 1.00 BBN  Initial version by Bj”rn Brodin.

Part of  Nordrad.

Description
************************************************************                */
#define DECBUF
#ifdef   VMS
#include <types.h>
#include <stdio.h>
#include <string.h>
#include <stat.h>
#include <netdb.h>
#include <time.h>
#include <math.h>
#else
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <netdb.h>
#include <time.h>
#include <math.h>
#include <malloc.h>
#endif
#include "netdef.h"
#include "api.h"
#include "net.h"
#include "fil.h"
#include "shft.h"
#include "rr_fil.h"
extern BUF b;
extern DAT d;
#define  TEN_TO_SEVEN  10000000
#define MAX_PARA_FILE_SIZE 4200    /* Max NoOfBytes of parameter file...*/

INT32 ConvSriToBufrFrmt (Fil_t *pSourceFile,
                         char *pImageFileStr,
                         Pixel_t *pPixelAttrIn);

INT32 ConvReflToBufrFrmt (Fil_t *pSourceFile,
                          char *pImageFileStr,
                          Pixel_t *pPixelAttrIn);

INT32 CnvToSriProd(Fil_t *pSourceFile,Fil_t *pDestFile,char *pParamFileStr,
                   Pixel_t *pPixelAttrIn,struct ApiProdDescrStruc 
                   *pApiProdDescr);

INT32 pckExpandNradProd(char *pSourceFileStr,char *pDestFileStr);
int   Encode(char *nbuf,char *npar,char *npix);
INT32 NradExecute(char *argv[] );

INT32 ExportToBufr(char *pSourceFileStr,
                   char *pParamFileStr,
                   char *pDestFileStr,
                   unsigned char BufrMode)
{
  Fil_t InFile;
  Fil_t SriFile;
  Fil_t *pSriFile;
  INT32 iRc = OK;
  char ImageFileStr[MAX_FILE_NAME_SIZE];
  char UnpSriFileStr[MAX_FILE_NAME_SIZE];
  char UnpSourceFileStr[MAX_FILE_NAME_SIZE];
  Attr_t AreaDefInfoIn;
  AreaDef_t *pAreaProperties;
  Attr_t PixelInfoIn;
  Pixel_t *pPixelAttrIn;
  INT32 iAttrLen = 0;
  Attr_t ProdNameInfo;
  unsigned char *pProdNameAttr;
  FILE *ParFilep;
  FILE *TmpParFilep;
  char TmpParamFileStr[MAX_FILE_NAME_SIZE];
  unsigned char s[7];
  Attr_t TimeInfoOut;
  Time_t *pTimeAttrOut;
  long lTimeInSec;
  struct tm *pTimeParts;
  Attr_t ResolutionInfo;
  Resolution_t *pResolutionAttr;
  Attr_t Z2Rconst;
  Z_To_R_Constants_t * pZ2Rconst;

  Attr_t IntStoreInfo;
  IntStore_t *pIntStoreAttr;

  INT32 iDummyRc = 0;
  struct ApiProdDescrStruc ApiProdDescr;
  INT32 iTmpUnpSourceCreated = FALSE;
  char *ExecPar[10];                        /* Watch the size*/
  
  memset(&InFile, 0, sizeof(InFile));
  strcpy(InFile.Name, 
         pSourceFileStr);
  strcpy(UnpSourceFileStr, 
         "");
  strcpy(UnpSriFileStr, 
         "");
  memset(&SriFile, 
         0, 
         sizeof(InFile));
  pTimeAttrOut = (Time_t *)TimeInfoOut.buff;
  pProdNameAttr = (unsigned char *)ProdNameInfo.buff;
  pPixelAttrIn = (Pixel_t *)PixelInfoIn.buff;
  pAreaProperties = (AreaDef_t *)AreaDefInfoIn.buff;
  pResolutionAttr = (Resolution_t *)ResolutionInfo.buff;
  pZ2Rconst = (Z_To_R_Constants_t *)Z2Rconst.buff;

  /* Open the file and read some attributes from the header */
  
  fiOpen(&InFile, 
         InputMode, 
         &iRc);
  if ((InFile.fp == NULL) || (iRc != OK))
    {
      if (iRc == -1)
        return  PGFFILNOTFND;
      else
        if (iRc == -3)
          return  PGFILLFILE;
        else
          return  APIILLPAR;
    } 

  fiReadAttr(&InFile, 
             (Attr_t *)pProdNameAttr, 
             Name_Attr, 
             &iAttrLen, 
             &iRc);
  if (iRc != OK)
    {
      fiClose(&InFile, 
              &iTmpRc);
      return  BUFNRDERROR;
    } 

  fiReadAttr(&InFile, 
             (Attr_t *)pTimeAttrOut, 
             Time_Attr, 
             &iAttrLen, 
             &iRc);
  if (iRc < 0)
    {
      fiClose(&InFile, 
              &iTmpRc);
      return  BUFNRDERROR;
    } 

  fiReadAttr(&InFile, 
             (Attr_t *)pResolutionAttr, 
             Resolution_Attr, 
             &iAttrLen, 
             &iRc);
  if (iRc != OK)
    {
      fiClose(&InFile, 
              &iTmpRc);
      return  BUFNRDERROR;
    } 

  fiReadAttr(&InFile, 
             (Attr_t *)pAreaProperties, 
             AreaProperties_Attr, 
             &iAttrLen, 
             &iRc);
  if (iRc != OK)
    {
      fiClose(&InFile, 
              &iTmpRc);
      return  BUFNRDERROR;
    } 

  fiReadAttr(&InFile, 
             (Attr_t *)pPixelAttrIn, 
             Pixel_Attr, 
             &iAttrLen, 
             &iRc);
  if (iRc != OK)
    {
      fiClose(&InFile, 
              &iTmpRc);
      return  BUFNRDERROR;
    } 

  if (pPixelAttrIn->Compressed == TRUE)
    {
    /***********************************************************/
    /* If the file is compressed we'll have to unpack it first */
    /***********************************************************/
      fiClose(&InFile, 
              &iTmpRc);
      tmpnam(UnpSourceFileStr);        /* names for temporary files         */
      if ((iRc = pckExpandNradProd(pSourceFileStr, 
                                   UnpSourceFileStr)) != OK)
        {
          iDummyRc = remove(UnpSourceFileStr);
          return  iRc;
        } 

      iTmpUnpSourceCreated = TRUE;

      /**********************************************************************/
      /* re open infile as unpacked                                         */
      /**********************************************************************/

      strcpy(InFile.Name, 
             UnpSourceFileStr);
      fiOpen(&InFile, 
             InputMode, 
             &iRc);
      if ((InFile.fp == NULL) || (iRc != OK))
        {
          iDummyRc = remove(UnpSourceFileStr);
          if (iRc == -1)
            return  PGFFILNOTFND;
          else
            if (iRc == -3)
              return  PGFILLFILE;
            else
              return  APIILLPAR;
        } 

      fiReadAttr(&InFile, 
                 (Attr_t *)pPixelAttrIn, 
                 Pixel_Attr, 
                 &iAttrLen, 
                 &iRc);
      if (iRc != OK)
        {
          fiClose(&InFile, 
                  &iTmpRc);
          if (iTmpUnpSourceCreated == TRUE)/* BBN 940527                    */
            iDummyRc = remove(UnpSourceFileStr);
          return  BUFNRDERROR;
        } 
    } 
  else

    strcpy(UnpSourceFileStr, 
           pSourceFileStr);

  /* If BufrMode = BUFR_4 we'll convert the file to SRI format  */
  /* (If it is not already a SRI product) and then convert it   */
  /* into a BUFR code that has only 4 bits per pixel            */
           
  if (BUFR_4 == BufrMode)
    {
    /***********************************************************************/
    /* unpack and conv to SRI format if neccessary                         */
    /***********************************************************************/

    if (*pProdNameAttr != PROD_RRSRI_Z)
      {
      tmpnam(UnpSriFileStr);         /* names for temporary files         */
      strcpy(SriFile.Name, 
             UnpSriFileStr);
      fiCreate(&SriFile, 
               SriFile.Name, 
               512, 
               0, 
               &iRc);
      pSriFile = &SriFile;
      if ((pSriFile->fp == NULL) || (iRc != OK))
        {
        fiClose(&InFile, 
                &iTmpRc);
        if (iRc == -1)
          return  PGFFILNOTFND;
        else
          if (iRc == -3)
            return  PGFILLFILE;
          else
            return  APIILLPAR;
        }       /* if ((pSriFile->fp == NULL) || (iRc != OK)) */

      iRc = CnvToSriProd(&InFile, 
                         pSriFile, 
                         pParamFileStr, 
                         pPixelAttrIn, 
                         &ApiProdDescr);
      } /* if (*pProdNameAttr != PROD_RRSRI_Z) */
    else
      {
      pSriFile = &InFile;   /* The infile is the SRI-file!*/
      } /* else*/

    /*=== Fetch the conversion-parameters from the sri-file ===*/
    fiReadAttr( pSriFile, 
                (Attr_t *)pZ2Rconst,
                Z_To_R_Constants_Attr, 
                &iAttrLen, 
                &iRc);
    if (iRc != OK)
      {
      fiClose( &InFile, &iTmpRc);
      return  BUFNRDERROR;
      } /* if (iRc != OK) */


    if (iRc != APIOK)
      {
      fiClose(&InFile, 
              &iTmpRc);
      fiClose(pSriFile, 
              &iTmpRc);

      if (strlen(UnpSriFileStr) > 0)
        iDummyRc = remove(UnpSriFileStr);
      if (iTmpUnpSourceCreated == TRUE)   /* BBN 940527             */
        iDummyRc = remove(UnpSourceFileStr);
      return  iRc;
      } /* if (iRc != APIOK) */

      /********************************************************************/
      /* ---- Create Temp parameter file for encode function ---          */
      /********************************************************************/

      strcpy( TmpParamFileStr, "");
      tmpnam( TmpParamFileStr);
      strcpy(ImageFileStr, "");        /*Will be inserted in TmpParamFile*/
      tmpnam(ImageFileStr);            /* names for temporary files      */
      iRc = MakeTmpSRIParamFile( pParamFileStr, 
                                 TmpParamFileStr, 
                                 ImageFileStr, 
                                 pProdNameAttr,
                                 pTimeAttrOut, 
                                 pResolutionAttr, 
                                 pAreaProperties, 
                                 pPixelAttrIn,
                                 pZ2Rconst );
      if (iRc != OK) 
        {
        iDummyRc = remove(UnpSriFileStr);
        if (iTmpUnpSourceCreated == TRUE)
          iDummyRc = remove(UnpSourceFileStr);
        remove(TmpParamFileStr);
        return NOK;
        }       /* if (iRc != OK) */
      /******************************************************************/
      /* ----- tmp par file created ----                                */
      /******************************************************************/

      if ((iRc == OK) || (iRc == APIOK))
        {
        iRc = ConvSriToBufrFrmt(pSriFile, 
                                ImageFileStr,
                                pPixelAttrIn);
        fiClose(pSriFile, &iTmpRc);
        
        if (iRc == OK)  
          {
          /*=== Build the execution  command ===*/
          ExecPar[0] = "encbufr";
          ExecPar[1] = TmpParamFileStr;
          ExecPar[2] = pDestFileStr;
          ExecPar[3] = NULL;
          
          iRc = (INT32)NradExecute( ExecPar);    /* Execute it*/
          if (iRc == NOK)    
            iRc = BUFERROR;
          }     /* if (iRc == OK)   */
        iDummyRc = remove(ImageFileStr);
        }       /* if ((iRc == OK) || (iRc == APIOK)) */
      else
        {
        fiClose(pSriFile, &iTmpRc);
        }       /* else */
     if (iRc == 0)
       iRc = APIOK;
     fiClose(&InFile, 
             &iTmpRc);

     iDummyRc = remove(TmpParamFileStr);
     if (strlen(UnpSriFileStr) > 0)
       iDummyRc = remove(UnpSriFileStr);
     if (iTmpUnpSourceCreated == TRUE)    /* BBN 940527               */
       iDummyRc = remove(UnpSourceFileStr);
     return  iRc;
    }   /* if (BUFR_4 == BufrMode)*/
  else
    {
    /* If BufrMode = BUFR_8 we'll only accept reflectivity      */
    /* products. We don't have to convert it into a SRI product */
    /* Rather we have to prepare a parameterfile that is        */
    /* a bit different than for SRI products.                   */
    /* There should be no classification table, but some codes  */
    /* that expresses the values of the constants used to       */
    /* calculate pixel values from physical values              */

    /*=== Fetch the conversion-parameters from the product file ===*/

    pIntStoreAttr = (IntStore_t *)IntStoreInfo.buff;
    fiReadAttr(&InFile, 
               (Attr_t *)pIntStoreAttr, 
               IntStore_Attr, 
               &iAttrLen, 
               &iRc);
    if (iRc != OK)
      {
      fiClose( &InFile, &iTmpRc);
      return  BUFNRDERROR;
      } /* if (iRc != OK) */


      /********************************************************************/
      /* ---- Create Temp parameter file for encode function ---          */
      /********************************************************************/

      strcpy( TmpParamFileStr, "");
      tmpnam( TmpParamFileStr);
      strcpy(ImageFileStr, "");        /*Will be inserted in TmpParamFile*/
      tmpnam(ImageFileStr);            /* names for temporary files      */
      iRc = MakeTmpReflParamFile( pParamFileStr, 
                                  TmpParamFileStr, 
                                  ImageFileStr, 
                                  pProdNameAttr,
                                  pTimeAttrOut, 
                                  pResolutionAttr, 
                                  pAreaProperties, 
                                  pPixelAttrIn,
                                  pIntStoreAttr);
      if (iRc != OK) 
        {
        if (iTmpUnpSourceCreated == TRUE)
          iDummyRc = remove(UnpSourceFileStr);
        remove(TmpParamFileStr);
        return NOK;
        }       /* if (iRc != OK) */
      /******************************************************************/
      /* ----- tmp par file created ----                                */
      /******************************************************************/

      iRc = ConvReflToBufrFrmt(&InFile, 
                               ImageFileStr,
                               pPixelAttrIn);

      fiClose(&InFile, &iTmpRc);
        
      if (iRc == OK)  
        {
        /*=== Build the execution  command ===*/
        ExecPar[0] = "encbufr";
        ExecPar[1] = TmpParamFileStr;
        ExecPar[2] = pDestFileStr;
        ExecPar[3] = NULL;
          
        iRc = (INT32)NradExecute( ExecPar);    /* Execute it*/
        if (iRc == NOK)    
          iRc = BUFERROR;
        }       /* if (iRc == OK)   */
      iDummyRc = remove(ImageFileStr);

      if (iRc == 0)
        iRc = APIOK;

      iDummyRc = remove(TmpParamFileStr);
      if (iTmpUnpSourceCreated == TRUE)    /* BBN 940527               */
        iDummyRc = remove(UnpSourceFileStr);
      return  iRc;
    }   /* else*/
} 

INT32 ConvSriToBufrFrmt (Fil_t *pSourceFile,
                        char *pImageFileStr,
                        Pixel_t *pPixelAttrIn)
{
  INT32 iRc = OK;
  FILE *pImageFile;                    /* Destination-file name             */
  unsigned char *pInData;              /* BBN 940526 to unsigned            */
  INT32 iNextRow;
  INT32 iPixDataSize = 0;
  unsigned char *pTmpRow;
  unsigned char *pRowPos;
  INT32 iInd = 0;
  INT32 iClassLim = 0;
  unsigned char ClassTab[MAX_PIX_VALUES+1];
  unsigned char PixMmHTab[16+1];       /* see decl of itopval in shft.h     */
  INT32 iNoBytes = 0;
  INT32 iAttrLen = 0;
  Attr_t IntStoreInfo;
  IntStore_t *pIntStoreAttr;
  double dTmpFloat;

  pIntStoreAttr = (IntStore_t *)IntStoreInfo.buff;
  fiReadAttr(pSourceFile, 
             (Attr_t *)pIntStoreAttr, 
             IntStore_Attr, 
             &iAttrLen, 
             &iRc);
  if (iRc != OK)
    return  BUFNRDERROR;

  /**************************************************************************/
  /* ---< Re arrange pixel data for conversion to BUFR format >----         */
  /**************************************************************************/

  iPixDataSize = pPixelAttrIn->ColCnt *pPixelAttrIn->RowCnt;
  pTmpRow = (unsigned char *)malloc(pPixelAttrIn->ColCnt);
  pInData = (unsigned char *)malloc(iPixDataSize);
  if ((pInData == NULL) || (pTmpRow == NULL))
    return  APINOMEM;

  PixMmHTab[0] = 0;
  for (iInd = 1; iInd < b.ntpixv+1; iInd++)
    {
      dTmpFloat = b.itopvl[iInd];
      dTmpFloat = dTmpFloat *0.36;
      dTmpFloat = log10(dTmpFloat);
      PixMmHTab[iInd] = (unsigned char)((dTmpFloat-pIntStoreAttr->Ord)/
         pIntStoreAttr->Slope+pIntStoreAttr->Offset);
    } 
  for (iInd = 0; iInd < MAX_PIX_VALUES; iInd++)
    {
      iClassLim = b.ntpixv;
      while ((iInd <= PixMmHTab[iClassLim]) && (iClassLim >= 0))
        iClassLim--;
      if (iClassLim == b.ntpixv)
        ClassTab[iInd] = 15;  /* 950926, chagned from 255*/
      else
        if (iClassLim > 0)
          ClassTab[iInd] = iClassLim;
        else
          ClassTab[iInd] = 0;
    } 
  ClassTab[0] = 0;
  ClassTab[255] = 15;  /* 950926, chagned from 255*/

  /**************************************************************************/
  /* read Pixel information from file in NORDRAD format                     */
  /**************************************************************************/

  fseek(pSourceFile->fp, 
        pPixelAttrIn->FileOffset-1, 
        SEEK_SET);
  iNoBytes = fread(pInData, 
                   sizeof(char), 
                   pPixelAttrIn->StorePixels, 
                   pSourceFile->fp);
  if (iNoBytes != pPixelAttrIn->StorePixels)
    return  BUFNRDERROR;

  pImageFile = fopen(pImageFileStr, 
                     "wb");

  /**************************************************************************/
  /* set pointer to last row in image data and read one row at a time       */
  /* backwords toward beginning. * /* add in next position from start in    */
  /* target file                                                            */
  /**************************************************************************/

  iNextRow = iPixDataSize-pPixelAttrIn->ColCnt;
  pRowPos = &pInData[iNextRow];
  fseek(pImageFile, 
        0L, 
        SEEK_SET);
  while (iNextRow >= 0)
    {
      iInd = 0;
      while (iInd < pPixelAttrIn->ColCnt)
        {
          pTmpRow[iInd] = ClassTab[pRowPos[iInd]];
          iInd++;
        } 
      iNoBytes = fwrite(pTmpRow, 
                        sizeof(char), 
                        pPixelAttrIn->ColCnt, 
                        pImageFile);
      if (iNoBytes != pPixelAttrIn->ColCnt)
        return  BUFERROR;

      iNextRow -= pPixelAttrIn->ColCnt;
      pRowPos = &pInData[iNextRow];
    } 
  fclose(pImageFile);
  free(pTmpRow);
  free(pInData);
  return  iRc;
} 



INT32 ConvReflToBufrFrmt (Fil_t *pSourceFile,
                          char *pImageFileStr,
                          Pixel_t *pPixelAttrIn)
{
  INT32 iRc = OK;
  FILE *pImageFile;                    /* Destination-file name             */
  unsigned char *pInData;              /* BBN 940526 to unsigned            */
  INT32 iNextRow;
  INT32 iPixDataSize = 0;
  unsigned char *pRowPos;
  INT32 iNoBytes = 0;

  /**************************************************************************/
  /* ---< Re arrange pixel data for conversion to BUFR format >----         */
  /**************************************************************************/

  iPixDataSize = pPixelAttrIn->ColCnt *pPixelAttrIn->RowCnt;
  pInData = (unsigned char *)malloc(iPixDataSize);
  if (pInData == NULL) 
    return  APINOMEM;

  /**************************************************************************/
  /* read Pixel information from file in NORDRAD format                     */
  /**************************************************************************/

  fseek(pSourceFile->fp, 
        pPixelAttrIn->FileOffset-1, 
        SEEK_SET);
  iNoBytes = fread(pInData, 
                   sizeof(char), 
                   pPixelAttrIn->StorePixels, 
                   pSourceFile->fp);
  if (iNoBytes != pPixelAttrIn->StorePixels)
    return  BUFNRDERROR;

  pImageFile = fopen(pImageFileStr, 
                     "wb");

  /**************************************************************************/
  /* set pointer to last row in image data and read one row at a time       */
  /* backwords toward beginning. * /* add in next position from start in    */
  /* target file                                                            */
  /**************************************************************************/

  iNextRow = iPixDataSize-pPixelAttrIn->ColCnt;
  pRowPos = &pInData[iNextRow];
  fseek(pImageFile, 
        0L, 
        SEEK_SET);
  while (iNextRow >= 0)
    {
      iNoBytes = fwrite(pRowPos, 
                        sizeof(char), 
                        pPixelAttrIn->ColCnt, 
                        pImageFile);
      if (iNoBytes != pPixelAttrIn->ColCnt)
        return  BUFERROR;

      iNextRow -= pPixelAttrIn->ColCnt;
      pRowPos = &pInData[iNextRow];
    } 
  fclose(pImageFile);
  free(pInData);
  return  iRc;
} 


char *FetchFloatPara(char *pBuf,char *pParaStr, float *pResult,int *pErr)/*
=========================================================================*/
{ char * p;
  if ( !(p = strstr( pBuf, pParaStr))) {    /* Can't find it!*/
    *pErr |= 1;
    return pBuf;
  }

  pBuf = p+1;                          /* set Return-pointer*/
  while (*(--p) ==' ') ;               /* get last none space*/
  while (*(p) != ' ')  p--;
  p++;                                 /* Point on item*/
  sscanf(p,"%f",pResult);               /* Scan and place result*/
  return pBuf;
  }


char *FetchIntPara(char *pBuf,char *pParaStr, int *pValue, int *pErr) /*
======================================================================*/
{ float HelpFloat;
  int   HelpInt;

  pBuf = FetchFloatPara( pBuf, pParaStr, &HelpFloat, pErr);
  HelpInt= (int) HelpFloat;
  *pValue = HelpInt;
  return pBuf;                 /* E R R O R: Return old pointer */
}


INT32 ModifyFloatPara(char *pBuf,char *pParaStr, float Value) /* Looks like:
====================================================  0.0   PARA_STR */
{ char * p;
  if ( !(p = strstr( pBuf, pParaStr)))
    return -1;                         /* Can't find it!*/
  while (*(--p) ==' ') ;               /* get last none space*/
  while (*(p) != ' ')  p--;
  p++;                                 /* Point on item*/
  sprintf(p,"%f",Value);               /* Scan and place result*/
  /*the bloody fkn will insert a null, scratch it!*/
  while(*p) p++;
  *p = ' ';
  return 0;
}


INT32 GetCnvConst(char *pParFile, IntStore_t *pStoreAttr, ConvConst_t * pbb)/*

============================================================================*/
{ FILE * ParFilep;
  char * pBuf;
  float HelpFloat;
  int NoOfPixVal = 1;
  int iLen;
  int Err = 0;
  size_t ch_size, buf_size;
  char HelpBuf[MAX_PARA_FILE_SIZE];

  if (  (ParFilep = fopen(pParFile, "r")) == NULL)
    return NOK;

  memset(&HelpBuf, 0, sizeof(HelpBuf));

  /*=== read from parameter file to end-of-file ===*/
  ch_size  = sizeof(char);
  buf_size = sizeof(HelpBuf);
  iLen = fread( HelpBuf, ch_size, buf_size , ParFilep) ;
  if ( iLen <100 )  {      /*Well, there must be at least some bytes...*/
    fclose(ParFilep);
    return NOK;
  }

  pBuf = FetchFloatPara((char *) &HelpBuf, "XYZZY-ORD",    &pStoreAttr->Ord,    &Err);
  pBuf = FetchFloatPara((char *) &HelpBuf, "XYZZY-SLOPE",  &pStoreAttr->Slope,  &Err);
  pBuf = FetchIntPara((char *) &HelpBuf, "XYZZY-OFFSET", &pStoreAttr->Offset, &Err);
  pBuf = FetchFloatPara((char *) &HelpBuf, "0 25   6",     &pbb->izr,    &Err);
  pBuf = FetchFloatPara((char *) &HelpBuf, "0 25   7",     &pbb->ifaczr, &Err);
  pBuf = FetchFloatPara((char *) &HelpBuf, "0 25   8",     &pbb->iexpzr, &Err);

  pBuf = strstr((char *) &HelpBuf, "3 13  10"); /*Sequence for Radar rainf. int mod.*/
  pBuf = FetchFloatPara(pBuf,"0 31   1", &HelpFloat, &Err); /* NoOf values?*/
  b.ntpixv = (int)  HelpFloat;

  if (b.ntpixv >16) b.ntpixv = 16;

  while ( NoOfPixVal <= b.ntpixv) {     /*Fetch the conversion values*/
    pBuf = FetchFloatPara( pBuf, "0 21  36", &HelpFloat, &Err );
    b.itopvl[ NoOfPixVal++] =  HelpFloat * 10 ;
    }
  
  fclose(ParFilep);
  if (Err)
    return NOK;
  else
    return OK;
}


INT32 MakeTmpSRIParamFile( char                * pParamFileStr, 
                           char                * pTmpParamFileStr,
                           char                * RawImgFileName,
                           unsigned char       * pProdNameAttr, 
                           Time_t              * pTimeAttrOut,
                           Resolution_t        * pResolutionAttr,
                           AreaDef_t           * pAreaProp, 
                           Pixel_t             * pPixelAttrIn,
			   Z_To_R_Constants_t  * pZ2Rconst) /*
============================================================================*/
{
#define TO_TMP(A,B)  fprintf( TmpParFilep,A,B)
  FILE *ParFilep;
  FILE *TmpParFilep;
  char HelpBuf[MAX_PARA_FILE_SIZE];
  int Time[6];
  unsigned char PictType;
  int FileLen;
  
  if ( (TmpParFilep = fopen(pTmpParamFileStr, "w")) == NULL)
    return NOK;
  sscanf(pTimeAttrOut->timeString, "%02d%02d%02d%02d%02d",
         &Time[0], &Time[1], &Time[2], &Time[3], &Time[4]);


  /*Read the stuff into top of working area*/
  fprintf( TmpParFilep,NradIdStr);
  
  if (Time[0] > 90)
    {
    TO_TMP("\n3  1 192   19%2d\n", Time[0] );                /* Year   0 4 1*/
    }   /* if (Time[0] > 90) */
  else
    {
    TO_TMP("\n3  1 192   20%2d\n", Time[0] );                /* Year   0 4 1*/
    }   /* if (Time[0] > 90) */
  TO_TMP("             %2d \n", Time[1]);                    /* month  0 4 2*/
  TO_TMP("             %2d \n", Time[2]);                    /* day    0 4 3*/
  TO_TMP("             %2d \n", Time[3]);                    /* hour   0 4 4*/
  TO_TMP("             %2d \n", Time[4]);                    /* minute 0 4 5*/

      
  TO_TMP("           %7.5f\n", pAreaProp->NorthEast.LatLong.Lat);   /* 0 5 2*/
  TO_TMP("           %7.5f\n", pAreaProp->SouthWest.LatLong.Long);  /* 0 6 2*/

  TO_TMP("           %7.5f\n", pAreaProp->NorthEast.LatLong.Lat);   /* 0 5 2*/
  TO_TMP("           %7.5f\n", pAreaProp->NorthEast.LatLong.Long);  /* 0 6 2*/

  TO_TMP("           %7.5f\n", pAreaProp->SouthWest.LatLong.Lat);   /* 0 5 2*/
  TO_TMP("           %7.5f\n", pAreaProp->NorthEast.LatLong.Long);  /* 0 6 2*/

  TO_TMP("           %7.5f\n", pAreaProp->SouthWest.LatLong.Lat);   /* 0 5 2*/
  TO_TMP("           %7.5f\n", pAreaProp->SouthWest.LatLong.Long);  /* 0 6 2*/


  if (pAreaProp->Proj.ProjectionType == 0)  {
    TO_TMP("           %2d\n",1);                                   /*0 29 1*/
    TO_TMP("         %7.1f\n", 0.0 );                              /* 0  5 2*/
    TO_TMP("         %7.1f\n", 0.0 );                              /* 0  5 2*/
/*    TO_TMP("          %7.1f\n",pAreaProp->Proj.ProjData.Pos.Lat ); */ /*0 5 2*/
/*    TO_TMP("          %7.1f\n",pAreaProp->Proj.ProjData.Pos.Long );*/ /*0 5 2*/
  } 
  else   {
    TO_TMP("            %2d\n", 7);                                /* 0 29 1*/
    TO_TMP("         %7.1f\n", 0.0 );                              /* 0  5 2*/
    TO_TMP("         %7.1f\n", 0.0 );                              /* 0  5 2*/
  } 

  TO_TMP("            %d\n", pResolutionAttr->Resolution );     /* 0 5 33*/
  TO_TMP("            %d\n", pResolutionAttr->Resolution );     /* 0 6 33*/

  TO_TMP("            %d\n",pPixelAttrIn->ColCnt); /* 0 30 21*/
  TO_TMP("            %d\n",pPixelAttrIn->RowCnt); /* 0 30 22*/

  TO_TMP("0 30 21     %d\n",pPixelAttrIn->ColCnt); /*One time extra  0 30 21*/
  TO_TMP("0 30 22     %d\n",pPixelAttrIn->RowCnt); /*One time extra  0 30 22*/

  switch (*pProdNameAttr) 
    {
    case PROD_RRPPI_Z:    PictType =  0;          break;
    case PROD_RRCAPPI_Z:  PictType =  2;          break;
    case PROD_RRPSC_Z:    PictType =  9;          break;
    case PROD_RRVMI_Z:    PictType = 14;          break;
    case PROD_RRHMI_Z:
      {
      if (pPixelAttrIn->ColCnt > 
          pPixelAttrIn->RowCnt)
        /* the north wall */
        PictType = 10;
      else
        /* The east wall */
        PictType = 11;
      break;
      } /* case PROD_RRHMI_Z: */
    case PROD_RRSRI_Z:    PictType = 15;          break;
    default:              fclose(TmpParFilep);    return  NOK;
  }    

  TO_TMP("3 21 11     %d\n", PictType);                           /* 0 30 31*/
  TO_TMP("            %d\n", 0xFFFF);                             /* 0 30 32*/
  TO_TMP("            %d\n", 0);                                  /* 0 29  2*/

  /*=== Add the rest from the Parameterfile ===*/
  if ( (ParFilep = fopen(pParamFileStr, "r")) ==NULL) {
    fclose(TmpParFilep);
    return NOK;
    }

  memset(&HelpBuf, 0, sizeof(HelpBuf));

  /*  read from parameter file to end-of-file */
  FileLen = fread( HelpBuf, sizeof(char), sizeof(HelpBuf) , ParFilep);
  if (FileLen <0) {
    fclose(ParFilep);
    fclose(TmpParFilep);
    return NOK;
    }
  

  if ( strncmp( NradIdStr,HelpBuf,sizeof(NradIdStr)-3 ) != 0) {
    fclose(ParFilep);
    fclose(TmpParFilep);
    return NOK;                 /*NOT a nordrad parameter file*/
  }

  if (ModifyFloatPara( HelpBuf, "0 25   6", (float) pZ2Rconst->Type))
    goto XXX;
  if (ModifyFloatPara( HelpBuf, "0 25   7",      pZ2Rconst->Factor ))
    goto XXX;

  if (ModifyFloatPara( HelpBuf, "0 25   8",    pZ2Rconst->Exponent ))
    goto XXX;

  fprintf( TmpParFilep, HelpBuf);          /*  Write to destination */
  fprintf( TmpParFilep,"3 21 192   ");
  fprintf( TmpParFilep, RawImgFileName);

  /*Close the files*/
  fclose(ParFilep);
  fclose(TmpParFilep);
  return OK;

XXX:
  fclose(ParFilep);
  fclose(TmpParFilep);
  return NOK;
 }

INT32 MakeTmpReflParamFile( char                * pParamFileStr,
                            char                * pTmpParamFileStr,
                            char                * RawImgFileName,
                            unsigned char       * pProdNameAttr, 
                            Time_t              * pTimeAttrOut,
                            Resolution_t        * pResolutionAttr,
                            AreaDef_t           * pAreaProp, 
                            Pixel_t             * pPixelAttrIn,
                            IntStore_t          * pIntStoreAttr) /*
============================================================================*/
{
#define TO_TMP(A,B)  fprintf( TmpParFilep,A,B)
  FILE *ParFilep;
  FILE *TmpParFilep;
  char HelpBuf[MAX_PARA_FILE_SIZE];
  char *pHelpBuf;
  int Time[6];
  unsigned char PictType;
  int FileLen;

  /* Create a temporary parameterfile that will be input */
  /* to the encbufr program. The parameter values will be*/
  /* constructed from values from the file and from a    */
  /* parameterfile that is input to this primitive       */
  /* When creating 8 bit BUFR code, we will not use the  */
  /* table describing the classification of the pixels   */
  /* that is found in the parameterfile                  */
  
  if ( (TmpParFilep = fopen(pTmpParamFileStr, "w")) == NULL)
    return NOK;
  sscanf(pTimeAttrOut->timeString, "%02d%02d%02d%02d%02d",
         &Time[0], &Time[1], &Time[2], &Time[3], &Time[4]);

  fprintf( TmpParFilep,NradIdStr);
  
  if (Time[0] > 90)
    {
    TO_TMP("\n3  1 192   19%2d\n", Time[0] );                /* Year   0 4 1*/
    }   /* if (Time[0] > 90) */
  else
    {
    TO_TMP("\n3  1 192   20%2d\n", Time[0] );                /* Year   0 4 1*/
    }   /* if (Time[0] > 90) */
  TO_TMP("             %2d \n", Time[1]);                    /* month  0 4 2*/
  TO_TMP("             %2d \n", Time[2]);                    /* day    0 4 3*/
  TO_TMP("             %2d \n", Time[3]);                    /* hour   0 4 4*/
  TO_TMP("             %2d \n", Time[4]);                    /* minute 0 4 5*/

      
  TO_TMP("           %7.5f\n", pAreaProp->SouthWest.LatLong.Lat);   /* 0 5 2*/
  TO_TMP("           %7.5f\n", pAreaProp->NorthEast.LatLong.Long);  /* 0 6 2*/
  TO_TMP("           %7.5f\n", pAreaProp->NorthEast.LatLong.Lat);   /* 0 5 2*/
  TO_TMP("           %7.5f\n", pAreaProp->NorthEast.LatLong.Long);  /* 0 6 2*/
  TO_TMP("           %7.5f\n", pAreaProp->NorthEast.LatLong.Lat);   /* 0 5 2*/
  TO_TMP("           %7.5f\n", pAreaProp->SouthWest.LatLong.Long);  /* 0 6 2*/
  TO_TMP("           %7.5f\n", pAreaProp->SouthWest.LatLong.Lat);   /* 0 5 2*/
  TO_TMP("           %7.5f\n", pAreaProp->SouthWest.LatLong.Long);  /* 0 6 2*/


  if (pAreaProp->Proj.ProjectionType == 0)  {
    TO_TMP("           %2d\n",1);                                   /*0 29 1*/
    TO_TMP("          %7.1f\n",pAreaProp->Proj.ProjData.Pos.Lat );  /*0 5 2*/
    TO_TMP("          %7.1f\n",pAreaProp->Proj.ProjData.Pos.Long ); /*0 5 2*/
  } 
  else   {
    TO_TMP("            %2d\n", 7);                                /* 0 29 1*/
    TO_TMP("         %7.1f\n", 0.0 );                              /* 0  5 2*/
    TO_TMP("         %7.1f\n", 0.0 );                              /* 0  5 2*/
  } 

  TO_TMP("            %d\n", pResolutionAttr->Resolution );     /* 0 5 33*/
  TO_TMP("            %d\n", pResolutionAttr->Resolution );     /* 0 6 33*/

  TO_TMP("            %d\n",pPixelAttrIn->ColCnt); /* 0 30 21*/
  TO_TMP("            %d\n",pPixelAttrIn->RowCnt); /* 0 30 22*/

  TO_TMP("0 30 21     %d\n",pPixelAttrIn->ColCnt); /*One time extra  0 30 21*/
  TO_TMP("0 30 22     %d\n",pPixelAttrIn->RowCnt); /*One time extra  0 30 22*/


  switch (*pProdNameAttr) 
    {
    case PROD_RRPPI_Z:    PictType =  0;          break;
    case PROD_RRCAPPI_Z:  PictType =  2;          break;
    case PROD_RRPSC_Z:    PictType =  9;          break;
    case PROD_RRVMI_Z:    PictType = 14;          break;
    case PROD_RRHMI_Z:
      {
      if (pPixelAttrIn->ColCnt > 
          pPixelAttrIn->RowCnt)
        /* the north wall */
        PictType = 10;
      else
        /* The east wall */
        PictType = 11;
      break;
      } /* case PROD_RRHMI_Z: */
    case PROD_RRSRI_Z:    PictType = 15;          break;
    default:              fclose(TmpParFilep);    return  NOK;
  }    
  TO_TMP("3 21 11     %d\n", PictType);                           /* 0 30 31*/
  TO_TMP("            %d\n", 0xFFFF);                             /* 0 30 32*/
  TO_TMP("            %d\n", 0);                                  /* 0 29  2*/

  TO_TMP("0 25 202    %7.5f\n",pIntStoreAttr->Ord - 
                            pIntStoreAttr->Offset *
                            pIntStoreAttr->Slope);               /* 0 25 202*/

  TO_TMP("0 25 203    %7.5f\n",pIntStoreAttr->Slope);            /* 0 25 203*/


  /*=== Read the parameterfile and take the last part from it ===*/
  if ( (ParFilep = fopen(pParamFileStr, "r")) ==NULL)
    {
    fclose(TmpParFilep);
    return NOK;
    }

  memset(&HelpBuf, 0, sizeof(HelpBuf));

  /*  read from parameter file to end-of-file */
  FileLen = fread( HelpBuf, sizeof(char), sizeof(HelpBuf) , ParFilep);
  if (FileLen <0) 
    {
    fclose(ParFilep);
    fclose(TmpParFilep);
    return NOK;
    }

  /* Verify the beginning of the file that it is really a valid */
  /* parameterfile                                              */
  
  if ( strncmp( NradIdStr,HelpBuf,sizeof(NradIdStr)-3 ) != 0) {
    fclose(ParFilep);
    fclose(TmpParFilep);
    return NOK;                 /*NOT a nordrad parameter file*/
  }

  /* Find the part of the parameterfile that is relevant for    */
  /* the reflectivity bufr format                               */

  pHelpBuf = strstr((char *) &HelpBuf, "3 21   7"); /*Calibration method */
  if (NULL == pHelpBuf)
    {
    fclose(ParFilep);
    fclose(TmpParFilep);
    return NOK;
    }   /* if (NULL == pHelpBuf) */
  

  fprintf( TmpParFilep, pHelpBuf);          /*  Write to destination */
  fprintf( TmpParFilep,"3 21 193   ");
  fprintf( TmpParFilep, RawImgFileName);

  /*Close the files*/
  fclose(ParFilep);
  fclose(TmpParFilep);
  return OK;
 }
