Ejemplo n.º 1
0
void main(void) {
  printf("Input Filename\n");
  scanf("%128s", &szFileName);
  fflush (stdin);

  while (true) {
    getfileinfo();
    NewFileAttr = 0;
    printf ("\n1 - Change File Attributes\n0 - Exit\n");
    scanf("%d", &c);
    fflush (stdin);

    switch(c) {
      case 0:
        return;

      case 1: {
        printf ("\nSet ARCHIVE\t\t (Y/N):");

        if (cc = getch(), cc == 'y' || cc == 'Y') NewFileAttr |= FILE_ATTRIBUTE_ARCHIVE;

        printf ("\nSet HIDDEN\t\t (Y/N):");

        if (cc = getch(), cc == 'y' || cc == 'Y') NewFileAttr |= FILE_ATTRIBUTE_HIDDEN;

        printf ("\nSet READONLY\t\t (Y/N):");

        if (cc = getch(), cc == 'y' || cc == 'Y') NewFileAttr |= FILE_ATTRIBUTE_READONLY;

        printf ("\nSet SYSTEM\t\t (Y/N):");

        if (cc = getch(), cc == 'y' || cc == 'Y') NewFileAttr |= FILE_ATTRIBUTE_SYSTEM;

        SetFileAttributes(szFileName, NewFileAttr);
        break;
      }

    }


  }


}
Ejemplo n.º 2
0
int8_t RogueSD::seektoend(int8_t handle)
{
  if ((_moduletype == uMMC && _fwversion < UMMC_MIN_FW_VERSION_FOR_NEW_COMMANDS) ||
      (_moduletype == uMP3 && _fwversion < UMP3_MIN_FW_VERSION_FOR_NEW_COMMANDS))
  {
    // old
    // two step process - get filesize, seek to that position
    return seek(handle, getfileinfo(handle).size);
  }
  else
  {
    // new
    if (_moduletype != uMMC) { print("FC"); };
    // J fh E
    print('J'); write('0'+handle); print('E'); print('\r');
  }

  return _get_response();
}
Ejemplo n.º 3
0
int16_t RogueSD::read(int8_t handle, uint16_t count, char *buffer)
{
  // read up to count bytes into buffer
  uint32_t bytesremaining;
  uint16_t i;
  fileinfo fi = getfileinfo(handle);

  // check first how many bytes are remaining
  bytesremaining = fi.size - fi.position;

  if(bytesremaining > 0)
  {
    if(count > bytesremaining)
      count = bytesremaining;
    if (_moduletype != uMMC) { print("FC"); };
    print('R'); write('0'+handle); print(' '); print(count); print('\r');
  }
  else
  {
    return 0;
  }

  // now read count bytes
  
  if(_get_response())
  {
    if(LastErrorCode == ERROR_EOF)
      return -1;
    else
      return -2;
  }

  for(i=0; i<count; i++)
    buffer[i] = _read_blocked();

  _read_blocked();                      // consume prompt
  
  return i;                             // return number of bytes read
}
Ejemplo n.º 4
0
int convert_slice(slice *slicei, int *thread_index) {

    char slicefile_svz[1024], slicesizefile_svz[1024];
    int fileversion, one, zero;
    char *slice_file;
    int version_local;
    char filetype[1024];
    char *shortlabel, *unit;
    char units[256];
    int ijkbar[6];
    uLong framesize;
    float *sliceframe_data=NULL;
    unsigned char *sliceframe_compressed=NULL, *sliceframe_uncompressed=NULL;
    unsigned char *sliceframe_compressed_rle=NULL, *sliceframe_uncompressed_rle=NULL;
    char cval[256];
    int sizebefore, sizeafter;
    int returncode;
    float minmax[2];
    float time_local;
    LINT data_loc;
    int percent_done;
    int percent_next=10;
    float valmin, valmax, denom;
    int chop_min, chop_max;
    uLongf ncompressed_zlib;
    int ncompressed_save;
#ifndef pp_THREAD
    int count=0;
#endif
    int ncol, nrow, idir;
    float time_max;
    int itime;
    LINT file_loc;

    FILE *SLICEFILE;
    FILE *slicestream,*slicesizestream;

#ifdef pp_THREAD
    if(GLOBcleanfiles==0) {
        int fileindex;

        fileindex = slicei + 1 - sliceinfo;
        sprintf(threadinfo[*thread_index].label,"sf %i",fileindex);
    }
#endif

    slice_file=slicei->file;
    version_local=slicei->version;

    fileversion = 1;
    one = 1;
    zero=0;

    // check if slice file is accessible

    strcpy(filetype,"");
    shortlabel=slicei->label.shortlabel;
    if(strlen(shortlabel)>0)strcat(filetype,shortlabel);
    trim(filetype);

    if(getfileinfo(slice_file,NULL,NULL)!=0) {
        fprintf(stderr,"*** Warning: The file %s does not exist\n",slice_file);
        return 0;
    }

    SLICEFILE=fopen(slice_file,"rb");
    if(SLICEFILE==NULL) {
        fprintf(stderr,"*** Warning: The file %s could not be opened\n",slice_file);
        return 0;
    }

    // set up slice compressed file

    if(GLOBdestdir!=NULL) {
        strcpy(slicefile_svz,GLOBdestdir);
        strcat(slicefile_svz,slicei->filebase);
    }
    else {
        strcpy(slicefile_svz,slicei->file);
    }
    {

        char *ext;
        int lensvz;

        lensvz = strlen(slicefile_svz);

        if(lensvz>4) {
            ext = slicefile_svz + lensvz - 4;
            if(strcmp(ext,".rle")==0) {
                slicefile_svz[lensvz-4]=0;
            }
            strcat(slicefile_svz,".svz");
        }
    }

    if(GLOBdestdir!=NULL) {
        strcpy(slicesizefile_svz,GLOBdestdir);
        strcat(slicesizefile_svz,slicei->filebase);
    }
    else {
        strcpy(slicesizefile_svz,slicei->file);
    }
    {

        char *ext;
        int lensvz;

        lensvz = strlen(slicesizefile_svz);

        if(lensvz>4) {
            ext = slicesizefile_svz + lensvz - 4;
            if(strcmp(ext,".rle")==0) {
                slicesizefile_svz[lensvz-4]=0;
            }
            strcat(slicesizefile_svz,".sz");
        }
    }

    if(GLOBcleanfiles==1) {
        slicestream=fopen(slicefile_svz,"rb");
        if(slicestream!=NULL) {
            fclose(slicestream);
            PRINTF("  Removing %s\n",slicefile_svz);
            UNLINK(slicefile_svz);
            LOCK_COMPRESS;
            GLOBfilesremoved++;
            UNLOCK_COMPRESS;
        }
        slicesizestream=fopen(slicesizefile_svz,"rb");
        if(slicesizestream!=NULL) {
            fclose(slicesizestream);
            PRINTF("  Removing %s\n",slicesizefile_svz);
            UNLINK(slicesizefile_svz);
            LOCK_COMPRESS;
            GLOBfilesremoved++;
            UNLOCK_COMPRESS;
        }
        return 0;
    }

    if(GLOBoverwrite_slice==0) {
        slicestream=fopen(slicefile_svz,"rb");
        if(slicestream!=NULL) {
            fclose(slicestream);
            fprintf(stderr,"*** Warning:  %s exists.\n",slicefile_svz);
            fprintf(stderr,"     Use the -f option to overwrite smokezip compressed files\n");
            return 0;
        }
    }

    slicestream=fopen(slicefile_svz,"wb");
    slicesizestream=fopen(slicesizefile_svz,"w");
    if(slicestream==NULL||slicesizestream==NULL) {
        if(slicestream==NULL) {
            fprintf(stderr,"*** Warning: The file %s could not be opened for writing\n",slicefile_svz);
        }
        if(slicesizestream==NULL) {
            fprintf(stderr,"  %s could not be opened for writing\n",slicesizefile_svz);
        }
        if(slicestream!=NULL)fclose(slicestream);
        if(slicesizestream!=NULL)fclose(slicesizestream);
        fclose(SLICEFILE);
        return 0;
    }

    // read and write slice header

    strcpy(units,"");
    unit=slicei->label.unit;
    if(strlen(unit)>0)strcat(units,unit);
    trim(units);
    sprintf(cval,"%f",slicei->valmin);
    trimzeros(cval);
#ifndef pp_THREAD
    if(GLOBcleanfiles==0) {
        PRINTF("Compressing %s (%s)\n",slice_file,filetype);
        PRINTF("  using min=%s %s",cval,units);
    }
#endif
    sprintf(cval,"%f",slicei->valmax);
    trimzeros(cval);
#ifndef pp_THREAD
    if(GLOBcleanfiles==0) {
        PRINTF(" max=%s %s\n",cval,units);
        PRINTF(" ");
    }
#endif
    valmin=slicei->valmin;
    valmax=slicei->valmax;
    denom = valmax-valmin;
    if(denom==0.0)denom=1.0;

    chop_min=0;
    chop_max=255;
    if(GLOBno_chop==0) {
        if(slicei->setchopvalmax==1) {
            chop_max = 255*(slicei->chopvalmax-valmin)/denom;
            if(chop_max<0)chop_max=0;
            if(chop_max>255)chop_max=255;
        }
        if(slicei->setchopvalmin==1) {
            chop_min = 255*(slicei->chopvalmin-valmin)/denom;
            if(chop_min<0)chop_min=0;
            if(chop_min>255)chop_min=255;
        }
    }


    fwrite(&one,4,1,slicestream);           // write out a 1 to determine "endianness" when file is read in later
    fwrite(&zero,4,1,slicestream);          // write out a zero now, then a one just before file is closed
    fwrite(&fileversion,4,1,slicestream);   // write out compressed fileversion in case file format changes later
    fwrite(&version_local,4,1,slicestream);       // fds slice file version
    sizeafter=16;

    //*** SLICE FILE FORMATS

    //*** FDS FORMAT (FORTRAN - each FORTRAN record has a 4 byte header and a 4 byte trailer surrounding the data)

    // 30 byte long label
    // 30 byte short label
    // 30 byte unit
    // i1,i2,j1,j2,k1,k2

    // for each time step:

    // time, compressed frame size
    // qq(1,nbuffer)              where nbuffer = (i2+1-i1)*(j2+1-j1)*(k2+1-k1)



    //*** ZLIB format (C - no extra bytes surrounding data)

    //*** header
    // endian
    // completion (0/1)
    // fileversion (compressed format)
    // version_local  (slicef version)
    // global min max (used to perform conversion)
    // i1,i2,j1,j2,k1,k2


    //*** frame
    // time, compressed frame size                        for each frame
    // compressed buffer


    //*** RLE format (FORTRAN)

    //*** header
    // endian
    // fileversion, slice version
    // global min max (used to perform conversion)
    // i1,i2,j1,j2,k1,k2


    //*** frame
    // time
    // compressed frame size                        for each frame
    // compressed buffer

    {
        int skip;

        skip = 3*(4+30+4);  // skip over 3 records each containing a 30 byte FORTRAN character string
        returncode=FSEEK(SLICEFILE,skip,SEEK_CUR);
        sizebefore=skip;
    }

    FORTSLICEREAD(ijkbar,6);
    sizebefore+=8+6*4;

    framesize =  (ijkbar[1]+1-ijkbar[0]);
    framesize *= (ijkbar[3]+1-ijkbar[2]);
    framesize *= (ijkbar[5]+1-ijkbar[4]);

    minmax[0]=slicei->valmin;
    minmax[1]=slicei->valmax;
    fwrite(minmax,4,2,slicestream);    // min max vals
    fwrite(ijkbar,4,6,slicestream);
    sizeafter+=(8+24);


    ncompressed_save=1.02*framesize+600;
    if(NewMemory((void **)&sliceframe_data,ncompressed_save*sizeof(float))==0)goto wrapup;
    if(NewMemory((void **)&sliceframe_compressed,ncompressed_save*sizeof(unsigned char))==0)goto wrapup;
    if(NewMemory((void **)&sliceframe_uncompressed,ncompressed_save*sizeof(unsigned char))==0)goto wrapup;

    fprintf(slicesizestream,"%i %i %i %i %i %i\n",ijkbar[0],ijkbar[1],ijkbar[2],ijkbar[3],ijkbar[4],ijkbar[5]);
    fprintf(slicesizestream,"%f %f\n",minmax[0],minmax[1]);

    idir=0;
    if(ijkbar[0]==ijkbar[1]) {
        idir=1;
        ncol = ijkbar[3] + 1 - ijkbar[2];
        nrow = ijkbar[5] + 1 - ijkbar[4];
    }
    else if(ijkbar[2]==ijkbar[3]) {
        idir=2;
        ncol = ijkbar[1] + 1 - ijkbar[0];
        nrow = ijkbar[5] + 1 - ijkbar[4];
    }
    else if(ijkbar[4]==ijkbar[5]) {
        idir=3;
        ncol = ijkbar[1] + 1 - ijkbar[0];
        nrow = ijkbar[3] + 1 - ijkbar[2];
    }
    if(idir==0) {
        idir=1;
        ncol = ijkbar[3] + 1 - ijkbar[2];
        nrow = ijkbar[5] + 1 - ijkbar[4];
    }


    {
        int ni, nj, nk;

        ni = ijkbar[1]+1-ijkbar[0];
        nj = ijkbar[3]+1-ijkbar[2];
        nk = ijkbar[5]+1-ijkbar[4];

        time_max=-1000000.0;
        itime=-1;
        for(;;) {
            int i;

            FORTSLICEREAD(&time_local,1);
            sizebefore+=12;
            if(returncode==0)break;
            FORTSLICEREAD(sliceframe_data,framesize);    //---------------
            if(returncode==0)break;

            sizebefore+=(8+framesize*4);
            if(time_local<time_max)continue;
            time_max=time_local;

#ifndef pp_THREAD
            count++;
#endif

            data_loc=FTELL(SLICEFILE);
            percent_done=100.0*(float)data_loc/(float)slicei->filesize;
#ifdef pp_THREAD
            threadinfo[*thread_index].stat=percent_done;
            if(percent_done>percent_next) {
                LOCK_PRINT;
                print_thread_stats();
                UNLOCK_PRINT;
                percent_next+=10;
            }
#else
            if(percent_done>percent_next) {
                PRINTF(" %i%s",percent_next,GLOBpp);
                FFLUSH();
                percent_next+=10;
            }
#endif
            for(i=0; i<framesize; i++) {
                int ival;
                int icol, jrow, index2;
                int ii,jj,kk;

                // val_in(i,j,k) = i + j*ni + k*ni*nj

                if(framesize<=ncol*nrow) { // only one slice plane

                    // i = jrow*ncol + icol;

                    icol = i%ncol;
                    jrow = i/ncol;

                    index2 = icol*nrow + jrow;
                }
                else {
                    ii = i%ni;
                    jj = (i/ni)%nj;
                    kk = i/(ni*nj);

                    index2 = ii*nj*nk + jj*nk + kk;
                }

                {
                    float val;

                    val = sliceframe_data[i];
                    if(val<valmin) {
                        ival=0;
                    }
                    else if(val>valmax) {
                        ival=255;
                    }
                    else {
                        ival = 1 + 253*(val-valmin)/denom;
                    }
                    if(ival<chop_min)ival=0;
                    if(ival>chop_max)ival=255;
                    sliceframe_uncompressed[index2] = ival;
                }
            }
            itime++;
            if(itime%GLOBslicezipstep!=0)continue;

            //int compress (Bytef *dest,   uLongf *destLen, const Bytef *source, uLong sourceLen);
            ncompressed_zlib=ncompressed_save;
            returncode=compress(sliceframe_compressed,&ncompressed_zlib,sliceframe_uncompressed,framesize);

            file_loc=FTELL(slicestream);
            fwrite(&time_local,4,1,slicestream);
            fwrite(&ncompressed_zlib,4,1,slicestream);
            fwrite(sliceframe_compressed,1,ncompressed_zlib,slicestream);
            sizeafter+=(8+ncompressed_zlib);
            fprintf(slicesizestream,"%f %i, %li\n",time_local,(int)ncompressed_zlib,(long)file_loc);
        }
        if(returncode!=0) {
            fprintf(stderr,"*** Error: compress returncode=%i\n",returncode);
        }
    }

wrapup:
#ifndef pp_THREAD
    PRINTF(" 100%s completed\n",GLOBpp);
#endif
    FREEMEMORY(sliceframe_data);
    FREEMEMORY(sliceframe_compressed);
    FREEMEMORY(sliceframe_uncompressed);
    FREEMEMORY(sliceframe_compressed_rle);
    FREEMEMORY(sliceframe_uncompressed_rle);

    fclose(SLICEFILE);
    FSEEK(slicestream,4,SEEK_SET);
    fwrite(&one,4,1,slicestream);  // write completion code
    fclose(slicestream);
    fclose(slicesizestream);

    {
        char before_label[256],after_label[256];

        getfilesizelabel(sizebefore,before_label);
        getfilesizelabel(sizeafter,after_label);
#ifdef pp_THREAD
        slicei->compressed=1;
        sprintf(slicei->summary,"compressed from %s to %s (%4.1f%s reduction)",before_label,after_label,(float)sizebefore/(float)sizeafter,GLOBx);
        threadinfo[*thread_index].stat=-1;
#else
        PRINTF("  records=%i, ",count);
        PRINTF("Sizes: original=%s, ",before_label);
        PRINTF("compressed=%s (%4.1f%s reduction)\n\n",after_label,(float)sizebefore/(float)sizeafter,GLOBx);
#endif
    }

    return 1;
}
Ejemplo n.º 5
0
int convert_volslice(slice *slicei, int *thread_index) {
    char slicefile_svz[1024];
    char *slice_file;
    char filetype[1024];
    char *shortlabel;
    int ijkbar[6];
    uLong framesize;
    float *sliceframe_data=NULL;
    int sizebefore, sizeafter;
    int returncode;
    LINT data_loc;
    int percent_done;
    int percent_next=10;
#ifndef pp_THREAD
    int count=0;
#endif
    FILE *SLICEFILE;
    FILE *slicestream;

#ifdef pp_THREAD
    if(GLOBcleanfiles==0) {
        int fileindex;

        fileindex = slicei + 1 - sliceinfo;
        sprintf(threadinfo[*thread_index].label,"vsf %i",fileindex);
    }
#endif

    slice_file=slicei->file;

    // check if slice file is accessible

    strcpy(filetype,"");
    shortlabel=slicei->label.shortlabel;
    if(strlen(shortlabel)>0)strcat(filetype,shortlabel);
    trim(filetype);

    if(getfileinfo(slice_file,NULL,NULL)!=0) {
        fprintf(stderr,"*** Warning: The file %s does not exist\n",slice_file);
        return 0;
    }

    SLICEFILE=fopen(slice_file,"rb");
    if(SLICEFILE==NULL) {
        fprintf(stderr,"*** Warning: The file %s could not be opened\n",slice_file);
        return 0;
    }

    // set up slice compressed file

    if(GLOBdestdir!=NULL) {
        strcpy(slicefile_svz,GLOBdestdir);
        strcat(slicefile_svz,slicei->filebase);
    }
    else {
        strcpy(slicefile_svz,slicei->file);
    }

    if(strlen(slicefile_svz)>4)strcat(slicefile_svz,".svv");

    if(GLOBcleanfiles==1) {
        slicestream=fopen(slicefile_svz,"rb");
        if(slicestream!=NULL) {
            fclose(slicestream);
            PRINTF("  Removing %s\n",slicefile_svz);
            UNLINK(slicefile_svz);
            LOCK_COMPRESS;
            GLOBfilesremoved++;
            UNLOCK_COMPRESS;
        }
        return 0;
    }

    if(GLOBoverwrite_slice==0) {
        slicestream=fopen(slicefile_svz,"rb");
        if(slicestream!=NULL) {
            fclose(slicestream);
            fprintf(stderr,"*** Warning: The file %s exists.\n",slicefile_svz);
            fprintf(stderr,"     Use the -f option to overwrite smokezip compressed files\n");
            return 0;
        }
    }

    slicestream=fopen(slicefile_svz,"wb");
    if(slicestream==NULL) {
        fprintf(stderr,"*** Warning: The file %s could not be opened for writing\n",slicefile_svz);
        return 0;
    }

    // read and write slice header

#ifndef pp_THREAD
    if(GLOBcleanfiles==0) {
        PRINTF("Compressing %s (%s)\n",slice_file,filetype);
    }
#endif


    {
        int skip;

        skip = 3*(4+30+4);  // skip over 3 records each containing a 30 byte FORTRAN character string
        returncode=FSEEK(SLICEFILE,skip,SEEK_CUR);
        sizebefore=skip;
    }

    FORTSLICEREAD(ijkbar,6);
    sizebefore+=4+6*4+4;
    sizeafter=0;

    {
        int one=1, version_local=0, completion=0;

        fwrite(&one,4,1,slicestream);
        fwrite(&version_local,4,1,slicestream);
        fwrite(&completion,4,1,slicestream);
    }


    {
        int ni, nj, nk;

        ni = ijkbar[1]+1-ijkbar[0];
        nj = ijkbar[3]+1-ijkbar[2];
        nk = ijkbar[5]+1-ijkbar[4];
        framesize = ni*nj*nk;
        NewMemory((void **)&sliceframe_data,framesize*sizeof(float));

        for(;;) {
            float vmin, vmax;
            float *valmin, *valmax;
            unsigned char *compressed_data_out;
            uLongf ncompressed_data_out;
            float time_local;

            FORTSLICEREAD(&time_local,1);
            if(returncode==0)break;
            CheckMemory;
            sizebefore+=12;

            FORTSLICEREAD(sliceframe_data,framesize);    //---------------
            if(returncode==0)break;
            CheckMemory;
            sizebefore+=(4+framesize*sizeof(float)+4);

            valmin=NULL;
            valmax=NULL;
            if(slicei->voltype==1) {
                vmin=0.0;
                valmin=&vmin;
            }
            else if(slicei->voltype==2) {
                vmin=20.0;
                valmin=&vmin;
                vmax=1400.0;
                valmax=&vmax;
            }
            else {
                ASSERT(0);
            }
            CheckMemory;
            compress_volsliceframe(sliceframe_data, framesize, time_local, valmin, valmax,
                                   &compressed_data_out, &ncompressed_data_out);
            CheckMemory;
            sizeafter+=ncompressed_data_out;
            if(ncompressed_data_out>0) {
                fwrite(compressed_data_out,1,ncompressed_data_out,slicestream);
            }
            CheckMemory;
            FREEMEMORY(compressed_data_out);

#ifndef pp_THREAD
            count++;
#endif

            data_loc=FTELL(SLICEFILE);
            percent_done=100.0*(float)data_loc/(float)slicei->filesize;
#ifdef pp_THREAD
            threadinfo[*thread_index].stat=percent_done;
            if(percent_done>percent_next) {
                LOCK_PRINT;
                print_thread_stats();
                UNLOCK_PRINT;
                percent_next+=10;
            }
#else
            if(percent_done>percent_next) {
                PRINTF(" %i%s",percent_next,GLOBpp);
                FFLUSH();
                percent_next+=10;
            }
#endif

        }
        if(returncode!=0) {
            fprintf(stderr,"*** Error: compress returncode=%i\n",returncode);
        }
        FREEMEMORY(sliceframe_data);
    }

#ifndef pp_THREAD
    PRINTF(" 100%s completed\n",GLOBpp);
#endif

    {
        int completion=1;

        FSEEK(slicestream,4,SEEK_SET);
        fwrite(&completion,4,1,slicestream);
    }
    fclose(SLICEFILE);
    fclose(slicestream);

    {
        char before_label[256],after_label[256];

        getfilesizelabel(sizebefore,before_label);
        getfilesizelabel(sizeafter,after_label);
#ifdef pp_THREAD
        slicei->vol_compressed=1;
        sprintf(slicei->volsummary,"compressed from %s to %s (%4.1f%s reduction)",before_label,after_label,(float)sizebefore/(float)sizeafter,GLOBx);
        threadinfo[*thread_index].stat=-1;
#else
        PRINTF("  records=%i, ",count);
        PRINTF("Sizes: original=%s, ",before_label);
        PRINTF("compressed=%s (%4.1f%s reduction)\n\n",after_label,(float)sizebefore/(float)sizeafter,GLOBx);
#endif
    }

    return 1;

}
Ejemplo n.º 6
0
int main(int argc, char **argv){

//  Bytef *source,*sourcecheck,*dest;
//  int sourceLen, destLen;
//  int returncode;

  char *arg;

  char *filebase;
  int filelen;
  char smvfile[1024];
  char smzlogfile[1024];
  char smvfilebase[1024];
  char *ext;
  char inifile[1024];
  char inifilebase[1024];
  char *prog;
  int i;
  int endian_fds;
  int endian_info;
  int redirect=0;

  set_stdout(stdout);
  initMALLOC();
  GLOBdoit_lighting=0;
  GLOBdoit_smoke3d=1;
  GLOBdoit_boundary=1;
  GLOBdoit_slice=1;
  GLOBdoit_volslice=1;
#ifdef pp_PLOT3D
  GLOBdoit_plot3d=1;
#else
  GLOBdoit_plot3d=0;
#endif
#ifdef pp_PART2
  GLOBdoit_particle=0;
#endif

#ifdef pp_KDTEST
  test_kd();
  exit(0);
#endif
  strcpy(GLOBpp,"%");
  strcpy(GLOBx,"X");
  GLOBfirst_initsphere=1;
  GLOBfirst_slice=1;
  GLOBfirst_patch=1;
  GLOBfirst_plot3d=1;
  GLOBfirst_part2iso=1;
  GLOBfirst_part2iso_smvopen=1;
#ifdef pp_THREAD
  mt_nthreads=2;
#endif
  GLOBframeskip=-1;
  GLOBno_chop=0;
  GLOBautozip=0;
  GLOBmake_demo=0;
  GLOBendf=0;
  GLOBsyst=0;
  GLOBendianfile=NULL;
  GLOBdestdir=NULL;
  GLOBsourcedir=NULL;
  endianswitch=-1;
  GLOBoverwrite_b=0;
  GLOBoverwrite_s=0;
  GLOBget_bounds=0;
  GLOBget_slice_bounds=0;
  GLOBget_plot3d_bounds=0;
  GLOBget_boundary_bounds=0;
#ifdef pp_PART
  GLOBget_part_bounds=0;
  GLOBpartfile2iso=0;
#endif
  GLOBoverwrite_slice=0;
  GLOBoverwrite_volslice=0;
  GLOBoverwrite_plot3d=0;
  endian_info=0;
  GLOBcleanfiles=0;
  GLOBsmoke3dzipstep=1;
  GLOBboundzipstep=1;
  GLOBslicezipstep=1;
  GLOBfilesremoved=0;

  npatchinfo=0;
  nsmoke3dinfo=0;
#ifdef pp_PART
  npartinfo=0;
  npartclassinfo=0;
  partinfo=NULL;
  partclassinfo=NULL;
  maxpart5propinfo=0;
  npart5propinfo=0;
#endif
  nsliceinfo=0;
  sliceinfo=NULL;
  nmeshes=0;

  patchinfo=NULL;
  smoke3dinfo=NULL;

  prog=argv[0];
  filebase=NULL;
  if(argc==1){
    version();
    return 1;
  }

  for(i=1;i<argc;i++){
    int lenarg;
    int lenarg2;
    char *arg2;

    arg=argv[i];
    lenarg=strlen(arg);
    if(arg[0]=='-'&&lenarg>1){
      switch(arg[1]){
      case 'a':
        GLOBautozip=1;
        break;
      case 'b':
        if(strcmp(arg,"-bounds")==0){
          GLOBget_bounds=1;
          GLOBget_slice_bounds=1;
#ifdef pp_PLOT3D
          GLOBget_plot3d_bounds=1;
#endif
          GLOBget_boundary_bounds=1;
#ifdef pp_PART
          GLOBget_part_bounds=1;
#endif
        }
        else if(strcmp(arg,"-bb")==0){
          GLOBget_boundary_bounds=1;
        }
        else if(strcmp(arg,"-bs")==0){
          GLOBget_slice_bounds=1;
        }
#ifdef pp_PLOT3D
        else if(strcmp(arg,"-bp")==0){
          GLOBget_plot3d_bounds=1;
        }
#endif
#ifdef pp_PART2
        else if(strcmp(arg,"-bP")==0){
          GLOBget_part_bounds=1;
        }
#endif
        else{
          GLOBoverwrite_b=1;
        }
        break;
#ifdef pp_PART2
      case 'y':
        if(strcmp(arg,"-yP")==0){
          GLOBdoit_particle=1;
        }
        break;
#endif
      case 'l':
        GLOBdoit_lighting=1;
        break;
      case 'n':
        if(strcmp(arg,"-n3")==0){
          GLOBdoit_smoke3d=0;
        }
        else if(strcmp(arg,"-nb")==0){
          GLOBdoit_boundary=0;
        }
#ifdef pp_PLOT3D
        else if(strcmp(arg,"-np")==0){
          GLOBdoit_plot3d=0;
        }
#endif
#ifdef pp_PART2
        else if(strcmp(arg,"-nP")==0){
          GLOBdoit_particle=0;
        }
#endif
        else if(strcmp(arg,"-ns")==0){
          GLOBdoit_slice=0;
        }
        else if(strcmp(arg,"-nvs")==0){
          GLOBdoit_volslice=0;
        }
        else if(strcmp(arg,"-no_chop")==0){
          GLOBno_chop=1;
        }
        break;
      case '2':
        GLOBoverwrite_slice=1;
        break;
      case '3':
        GLOBoverwrite_volslice=1;
        GLOBoverwrite_s=1;
        break;
#ifdef  pp_PART2
      case 'P':
        GLOBoverwrite_part=1;
        break;
#endif
      case 'p':
        if(strcmp(arg,"-part2iso")==0){
          GLOBpartfile2iso=1;
        }
#ifdef pp_PLOT3D
        else{
          GLOBoverwrite_plot3d=1;
        }
#endif
        break;
      case 'f':
        GLOBoverwrite_b=1;
        GLOBoverwrite_s=1;
        GLOBoverwrite_slice=1;
        GLOBoverwrite_volslice=1;
#ifdef pp_PLOT3D
        GLOBoverwrite_plot3d=1;
#endif
#ifdef pp_PART2
        GLOBoverwrite_part=1;
#endif
        break;
      case 'c':
        GLOBcleanfiles=1;
        break;
      case 'e':
        endian_info=1;
        break;
      case 'r':
        redirect=1;
        break;
      case 's':
        if(i+1>=argc)break;
        if(lenarg==2){
            lenarg2=strlen(argv[i+1]);
            NewMemory((void **)&GLOBsourcedir,lenarg2+2);
            strcpy(GLOBsourcedir,argv[i+1]);
            if(GLOBsourcedir[lenarg2-1]!=dirseparator[0]){
              strcat(GLOBsourcedir,dirseparator);
            }
            if(getfileinfo(GLOBsourcedir,NULL,NULL)!=0){
              fprintf(stderr,"*** Warning: The source directory specified, %s, does not exist or cannot be accessed\n",GLOBsourcedir);
              return 1;
            }
           i++;
        }
        else if(strcmp(arg,"-skip")==0){
          GLOBframeskip=-1;
          arg2=argv[i+1];
          sscanf(arg2,"%i",&GLOBframeskip);
          if(GLOBframeskip>0){
            GLOBslicezipstep=GLOBframeskip;
            GLOBsmoke3dzipstep=GLOBframeskip;
            GLOBboundzipstep=GLOBframeskip;
          }
          i++;
        }
        break;
      case 'd':
        if(strcmp(arg,"-demo")==0){
          GLOBautozip=1;
          GLOBmake_demo=1;
          break;
        }
        if(i+1<argc){
          lenarg2=strlen(argv[i+1]);
          NewMemory((void **)&GLOBdestdir,lenarg2+2);
          strcpy(GLOBdestdir,argv[i+1]);
          if(GLOBdestdir[lenarg2-1]!=dirseparator[0]){
            strcat(GLOBdestdir,dirseparator);
          }
 //         if(getfileinfo(GLOBdestdir,NULL,NULL)!=0){
 //           fprintf(stderr,"*** Warning: The destination directory %s does not exist or cannot be accessed\n",GLOBdestdir);
 //           return 1;
 //         }
          i++;
        }
        break;
#ifdef pp_THREAD
      case 't':
        mt_compress=1;
        if(i+1<argc){
          arg2=argv[i+1];
          sscanf(arg2,"%i",&mt_nthreads);
          if(mt_nthreads<1)mt_nthreads=1;
          if(mt_nthreads>NTHREADS_MAX)mt_nthreads=NTHREADS_MAX;
          i++;
        }
        break;
#endif
      case 'h':
        usage(prog);
        return 1;
      case 'v':
        version();
        return 1;
      default:
        usage(prog);
        return 1;
      }
    }
    else{
      if(filebase==NULL){
        filebase=argv[i];
      }
    }
  }

#ifdef pp_THREAD
  if(GLOBcleanfiles==1)mt_nthreads=1;
#endif

  // construct smv filename
  
  if(filebase==NULL){
    usage(prog);
    return 1;
  }
#ifdef pp_THREAD
  init_pthread_mutexes();
#endif
  filelen=strlen(filebase);
  if(filelen>4){
    ext=filebase+filelen-4;
    if(strcmp(ext,".smv")==0){
      ext[0]=0;
      filelen=strlen(filebase);
    }
  }
  if(GLOBsourcedir==NULL){
    strcpy(smvfile,filebase);
    strcpy(smzlogfile,filebase);
  }
  else{
    strcpy(smvfile,GLOBsourcedir);
    strcat(smvfile,filebase);
    strcpy(smzlogfile,GLOBsourcedir);
    strcat(smzlogfile,filebase);
  }
  strcpy(smvfilebase,filebase);
  if(GLOBpartfile2iso==1||GLOBcleanfiles==1){
    strcpy(GLOBsmvisofile,smvfile);
    strcat(GLOBsmvisofile,".isosmv");
  }

  strcat(smvfile,".smv");
  if(redirect==1){
    if(GLOBsourcedir==NULL){
      strcpy(smzlogfile,filebase);
    }
    else{
      strcpy(smzlogfile,GLOBsourcedir);
      strcat(smzlogfile,filebase);
    }
    strcat(smzlogfile,".smzlog");
    SMZLOG_STREAM=fopen(smzlogfile,"w");
    if(SMZLOG_STREAM!=NULL){
      set_stdout(SMZLOG_STREAM);
    }
  }
  
  // construct ini file name

  strcpy(inifile,smvfile);
  inifile[strlen(inifile)-4]=0;
  strcat(inifile,".ini");
  strcpy(inifilebase,filebase);
  strcat(inifilebase,".ini");

  strcpy(GLOBendianfilebase,"");

  // make sure smv file name exists

  if(getfileinfo(smvfile,NULL,NULL)!=0){
    fprintf(stderr,"*** Error: The file %s does not exist\n",smvfile);
    return 1;
  }

  // make sure smv file can be opened

  if(readsmv(smvfile)!=0)return 1;

#ifdef pp_PLOT3D
  if(nplot3dinfo>0){
    plot3dinfo[0].dup=0;
    for(i=1;i<nplot3dinfo;i++){
      plot3d *plot3di; 

      plot3di = plot3dinfo + i;

      plot3di->dup=0;
      plot3ddup(plot3di,i);
    }
  }
#endif
  if(npatchinfo>0){
    patchinfo->dup=0;
    for(i=1;i<npatchinfo;i++){
      patch *patchi; 

      patchi = patchinfo + i;

      patchi->dup=0;
      patchdup(patchi,i);
    }
  }
  if(nsliceinfo>0){
    sliceinfo[0].dup=0;
    for(i=1;i<nsliceinfo;i++){
      slice *slicei; 

      slicei = sliceinfo + i;

      slicei->dup=0;
      slicedup(slicei,i);
    }
  }

  if(getendian()==1){
      PRINTF("Smokezip running on a big endian computer.\n");
  }
  else{
      PRINTF("Smokezip running on a little endian computer.\n");
  }
  if(GLOBendf==0&&GLOBsyst==0){
    fprintf(stderr,"Warning: casename.end file is missing.  Endianness of\n");
    fprintf(stderr,"         FDS boundary file data is unknown.\n");
    if(getendian()==1){
      fprintf(stderr,"         Assuming FDS boundary data is big endian - \n");
    }
    if(getendian()==0){
      fprintf(stderr,"         Assuming FDS boundary data is little endian - \n");
    }
    fprintf(stderr,"         or equivalently assuming FDS and Smokezip are\n");
    fprintf(stderr,"         being run on the same type of computer\n");
    endianswitch=0;
  }
  else{
    endian_fds=getendian()+endianswitch;
    if(endian_fds==2)endian_fds=0;
    if(endian_fds==1){
      PRINTF("FDS was run on a big endian computer. \n\n");
    }
    else{
      PRINTF("FDS was run on a little endian computer.\n\n");
    }
  }
  if(endian_info==1)return 0;

  readini(inifile);

#ifdef pp_THREAD
  mt_compress_all();
#else
  compress_all(NULL);
#endif

  if(GLOBcleanfiles==0&&GLOBdestdir!=NULL){
    PRINTF("Copying .smv, .ini and .end files to %s directory\n",GLOBdestdir);
    filecopy(GLOBdestdir,smvfile,smvfilebase);
    filecopy(GLOBdestdir,inifile,inifilebase);
    filecopy(GLOBdestdir,GLOBendianfile,GLOBendianfilebase);
  }
  if(GLOBcleanfiles==1&&GLOBfilesremoved==0){
    PRINTF("No compressed files were removed\n");
  }
  if(GLOBmake_demo==1){
    makesvd(GLOBdestdir,smvfile);
  }
  return 0;
}
Ejemplo n.º 7
0
static bbc_status_t retrieve_file(serial_h com, filelist *file)
{
  bbc_status_t result ;

  file->type = 0 ;

  if ( (result = getfileinfo(com, file)) == BBC_OK ) {
    char pcname[MAXLINELEN] ;
    FILE *pcfile ;
    bool fileerr = false ;

    if ( file->type == 0 ) { /* OSFILE returned 0 */
      printf("File %s does not exist on BBC, skipping\n", file->name) ;
      return BBC_OK ;
    }

    strcpy(pcname, file->name) ;

    /* Check if PC name is used */
    if ( !check_pcname(file->type == 2 ? "Directory" : "File",
                       pcname, MAXLINELEN) )
      return BBC_OK ;

    if ( file->type == 1 ) { /* OSFILE indicates it's a file */
      char buffer[BBCTRACKSIZE] ;
      int fhandle, size ;

      if ( (pcfile = fopen(pcname, "wb")) == NULL ) {
        printf("Can't open PC file %s to retrieve %s, skipping\n",
               pcname, file->name) ;
        return BBC_OK ;
      }

      printf("Retrieving file %s %x %x %x %c%c%c%c to %s\n",
             file->name, file->load, file->exec, file->length,
             (file->attrs & FILE_Not_R) ? ' ' : 'R',
             (file->attrs & FILE_Not_W) ? ' ' : 'W',
             (file->attrs & FILE_Not_X) ? ' ' : 'X',
             (file->attrs & FILE_Not_D) ? 'L' : ' ',
             pcname) ;

      serial_printf(com, "S%s\r", file->name) ;

      if ( (result = bbc_readline(com, buffer, MAXLINELEN)) == BBC_SYNC &&
           (result = bbc_readline(com, buffer, MAXLINELEN)) == BBC_OK &&
           sscanf(buffer, "%d", &fhandle) == 1 &&
           fhandle != 0 &&
           (result = bbc_readline(com, buffer, MAXLINELEN)) == BBC_OK &&
           sscanf(buffer, "%d", &size) == 1 ) {
        int remaining = size, nbytes = 0 ;
        unsigned int crc = 0;

        while ( remaining > 0 ) {
          int rbytes = remaining > BBCTRACKSIZE ? BBCTRACKSIZE : remaining ;

          if ( (result = bbc_read(com, buffer, &rbytes)) == BBC_OK ) {
            if ( !fileerr &&
                 (int)fwrite(buffer, sizeof(char), rbytes, pcfile) != rbytes )
              fileerr = true ;
            remaining -= rbytes ;
            nbytes += rbytes ;
            crccalc(buffer, rbytes, &crc) ;
            printf("\rRead %d bytes of %d", nbytes, size) ;
            fflush(stdout) ;
          } else /* Error reading bytes */
            break ;
        }

        putchar('\n') ;

        if ( result == BBC_OK ) {
          unsigned int bbccrc = 0 ;

          if ( (result = bbc_readline(com, buffer, MAXLINELEN)) != BBC_OK ||
               sscanf(buffer, "%u", &bbccrc) != 1 ) {
            printf("Problem retrieving CRC for %s from BBC\n", file->name) ;
            fileerr = true ;
          } else if ( bbccrc != crc ) {
            printf("CRC error for %s (%x not equal to %x)\n",
                   file->name, crc, bbccrc) ;
            fileerr = true ;
          }
        }
      } else {
        printf("Problem opening %s on BBC, skipping\n", file->name) ;
        fileerr = true ;
      }

      fclose(pcfile) ;
    } else if ( file->type == 2 ) { /* OSFILE indicates it's a directory */
      char pcdir[MAXLINELEN], bbcdir[MAXLINELEN] ;
      filelist *subfiles = NULL ;

      printf("Retrieving directory %s %x %x %x %c%c%c%c to %s\n",
             file->name, file->load, file->exec, file->length,
             (file->attrs & FILE_Not_R) ? ' ' : 'R',
             (file->attrs & FILE_Not_W) ? ' ' : 'W',
             (file->attrs & FILE_Not_X) ? ' ' : 'X',
             (file->attrs & FILE_Not_D) ? 'L' : ' ',
             pcname) ;
      (void)mkdir(pcname, 0755) ;
      if ( getcwd(pcdir, MAXLINELEN) &&
           (result = getcurdir(com, bbcdir, MAXLINELEN)) == BBC_OK ) {
        if ( chdir(pcname) == 0 ) {
          if ( (result = setcurdir(com, file->name)) == BBC_SYNC ) {
            if ( (result = getfilenames(com, "*", &subfiles, false)) == BBC_SYNC ) {
              result = BBC_OK ;

              while ( subfiles && !interrupted(false) ) {
                filelist *next = subfiles->next ;

                if ( (result = retrieve_file(com, subfiles)) != BBC_OK ) {
                  printf("Error retrieving file %s, skipping\n",
                         subfiles->name) ;
                  free(subfiles) ;
                  subfiles = next ;
                  fileerr = true ;
                  break ;
                }

                free(subfiles) ;
                subfiles = next ;
              }

              while ( subfiles ) {
                filelist *next = subfiles->next ;
                printf("Skipping file %s because of previous error\n",
                       subfiles->name) ;
                free(subfiles) ;
                subfiles = next ;
              }

              if ( interrupted(true) )
                fileerr = true ;
            }

            if ( result == BBC_OK &&
                 (result = setcurdir(com, bbcdir)) == BBC_SYNC )
              result = BBC_OK ;
          }
          (void)chdir(pcdir) ;
        }
      }
    } else {
      printf("File %s has unknown OSFILE type %d, skipping\n",
             file->name, file->type) ;
      return BBC_OK ;
    }

    if ( result == BBC_OK && !fileerr ) { /* Write .inf file */
      char *basename ;

      strcat(pcname, ".inf") ;

      /* Get basename to compare against; if !boot, get boot option */
      if ( (basename = strrchr(file->name, '.')) != NULL )
        ++basename ;
      else
        basename = file->name ;

      if ( (pcfile = fopen(pcname, "w")) != NULL ) {
        fprintf(pcfile, "%s %06x %06x %06x%s",
                file->name, file->load, file->exec, file->length,
                (file->attrs & FILE_Not_D) ? " Locked" : "") ;
        /* Use qmatch to use case-insensitive comparison */
        if ( qmatch("!boot", basename, -1) ) {
          char buffer[MAXLINELEN] ;

          if ( (result = getbootopt(com, buffer, MAXLINELEN)) == BBC_OK )
            fprintf(pcfile, " OPT4=%s", buffer) ;
        }
        fprintf(pcfile, " ATTR=%x TYPE=%d\n", file->attrs, file->type) ;
        fclose(pcfile) ;
      } else { /* Can't open .inf name, delete downloaded file */
        printf("Problem creating info file %s.inf, skipping\n", file->name) ;
        pcname[strlen(pcname) - 4] = '\0' ;
        remove(pcname) ;
      }
    } else { /* If download failed, remove file */
      remove(pcname) ;
    }
  }

  return result ;
}
Ejemplo n.º 8
0
int readsmv(FILE *streamsmv, FILE *stream_out, casedata *smvcase){
  
  int igrid,ipdim;
  int islice,iplot3d,iboundary;
  char buffer[255];
  mesh *meshinfo=NULL;
  slice *sliceinfo=NULL;
  boundary *boundaryinfo=NULL;
  plot3d *plot3dinfo=NULL;
  int nmeshes, nsliceinfo, nplot3dinfo, nboundary_files;
  int itrnx, itrny, itrnz;

  igrid=0;
  ipdim=0;
  nmeshes=0;
  nsliceinfo=0;
  nplot3dinfo=0;
  nboundary_files=0;
  itrnx=0;
  itrny=0;
  itrnz=0;

  while(!feof(streamsmv)){
    if(fgets(buffer,255,streamsmv)==NULL)break;
    CheckMemory;
    if(strncmp(buffer," ",1)==0)continue;

    if(
      match(buffer,"SLCF") == 1||
      match(buffer,"SLCC") == 1||
      match(buffer,"SLFL") == 1||
      match(buffer,"SLCT") == 1
      ){
      nsliceinfo++;
      continue;
    }
    if(match(buffer,"BNDF") == 1||
       match(buffer,"BNDC") == 1
       ){
      nboundary_files++;
      continue;
    }
    if(
      match(buffer,"PL3D") == 1){
      nplot3dinfo++;
      continue;
    }
    if(match(buffer,"GRID") == 1){
      nmeshes++;
      continue;
    }
    if(match(buffer,"PDIM") == 1){
      ipdim++;
      continue;
    }
  }

  if(nmeshes!=ipdim){
    fprintf(stderr,"*** Error (fatal): number of GRID statements (%i) not equal to\n",nmeshes);
    fprintf(stderr,"                 number of PDIM statements (%i)\n",ipdim);
    exit(0);
  }

  // allocate memory for mesh info

  if(nmeshes>0&&nmeshes==ipdim){
    NewMemory((void **)&meshinfo,nmeshes*sizeof(mesh));
  }
  smvcase->meshinfo = meshinfo;
  smvcase->nmeshes = nmeshes;

  // allocate memory for slice file info

  if(nsliceinfo>0){
    slice *slicei;
    int i;

    NewMemory((void **)&sliceinfo,nsliceinfo*sizeof(slice));
    for(i=0;i<nsliceinfo;i++){
      slicei = sliceinfo + i;
      slicei->file=NULL;
    }
  }
  smvcase->sliceinfo=sliceinfo;
  smvcase->nsliceinfo = nsliceinfo;

  // allocate memory for boundary file info

  if(nboundary_files>0){
    boundary *boundaryi;
    int i;

    NewMemory((void **)&boundaryinfo,nboundary_files*sizeof(boundary));
    for(i=0;i<nboundary_files;i++){
      boundaryi = boundaryinfo + i;
      boundaryi->file=NULL;
    }
  }
  smvcase->boundaryinfo = boundaryinfo;
  smvcase->nboundary_files = nboundary_files;

  // allocate memory for plot3d file info

  if(nplot3dinfo>0){
    NewMemory((void **)&plot3dinfo,nplot3dinfo*sizeof(plot3d));
  }
  smvcase->nplot3dinfo = nplot3dinfo;
  smvcase->plot3dinfo = plot3dinfo;

  islice=0;
  iplot3d=0;
  iboundary=0;
  ipdim=0;
  igrid=0;
  rewind(streamsmv);
  while(!feof(streamsmv)){
    if(fgets(buffer,255,streamsmv)==NULL)break;
    CheckMemory;
    if(stream_out==NULL&&strncmp(buffer," ",1)==0)continue;

  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ GRID ++++++++++++++++++++++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */
    if(match(buffer,"GRID") == 1){
      mesh *meshi;
      float *xp, *yp, *zp;
      int ibar, jbar, kbar;

      meshi=meshinfo+igrid;
      igrid++;
      fgets(buffer,255,streamsmv);
      sscanf(buffer,"%i %i %i",&ibar,&jbar,&kbar);
      NewMemory((void **)&xp,sizeof(float)*(ibar+1));
      NewMemory((void **)&yp,sizeof(float)*(jbar+1));
      NewMemory((void **)&zp,sizeof(float)*(kbar+1));
      meshi->ibar=ibar;
      meshi->jbar=jbar;      
      meshi->kbar=kbar;
      meshi->xplt=xp;
      meshi->yplt=yp;
      meshi->zplt=zp;

      if(stream_out!=NULL){
        trim(buffer);
        fprintf(stream_out,"GRID\n%s\n",buffer);
      }
      
      continue;
    }
  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ PDIM ++++++++++++++++++++++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */
    if(match(buffer,"PDIM") == 1){
      mesh *meshi;

      meshi=meshinfo+ipdim;
      ipdim++;
      fgets(buffer,255,streamsmv);
      sscanf(buffer,"%f %f %f %f %f %f",&meshi->xbar0,&meshi->xbar,&meshi->ybar0,&meshi->ybar,&meshi->zbar0,&meshi->zbar);
      if(stream_out!=NULL){
        trim(buffer);
        fprintf(stream_out,"PDIM\n%s\n",buffer);
      }
      continue;
    }
  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ TRNX ++++++++++++++++++++++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */
    if(match(buffer,"TRNX")==1){
      float *xpltcopy, *xplt;
      int ibar, idummy, nn;
      mesh *meshi;

      if(stream_out!=NULL){
        trim(buffer);
        fprintf(stream_out,"%s\n",buffer);
      }
      itrnx++;
      meshi = meshinfo + itrnx - 1;
      xpltcopy=meshi->xplt;
      xplt = meshi->xplt;

      ibar=meshi->ibar;
      fgets(buffer,255,streamsmv);
      if(stream_out!=NULL){
        trim(buffer);
        fprintf(stream_out,"%s\n",buffer);
      }
      sscanf(buffer,"%i ",&idummy);
      for(nn=0;nn<idummy;nn++){
        fgets(buffer,255,streamsmv);
        if(stream_out!=NULL){
          trim(buffer);
          fprintf(stream_out,"%s\n",buffer);
        }
      }
      for(nn=0;nn<=ibar;nn++){
        fgets(buffer,255,streamsmv);
        if(stream_out!=NULL){
          trim(buffer);
          fprintf(stream_out,"%s\n",buffer);
        }
        sscanf(buffer,"%i %f",&idummy,xpltcopy);
        xpltcopy++;
      }
      meshi->dx=xplt[1]-xplt[0];
      
      continue;
    }
  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ TRNY ++++++++++++++++++++++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */
    if(match(buffer,"TRNY")==1){
      float *ypltcopy, *yplt;
      int jbar, idummy, nn;
      mesh *meshi;

      if(stream_out!=NULL){
        trim(buffer);
        fprintf(stream_out,"%s\n",buffer);
      }
      itrny++;
      meshi = meshinfo + itrny - 1;
      yplt = meshi->yplt;
      ypltcopy=meshi->yplt;
      jbar=meshi->jbar;
      fgets(buffer,255,streamsmv);
      if(stream_out!=NULL){
        trim(buffer);
        fprintf(stream_out,"%s\n",buffer);
      }
      sscanf(buffer,"%i ",&idummy);
      for(nn=0;nn<idummy;nn++){
        fgets(buffer,255,streamsmv);
        if(stream_out!=NULL){
          trim(buffer);
          fprintf(stream_out,"%s\n",buffer);
        }
      }
      for(nn=0;nn<=jbar;nn++){
        fgets(buffer,255,streamsmv);
        if(stream_out!=NULL){
          trim(buffer);
          fprintf(stream_out,"%s\n",buffer);
        }
        sscanf(buffer,"%i %f",&idummy,ypltcopy);
        ypltcopy++;
      }
      meshi->dy=yplt[1]-yplt[0];
      continue;
    }
  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ TRNZ ++++++++++++++++++++++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */
    if(match(buffer,"TRNZ")==1){
      float *zpltcopy,*zplt;
      int kbar, idummy, nn;
      mesh *meshi;

      if(stream_out!=NULL){
        trim(buffer);
        fprintf(stream_out,"%s\n",buffer);
      }
      itrnz++;
      meshi = meshinfo + itrnz - 1;
      zplt = meshi->zplt;
      zpltcopy=meshi->zplt;
      kbar=meshi->kbar;
      fgets(buffer,255,streamsmv);
      if(stream_out!=NULL){
        trim(buffer);
        fprintf(stream_out,"%s\n",buffer);
      }
      sscanf(buffer,"%i ",&idummy);
      for(nn=0;nn<idummy;nn++){
        fgets(buffer,255,streamsmv);
        if(stream_out!=NULL){
          trim(buffer);
          fprintf(stream_out,"%s\n",buffer);
        }
      }
      for(nn=0;nn<=kbar;nn++){
        fgets(buffer,255,streamsmv);
        if(stream_out!=NULL){
          trim(buffer);
          fprintf(stream_out,"%s\n",buffer);
        }
        sscanf(buffer,"%i %f",&idummy,zpltcopy);
        zpltcopy++;
      }
      meshi->dz = zplt[1]-zplt[0];
      continue;
    }
    if(match(buffer,"ENDF") == 1){
      char endian_filename[1024];
      FILE *ENDIANfile;
      int endian=0, endian_native, endian_data, len;

      if(fgets(buffer,255,streamsmv)==NULL)break;
      len=strlen(buffer);
      buffer[len-1]='\0';
      trim(buffer);
      fullfile(endian_filename,smvcase->dir,buffer);
      ENDIANfile = fopen(endian_filename,"rb");
      if(ENDIANfile!=NULL){
        endian_native = getendian();
        FSEEK(ENDIANfile,4,SEEK_SET);
        fread(&endian_data,4,1,ENDIANfile);
        fclose(ENDIANfile);
        endian=endian_native;
        if(endian_data!=1)endian=1-endian_native;
        smvcase->endian=endian;
      }
      if(stream_out!=NULL){
        int lenout;

        make_outfile(endian_filename, NULL, buffer, ".end");
        fprintf(stream_out,"ENDF\n %s\n",endian_filename);
        make_outfile(endian_filename, destdir, buffer, ".end");
        lenout=strlen(endian_filename);
        FORTendianout(endian_filename,lenout);
      }
      continue;
    }
  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ PL3D ++++++++++++++++++++++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */
    if(match(buffer,"PL3D") == 1){
      mesh *plot3dmesh;
      plot3d *plot3di;
      float time_local;
      int meshnumber=1;
      char full_file[1024];
      FILE_SIZE filesize;

      if(strlen(buffer)>4){
        sscanf(buffer+4,"%f %i",&time_local,&meshnumber);
      }

      plot3dmesh = meshinfo + meshnumber - 1;

      plot3di = plot3dinfo + iplot3d;
      plot3di->plot3dmesh=plot3dmesh;
      plot3di->time=time_local;
      trim(buffer);
      strcpy(plot3di->keyword,buffer);

      fgets(buffer,255,streamsmv);
      fullfile(full_file,smvcase->dir,buffer);
      if(getfileinfo(full_file,NULL,&filesize)==0){
        NewMemory((void **)&plot3di->file,(unsigned int)(strlen(full_file)+1));
        NewMemory((void **)&plot3di->histogram[0],sizeof(histogramdata));
        NewMemory((void **)&plot3di->histogram[1],sizeof(histogramdata));
        NewMemory((void **)&plot3di->histogram[2],sizeof(histogramdata));
        NewMemory((void **)&plot3di->histogram[3],sizeof(histogramdata));
        NewMemory((void **)&plot3di->histogram[4],sizeof(histogramdata));
      
        CheckMemory;
        strcpy(plot3di->file,trim_front(buffer));
        CheckMemory;
        if(readlabels(plot3di->labels+0,streamsmv)==2)break;
        if(readlabels(plot3di->labels+1,streamsmv)==2)break;
        if(readlabels(plot3di->labels+2,streamsmv)==2)break;
        if(readlabels(plot3di->labels+3,streamsmv)==2)break;
        if(readlabels(plot3di->labels+4,streamsmv)==2)break;

        CheckMemory;
      
        iplot3d++;
      }
      else{
        if(display_warnings==1)fprintf(stderr,"*** Warning: the file, %s, does not exist.\n",full_file);
        CheckMemory;
        if(readlabels(plot3di->labels+0,streamsmv)==2)break;
        if(readlabels(plot3di->labels+1,streamsmv)==2)break;
        if(readlabels(plot3di->labels+2,streamsmv)==2)break;
        if(readlabels(plot3di->labels+3,streamsmv)==2)break;
        if(readlabels(plot3di->labels+4,streamsmv)==2)break;
        nplot3dinfo--;
        smvcase->nplot3dinfo=nplot3dinfo;
      }
      continue;
    }

  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ SLCF ++++++++++++++++++++++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */
    if(
      match(buffer,"SLCF") == 1||
      match(buffer,"SLCC") == 1||
      match(buffer,"SLFL") == 1||
      match(buffer,"SLCT") == 1)
    {
      int version_local=0;
      int len;
      FILE_SIZE filesize;
      slice *slicei;
      int meshnumber=0;
      mesh *slicemesh;
      char full_file[1024];

      len=strlen(buffer);
      if(len>4){
        sscanf(buffer+4,"%i %i",&meshnumber,&version_local);
      }

      slicei = sliceinfo + islice;

      slicemesh = smvcase->meshinfo+meshnumber-1;
      slicei->slicemesh = slicemesh;
      trim(buffer);

      strcpy(slicei->keyword,buffer);

      if(match(buffer,"SLCF") == 1){
        slicei->slicetype=1;
      }
      if(match(buffer,"SLCC") == 1){
        slicei->slicetype=2;
      }
      if(match(buffer,"SLFL") == 1){
        slicei->slicetype=3;
      }
      if(match(buffer,"SLCT") == 1){
        slicei->slicetype=4;
      }

      slicei->version=version_local;

      if(fgets(buffer,255,streamsmv)==NULL)break;
      trim(buffer);
      if(strlen(buffer)==0)break;
      fullfile(full_file,smvcase->dir,buffer);
      if(getfileinfo(full_file,NULL,&filesize)==0){
        int is1=-1, is2=-1, js1=-1, js2=-1, ks1=-1, ks2=-1;
        int ni, nj, nk;
        int error, lenfile;
        int endian;
        float *xplt, *yplt, *zplt;

        endian=getendian();
        NewMemory((void **)&slicei->file,(unsigned int)(strlen(full_file)+1));
        NewMemory((void **)&slicei->histogram,sizeof(histogramdata));
        STRCPY(slicei->file,trim_front(buffer));
        if(readlabels(&slicei->label,streamsmv)==2){
          fprintf(stderr,"*** Warning: problem reading SLCF entry\n");
          break;
        }
        slicei->filesize=filesize;
        lenfile=strlen(full_file);
        FORTgetsliceparms(full_file,&is1,&is2,&js1,&js2,&ks1,&ks2,&ni,&nj,&nk,&slicei->volslice,&error,lenfile);
        slicei->is1=is1;
        slicei->is2=is2;
        slicei->js1=js1;
        slicei->js2=js2;
        slicei->ks1=ks1;
        slicei->ks2=ks2;
        xplt = slicemesh->xplt;
        yplt = slicemesh->yplt;
        zplt = slicemesh->zplt;
        slicei->xmin = xplt[is1];
        slicei->xmax = xplt[is2];
        slicei->ymin = yplt[js1];
        slicei->ymax = yplt[js2];
        slicei->zmin = zplt[ks1];
        slicei->zmax = zplt[ks2];
        slicei->slice2=NULL;

        islice++;
      }
      else{
        if(display_warnings==1)fprintf(stderr,"*** Warning: the file, %s, does not exist.\n",buffer);
        if(readlabels(&sliceinfo[islice].label,streamsmv)==2)break;
        nsliceinfo--;
        smvcase->nsliceinfo=nsliceinfo;
      }
      continue;
    }
  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ BNDF ++++++++++++++++++++++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */
    if(match(buffer,"BNDF") == 1||
       match(buffer,"BNDC") == 1
       ){
      int version_local=0;
      int len;
      FILE_SIZE filesize;
      boundary *boundaryi;
      int meshnumber=0;
      mesh *boundarymesh;
      char full_file[1024];

      len=strlen(buffer);
      if(len>4){
        sscanf(buffer+4,"%i %i",&meshnumber,&version_local);
      }

      boundaryi = boundaryinfo + iboundary;

      boundarymesh = smvcase->meshinfo+meshnumber-1;
      boundaryi->boundarymesh = boundarymesh;
      trim(buffer);

      strcpy(boundaryi->keyword,buffer);

      boundaryi->version=version_local;

      if(match(buffer,"BNDF") == 1){
        boundaryi->boundarytype=1;
      }
      if(match(buffer,"BNDC") == 1){
        boundaryi->boundarytype=2;
      }

      if(fgets(buffer,255,streamsmv)==NULL)break;
      trim(buffer);
      if(strlen(buffer)==0)break;
      fullfile(full_file,smvcase->dir,buffer);
      if(getfileinfo(full_file,NULL,&filesize)==0){
        int lenfile, endian, npatches, error, boundaryunitnumber;

        NewMemory((void **)&boundaryi->file,(unsigned int)(strlen(full_file)+1));
        NewMemory((void **)&boundaryi->histogram,sizeof(histogramdata));
        STRCPY(boundaryi->file,trim_front(buffer));
        if(readlabels(&boundaryi->label,streamsmv)==2){
          fprintf(stderr,"*** Warning: problem reading BNDF entry\n");
          break;
        }
        boundaryi->filesize=filesize;
        lenfile=strlen(full_file);
        endian=getendian();
        boundaryunitnumber=15;
        FORTgetboundaryheader1(full_file,&boundaryunitnumber, &npatches, &error, lenfile);
        if(npatches>0){
          int *pi1, *pi2, *pj1, *pj2, *pk1, *pk2, *patchdir, *patch2index, *patchsize, *qoffset;
          int i;

          NewMemory((void **)&pi1,npatches*sizeof(int));
          NewMemory((void **)&pi2,npatches*sizeof(int));
          NewMemory((void **)&pj1,npatches*sizeof(int));
          NewMemory((void **)&pj2,npatches*sizeof(int));
          NewMemory((void **)&pk1,npatches*sizeof(int));
          NewMemory((void **)&pk2,npatches*sizeof(int));
          NewMemory((void **)&patchdir,npatches*sizeof(int));
          NewMemory((void **)&patch2index,npatches*sizeof(int));
          NewMemory((void **)&patchsize,npatches*sizeof(int));
          NewMemory((void **)&qoffset,npatches*sizeof(int));
          boundaryi->pi1=pi1;
          boundaryi->pi2=pi2;
          boundaryi->pj1=pj1;
          boundaryi->pj2=pj2;
          boundaryi->pk1=pk1;
          boundaryi->pk2=pk2;
          boundaryi->patchdir=patchdir;
          boundaryi->patch2index=patch2index;
          boundaryi->npatches=npatches;
          boundaryi->patchsize=patchsize;
          boundaryi->qoffset=qoffset;
          FORTgetboundaryheader2(&boundaryunitnumber, &version_local, &npatches, pi1, pi2, pj1, pj2, pk1, pk2, patchdir);
          for(i=0;i<npatches;i++){
            boundaryi->patchsize[i] = (pi2[i]+1-pi1[i])*(pj2[i]+1-pj1[i])*(pk2[i]+1-pk1[i]);
            if(i==0){
              boundaryi->qoffset[i]=0;
            }
            else{
              boundaryi->qoffset[i]=boundaryi->qoffset[i-1]+boundaryi->patchsize[i-1];
            }
          }
          CheckMemory;
       }

        boundaryi->boundary2=NULL;

        iboundary++;
      }
      else{
        fprintf(stderr,"*** Warning: the file, %s, does not exist.\n",buffer);
        if(readlabels(&boundaryinfo[iboundary].label,streamsmv)==2)break;
        nboundary_files--;
        smvcase->nboundary_files=nboundary_files;
      }
      continue;
    }

  /*
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ++++++++++++++++++++++ vis keywords not differenced++++++++++
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  */

    // skip over the following keywords

    if(
       match(buffer,"ISOF") == 1||
       match(buffer,"ISOG") == 1||
       match(buffer,"TISOF")==1||
       match(buffer,"SMOKE3D")==1||
       match(buffer,"SMOKF3D")==1||
       match(buffer,"VSMOKF3D")==1||
       match(buffer,"PART")==1||
       match(buffer,"EVAC")==1||
       match(buffer,"PRT5")==1||
       match(buffer,"EVA5")==1
       ){
      char comm[1024];

      strcpy(comm,buffer);
      fgets(buffer,255,streamsmv);
      if(match(comm,"PRT5")==1||match(comm,"EVA5")==1){
        int i, nlines;

        fgets(buffer,255,streamsmv);
        sscanf(buffer,"%i",&nlines);
        for(i=0;i<nlines;i++){
          fgets(buffer,255,streamsmv);
        }
      }
      else{
        fgets(buffer,255,streamsmv);
        fgets(buffer,255,streamsmv);
        fgets(buffer,255,streamsmv);
      }
      if(match(comm,"TISOF")==1){
        int i;

        for(i=0;i<3;i++){
          fgets(buffer,255,streamsmv);
        }
      }
      continue;
    }
    if(stream_out!=NULL){
      trim(buffer);
      fprintf(stream_out,"%s\n",buffer);
    }
    continue;
  }
  if(stream_out!=NULL){
    fprintf(stream_out,"SMOKEDIFF\n");
  }
  return 0;
}
Ejemplo n.º 9
0
/******************************************************** Main Function **************************************************/
int main (int argc, char **argv)
{
	//inputs
	FILE *f_src; //source file pointer
	FILE *f_src_ctr; //source center file
	//outputs
	FILE *f_cid; //cluster-id file pointer
	FILE *f_mfi; //added April 16, 2009
	

	char name_string[LINE_LEN]; //for name use

	int time_id=-1;

	long file_Len=0;
	long num_clust=0;
	long num_dm=0;
	long norm_used=0;
	long dist_used=0;
	long i=0;
	long j=0;

	long *cluster_id;
	long *IDmapping; //this is to keep the original populationID of the center.txt

	double kmean_term=0;
	
	double **cluster_center;
	double **orig_data;
	double **normalized_data;
		
/*
	_strtime( tmpbuf );
    printf( "Starting time:\t\t\t\t%s\n", tmpbuf );
	_strdate( tmpbuf );
    printf( "Starting date:\t\t\t\t%s\n", tmpbuf );
*/

	if (argc!=3)
	{
		//modified on July 23, 2010
		fprintf(stderr, "usage: cent_adjust input_center input_data_file\n");       
		abort();
	}	
	

	f_src_ctr=fopen(argv[1],"r");	
	
	//read source data
	f_src=fopen(argv[2],"r");
	
	getfileinfo(f_src, &file_Len, &num_dm, name_string, &time_id); //get the filelength, number of dimensions, and num/name of parameters

	rewind(f_src); //reset data file pointer	

	orig_data = (double **)malloc(sizeof(double*)*file_Len);
	memset(orig_data,0,sizeof(double*)*file_Len);
	for (i=0;i<file_Len;i++)
	{
		orig_data[i]=(double *)malloc(sizeof(double)*num_dm);
		memset(orig_data[i],0,sizeof(double)*num_dm);
	}
	
	readsource(f_src, file_Len, num_dm, orig_data, time_id); //read the data;
	
	fclose(f_src);
	/////////////////////////////////////////////////////////////////////////////
	getctrfileinfo(f_src_ctr, &num_clust); //get how many populations
	norm_used=0;
	dist_used=0;
	kmean_term=3;  //modified on Oct 16, 2009: changed kmean_term=1 to kmean_term=2

	rewind(f_src_ctr); //reset center file pointer

	//read population center
	cluster_center=(double **)malloc(sizeof(double*)*num_clust);
	memset(cluster_center,0,sizeof(double*)*num_clust);
	for (i=0;i<num_clust;i++)
	{
		cluster_center[i]=(double*)malloc(sizeof(double)*num_dm);
		memset(cluster_center[i],0,sizeof(double)*num_dm);
	}
	for (i=0;i<num_clust;i++)
		for (j=0;j<num_dm;j++)
			cluster_center[i][j]=0;

	IDmapping=(long *)malloc(sizeof(long)*num_clust);
	memset(IDmapping,0,sizeof(long)*num_clust);

	readcenter(f_src_ctr,num_clust,num_dm,cluster_center,IDmapping); //read population center
    fclose(f_src_ctr);

	/////////////////////////////////////////////////////////////////////////////
	normalized_data=(double **)malloc(sizeof(double*)*file_Len);
	memset(normalized_data,0,sizeof(double*)*file_Len);
	for (i=0;i<file_Len;i++)
	{
		normalized_data[i]=(double *)malloc(sizeof(double)*num_dm);
		memset(normalized_data[i],0,sizeof(double)*num_dm);
	}
	
	tran(orig_data, file_Len, num_dm, norm_used, normalized_data);
	/************************************************* Compute number of clusters *************************************************/
	
	cluster_id=(long*)malloc(sizeof(long)*file_Len);
	memset(cluster_id,0,sizeof(long)*file_Len);

	assign_event(normalized_data,num_clust,dist_used,kmean_term,file_Len,num_dm,cluster_id,cluster_center,0);

	
	//show(orig_data,cluster_id,file_Len,num_clust,num_dm,show_data,num_disp,name_string); 
	show(orig_data, cluster_id, file_Len, num_clust, num_dm, name_string, IDmapping);

	f_cid=fopen("population_id.txt","w");

	for (i=0;i<file_Len;i++)
		fprintf(f_cid,"%d\n",IDmapping[cluster_id[i]]);
		

	fclose(f_cid);
 
	//added April 16, 2009
	f_mfi=fopen("MFI.txt","w");

	for (i=0;i<num_clust;i++)
	{
		fprintf(f_mfi,"%d\t",IDmapping[i]);

		for (j=0;j<num_dm;j++)
		{
			if (j==num_dm-1)
				fprintf(f_mfi,"%.0f\n",cluster_center[i][j]);
			else
				fprintf(f_mfi,"%.0f\t",cluster_center[i][j]);
		}
	}
	fclose(f_mfi);

	//ended April 16, 2009

	for (i=0;i<num_clust;i++)
		free(cluster_center[i]);
	free(cluster_center);
		

	/********************************************** Release memory ******************************************/
  
	for (i=0;i<file_Len;i++)
	{
		free(orig_data[i]);		
		free(normalized_data[i]);
	}
	
	free(orig_data);
	free(normalized_data);
	free(cluster_id);
	free(IDmapping);

/*
	_strtime( tmpbuf );
    printf( "Ending time:\t\t\t\t%s\n", tmpbuf );
	_strdate( tmpbuf );
    printf( "Ending date:\t\t\t\t%s\n", tmpbuf );
*/

}
Ejemplo n.º 10
0
int
fileutils___getfileinfo(char *filename, int *i)
{
    return(getfileinfo(filename, i));
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
  int ch, option_index;
  int infd, inwd;
  int res, ret, status;
  const char *command, *path;
  struct fileinfo hints, *info, *p;
  fd_set fds;
  sigset_t sigmask, empty_mask;
  struct sigaction sa;
  const struct inotify_event *event;
  char buf[BUFFER_SIZE]
    __attribute__((aligned(__alignof__(struct inotify_event))));
  char *iter;
  ssize_t len;
  pid_t pid;
  char *env[2];

  static struct option options[] = {
    { "help",      no_argument, &help_flag,      1 },
    { "version",   no_argument, &version_flag,   1 },
    { "recursive", no_argument, &recursive_flag, 1 },
    { 0, 0, 0, 0 }
  };

  ret = EXIT_FAILURE;

  while (1) {
    option_index = 0;
    ch = getopt_long(argc, argv, "hvr", options, &option_index);

    if (ch == -1)
      break;

    switch (ch) {
    case 0:
      if (options[option_index].flag != 0)
        break;
      printf("option %s\n", options[option_index].name);
      break;

    case 'h':
      help_flag = 1;
      break;

    case 'v':
      version_flag = 1;
      break;

    case 'r':
      recursive_flag = 1;
      break;
    }
  }

  if (version_flag) {
    printf("%s\n", PACKAGE_STRING);
    ret = EXIT_SUCCESS;
    goto done;
  }

  if (help_flag || (optind + 1) >= argc) {
    printf("Usage: watchtower [options] <command> <dir>\n");
    printf("\n");
    printf("Run a shell script in response to filesystem events.\n");
    printf("\n");
    printf("Examples:\n");
    printf("  watchtower 'echo $F' /home/user  # prints any filenames modified under "
           "/home/user\n");
    printf("\n");
    printf("Available options:\n");
    printf("  -h, --help       print this message\n");
    printf("  -v, --version    print program version\n");
    printf("  -r, --recursive  set program to watch entire subtree\n");
    ret = EXIT_SUCCESS;
    goto done;
  }

  if (recursive_flag)
    fprintf(stderr, "WARNING: recursive mode is not yet implemented\n");

  command = argv[optind++];
  path = argv[optind];

  memset(&hints, 0, sizeof(struct fileinfo));
  hints.fi_type = DT_DIR;

  if ((res = getfileinfo(path, &hints, &info)) != 0) {
    fprintf(stderr, "getfileinfo: %s\n", gfi_strerror(res));
    goto done;
  }

  infd = inotify_init();

  for (p = info; p; p = p->fi_next) {
    if (strcmp(p->fi_name, "..") == 0)
      continue;

    if (strcmp(p->fi_name, ".") == 0)
      inwd = inotify_add_watch(infd, p->fi_path, IN_MODIFY);
  }

  freefileinfo(info);

  sigemptyset(&sigmask);
  sigaddset(&sigmask, SIGINT);
  sigprocmask(SIG_BLOCK, &sigmask, NULL);

  sa.sa_flags = 0;
  sa.sa_handler = interrupt_handler;
  sigemptyset(&sa.sa_mask);
  sigaction(SIGINT, &sa, NULL);

  sigemptyset(&empty_mask);

  for (;;) {
    FD_ZERO(&fds);
    FD_SET(infd, &fds);

    pselect(infd + 1, &fds, NULL, NULL, NULL, &empty_mask);

    if (got_SIGINT) {
      printf("\ncleaning up...\n");
      break;
    }

    len = read(infd, buf, BUFFER_SIZE);

    for (iter = buf; iter < buf + len;
         iter += sizeof(struct inotify_event) + event->len) {
      event = (const struct inotify_event *)iter;

      if (event->mask & IN_MODIFY) {
        pid = fork();

        switch (pid) {
        case -1:
          fprintf(stderr, "forking failed\n");
          break;

        case 0:
          env[0] = malloc(strlen(event->name) + 3);
          sprintf(env[0], "F=%s", event->name);
          env[1] = NULL;
          execle("/bin/sh", "sh", "-c", command, (char *)NULL, env);
          free(env[0]);
          ret = EXIT_SUCCESS;
          goto done;

        default:
          fflush(NULL);
          if (waitpid(pid, &status, 0) == -1)
            fprintf(stderr, "child process failed\n");
          break;
        }
      }
    }
  }

  inotify_rm_watch(infd, inwd);
  close(infd);

  ret = EXIT_SUCCESS;

 done:
  return ret;
}