#include <stdio.h>
#include <fcntl.h>
#include "options.h"
#include "misc.h"
#include "var.h"
#include "ship.h"

main()
{
    FILE    *fp, *fopen();
    int     shpf, x, n, numships;
    struct shpstr *sp;
    struct shpstr all[2000];
    char    *sprintf(), buf[80];

    if ((fp=fopen("ship.ascii", "r")) == (FILE *)0){
        fprintf(stderr,"Cannot open ship.ascii!\n");
        exit(-1);
    }

    fscanf(fp,"%d",&numships);

    sp = all;
    for(x=0;x<numships;x++,sp++)
        read_ship(sp, fp);
    fclose(fp);

    unlink(sprintf(buf,"%s/ship",DATADIR));
    shpf = open(sprintf(buf,"%s/ship",DATADIR), O_WRONLY|O_CREAT, 0);
    n=write(shpf, all, numships*sizeof(struct shpstr));
    close(shpf);

    printf("Writing %s/ship\n",DATADIR);
    printf("wrote %d bytes out of %d!\n",n,numships*sizeof(struct shpstr));
}

read_ship(sp, fp, cnum)
struct shpstr *sp;
FILE *fp;
int  cnum;
{
    int x, y, ind, relate, reject;
    float f;
    long l;
    char c;

    fscanf(fp,"%d ",&x);
    sp->shp_x = (coord)x;
    fscanf(fp,"%d ",&x);
    sp->shp_y = (coord)x;
    fscanf(fp,"%d ",&x);
    sp->shp_own = (natid)x;
    fscanf(fp,"%d ",&x);
    sp->shp_type=(char)x;
    fscanf(fp,"%d ",&x);
    sp->shp_effic=(char)x;
    fscanf(fp,"%d ",&x);
    sp->shp_mobil=(char)x;
    fscanf(fp,"%d ",&x);
    sp->shp_sell=(short)x;
    fscanf(fp,"%d ",&x);
    sp->shp_tech=(short)x;
    fscanf(fp,"%d ",&x);
    sp->shp_uid=(short)x;
    fscanf(fp,"%d ",&x);
    sp->shp_fleet=(char)x;
    fscanf(fp,"%d ",&x);
    sp->shp_nplane=(u_char)x;
#ifdef AUTONAV
    fscanf(fp,"%d ",&x);
    sp->shp_destx[0]=(coord)x;
    fscanf(fp,"%d ",&x);
    sp->shp_destx[1]=(coord)x;
    fscanf(fp,"%d ",&x);
    sp->shp_desty[0]=(coord)x;
    fscanf(fp,"%d ",&x);
    sp->shp_desty[1]=(coord)x;
    fscanf(fp,"%d ",&x);
    sp->shp_trdtype[0]=(u_char)x;
    fscanf(fp,"%d ",&x);
    sp->shp_trdtype[1]=(u_char)x;
    fscanf(fp,"%d ",&x);
    sp->shp_autonav=(u_char)x;
#endif /* AUTONAV */
    fscanf(fp,"%d ",&x);
    sp->shp_spare=(char)x;
    fscanf(fp,"%d ",&x);
    sp->shp_nv=(char)x;

    for(y=0;y<MAXSHPV;y++){
        fscanf(fp,"%d ",&x);
        sp->shp_vtype[y]=(u_char)x;
        }

    for(y=0;y<MAXSHPV;y++){
        fscanf(fp,"%d ",&x);
        sp->shp_vamt[y]=(u_short)x;
        }

#ifdef SAIL
    fscanf(fp,"%d ",&x);
    sp->shp_mobquota=(u_char)x;

    for(y=0;y<MAXSHPPATH;y++){
        fscanf(fp,"%d ",&x);
        sp->shp_path[y]=(char)x;
        }

    fscanf(fp,"%d ",&x);
    sp->shp_follow=(short)x;
#endif /* SAIL */

#ifdef SHIPNAMES
    for(y=0;y<MAXSHPNAMLEN;y++){
        fscanf(fp,"%d ",&x);
        sp->shp_name[y]=(char)x;
        }

    printf("Read ship '%s'\n",sp->shp_name);
#endif /* SHIPNAMES */
}
