
#include "geninc.h"
#include "ioserv.h"

#if PROTOTYPE_ALLOWED
int code2text(FILE *fpship, FILE *fpinst, PRODUCER_ID_TYPE producer_id, char *country, char *inst, char *ship)
#else
int code2text(fpship, fpinst, producer_id, country, inst, ship)
FILE *fpship, *fpinst;
PRODUCER_ID_TYPE producer_id;
char *country, *inst, *ship;
#endif
{
  int found = 0, i;
  char line[255];

  rewind(fpship);
  rewind(fpinst);
  country[0] = inst[0] = ship[0] = '?'; 
  country[1] = inst[1] = ship[1] = '?';
  country[2] = inst[2] = ship[2] = '\0';

  while (fgets(line, 255, fpship) != NULL 
    && (strlen(line) < 41 || !(found = !strncmp(line+39, producer_id.country, 2))));
  if (producer_id.country[0] == '3' 
    && (producer_id.country[1] == '2' 
    ||  producer_id.country[1] == '3'))
  {
    producer_id.country[1] = '1';  /* reset to primary number  = 31 */
  }
  else if (producer_id.country[0] == '5'
    && (producer_id.country[1] == '0' 
    ||  producer_id.country[1] == '1'))
  {
    strncpy(producer_id.country, '49', 2);  /* reset to primary number  = 49 */
  }
   
  if (found)
  {
    strncpy(country, line, 39);
    country[39] = '\0';
    while ((strlen(line) < 45 
	    || !(found = !strncmp(line+43, producer_id.platform, 2)))
           && strncmp(line, country, 39) == 0
	   && fgets(line, 255, fpship) != NULL)
    i = 0;
    if (found)
    {
      while (line[46+i] != '\n')
      {
        ship[i] = line[46+i];
        i++;
      }
    }
    ship[i] = '\0';
    found = 0;
    while (fgets(line, 255, fpinst) != NULL 
	   && (strlen(line) < 10 
              || !(found = !strncmp(line+3, producer_id.country, 2))));
    if (found)
    {
      do
      {
	found = !strncmp(line+8, producer_id.institution, 2);
      } while (!found 
	       && fgets(line, 255, fpinst) != NULL 
	       && strncmp(line+3, producer_id.country, 2) == 0);
      i = 0;
      if (found)
      {
	while (line[21+i] != '\n')
	{
	  inst[i] = line[21+i];
	  i++;
        }
      }
      inst[i] = '\0';
    }
  }
  else
    country[0] = '\0';
}

#ifdef EXE

#if PROTOTYPE_ALLOWED
void main(int argc, char *argv[])
#else
void main(argc,argv)
int argc;
char *argv[];
#endif
{
  char country[40], inst[80], platform[80];
  PRODUCER_ID_TYPE producer_id;
  FILE *fpinst, *fpship;

  if (argc < 2)
  {
    printf("\n Enter producer id (cciippnnnn) => ");
    scanf("%s", &producer_id);
  }
  else
    strcpy(&producer_id, argv[1]);

  fpinst = check_fopen("inst.cde", "r");
  fpship = check_fopen("ship.cde", "r");
  code2text(fpship, fpinst, producer_id, country, inst, platform);
  printf("\n For producer id %s\n  country = %s\n  institution = %s\n  platform = %s\n",
    &producer_id, country, inst, platform);
  fclose(fpinst);
  fclose(fpship);
}
#endif
